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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import TYPE_CHECKING
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import yaml
|
| 6 |
+
from toolkit.config_modules import GenerateImageConfig, ModelConfig
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from toolkit.models.base_model import BaseModel
|
| 9 |
+
from toolkit.basic import flush
|
| 10 |
+
from diffusers import AutoencoderKL
|
| 11 |
+
from toolkit.prompt_utils import PromptEmbeds
|
| 12 |
+
from toolkit.samplers.custom_flowmatch_sampler import CustomFlowMatchEulerDiscreteScheduler
|
| 13 |
+
from toolkit.dequantize import patch_dequantization_on_save
|
| 14 |
+
from toolkit.accelerator import unwrap_model
|
| 15 |
+
from optimum.quanto import freeze, QTensor
|
| 16 |
+
from toolkit.util.quantize import quantize, get_qtype
|
| 17 |
+
from transformers import T5TokenizerFast, T5EncoderModel
|
| 18 |
+
from .src import FLitePipeline, DiT
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from toolkit.data_transfer_object.data_loader import DataLoaderBatchDTO
|
| 22 |
+
|
| 23 |
+
scheduler_config = {
|
| 24 |
+
"base_image_seq_len": 256,
|
| 25 |
+
"base_shift": 0.5,
|
| 26 |
+
"max_image_seq_len": 4096,
|
| 27 |
+
"max_shift": 1.15,
|
| 28 |
+
"num_train_timesteps": 1000,
|
| 29 |
+
"shift": 3.0,
|
| 30 |
+
"use_dynamic_shifting": True
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class FLiteModel(BaseModel):
|
| 35 |
+
arch = "f-lite"
|
| 36 |
+
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
device,
|
| 40 |
+
model_config: ModelConfig,
|
| 41 |
+
dtype='bf16',
|
| 42 |
+
custom_pipeline=None,
|
| 43 |
+
noise_scheduler=None,
|
| 44 |
+
**kwargs
|
| 45 |
+
):
|
| 46 |
+
super().__init__(
|
| 47 |
+
device,
|
| 48 |
+
model_config,
|
| 49 |
+
dtype,
|
| 50 |
+
custom_pipeline,
|
| 51 |
+
noise_scheduler,
|
| 52 |
+
**kwargs
|
| 53 |
+
)
|
| 54 |
+
self.is_flow_matching = True
|
| 55 |
+
self.is_transformer = True
|
| 56 |
+
self.target_lora_modules = ['DiT']
|
| 57 |
+
|
| 58 |
+
# static method to get the noise scheduler
|
| 59 |
+
@staticmethod
|
| 60 |
+
def get_train_scheduler():
|
| 61 |
+
return CustomFlowMatchEulerDiscreteScheduler(**scheduler_config)
|
| 62 |
+
|
| 63 |
+
def get_bucket_divisibility(self):
|
| 64 |
+
# return the bucket divisibility for the model
|
| 65 |
+
return 16
|
| 66 |
+
|
| 67 |
+
def load_model(self):
|
| 68 |
+
dtype = self.torch_dtype
|
| 69 |
+
|
| 70 |
+
# will be updated if we detect a existing checkpoint in training folder
|
| 71 |
+
model_path = self.model_config.name_or_path
|
| 72 |
+
|
| 73 |
+
extras_path = self.model_config.extras_name_or_path
|
| 74 |
+
|
| 75 |
+
self.print_and_status_update("Loading transformer")
|
| 76 |
+
|
| 77 |
+
transformer = DiT.from_pretrained(
|
| 78 |
+
model_path,
|
| 79 |
+
subfolder="dit_model",
|
| 80 |
+
torch_dtype=dtype,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
transformer.to(self.quantize_device, dtype=dtype)
|
| 84 |
+
|
| 85 |
+
if self.model_config.quantize:
|
| 86 |
+
# patch the state dict method
|
| 87 |
+
patch_dequantization_on_save(transformer)
|
| 88 |
+
quantization_type = get_qtype(self.model_config.qtype)
|
| 89 |
+
self.print_and_status_update("Quantizing transformer")
|
| 90 |
+
quantize(transformer, weights=quantization_type,
|
| 91 |
+
**self.model_config.quantize_kwargs)
|
| 92 |
+
freeze(transformer)
|
| 93 |
+
transformer.to(self.device_torch)
|
| 94 |
+
else:
|
| 95 |
+
transformer.to(self.device_torch, dtype=dtype)
|
| 96 |
+
|
| 97 |
+
flush()
|
| 98 |
+
|
| 99 |
+
self.print_and_status_update("Loading T5")
|
| 100 |
+
tokenizer = T5TokenizerFast.from_pretrained(
|
| 101 |
+
extras_path, subfolder="tokenizer", torch_dtype=dtype
|
| 102 |
+
)
|
| 103 |
+
text_encoder = T5EncoderModel.from_pretrained(
|
| 104 |
+
extras_path, subfolder="text_encoder", torch_dtype=dtype
|
| 105 |
+
)
|
| 106 |
+
text_encoder.to(self.device_torch, dtype=dtype)
|
| 107 |
+
flush()
|
| 108 |
+
|
| 109 |
+
if self.model_config.quantize_te:
|
| 110 |
+
self.print_and_status_update("Quantizing T5")
|
| 111 |
+
quantize(text_encoder, weights=get_qtype(
|
| 112 |
+
self.model_config.qtype))
|
| 113 |
+
freeze(text_encoder)
|
| 114 |
+
flush()
|
| 115 |
+
|
| 116 |
+
self.noise_scheduler = FLiteModel.get_train_scheduler()
|
| 117 |
+
|
| 118 |
+
self.print_and_status_update("Loading VAE")
|
| 119 |
+
vae = AutoencoderKL.from_pretrained(
|
| 120 |
+
extras_path,
|
| 121 |
+
subfolder="vae",
|
| 122 |
+
torch_dtype=dtype
|
| 123 |
+
)
|
| 124 |
+
vae = vae.to(self.device_torch, dtype=dtype)
|
| 125 |
+
|
| 126 |
+
self.print_and_status_update("Making pipe")
|
| 127 |
+
|
| 128 |
+
pipe: FLitePipeline = FLitePipeline(
|
| 129 |
+
text_encoder=None,
|
| 130 |
+
tokenizer=tokenizer,
|
| 131 |
+
vae=vae,
|
| 132 |
+
dit_model=None,
|
| 133 |
+
)
|
| 134 |
+
# for quantization, it works best to do these after making the pipe
|
| 135 |
+
pipe.text_encoder = text_encoder
|
| 136 |
+
pipe.dit_model = transformer
|
| 137 |
+
pipe.transformer = transformer
|
| 138 |
+
pipe.scheduler = self.noise_scheduler,
|
| 139 |
+
|
| 140 |
+
self.print_and_status_update("Preparing Model")
|
| 141 |
+
|
| 142 |
+
text_encoder = [pipe.text_encoder]
|
| 143 |
+
tokenizer = [pipe.tokenizer]
|
| 144 |
+
|
| 145 |
+
pipe.transformer = pipe.transformer.to(self.device_torch)
|
| 146 |
+
|
| 147 |
+
flush()
|
| 148 |
+
# just to make sure everything is on the right device and dtype
|
| 149 |
+
text_encoder[0].to(self.device_torch)
|
| 150 |
+
text_encoder[0].requires_grad_(False)
|
| 151 |
+
text_encoder[0].eval()
|
| 152 |
+
pipe.transformer = pipe.transformer.to(self.device_torch)
|
| 153 |
+
flush()
|
| 154 |
+
|
| 155 |
+
# save it to the model class
|
| 156 |
+
self.vae = vae
|
| 157 |
+
self.text_encoder = text_encoder # list of text encoders
|
| 158 |
+
self.tokenizer = tokenizer # list of tokenizers
|
| 159 |
+
self.model = pipe.transformer
|
| 160 |
+
self.pipeline = pipe
|
| 161 |
+
self.print_and_status_update("Model Loaded")
|
| 162 |
+
|
| 163 |
+
def get_generation_pipeline(self):
|
| 164 |
+
scheduler = FLiteModel.get_train_scheduler()
|
| 165 |
+
# it has built in scheduler. Basically euler flowmatching
|
| 166 |
+
pipeline = FLitePipeline(
|
| 167 |
+
text_encoder=unwrap_model(self.text_encoder[0]),
|
| 168 |
+
tokenizer=self.tokenizer[0],
|
| 169 |
+
vae=unwrap_model(self.vae),
|
| 170 |
+
dit_model=unwrap_model(self.transformer)
|
| 171 |
+
)
|
| 172 |
+
pipeline.transformer = pipeline.dit_model
|
| 173 |
+
pipeline.scheduler = scheduler
|
| 174 |
+
|
| 175 |
+
return pipeline
|
| 176 |
+
|
| 177 |
+
def generate_single_image(
|
| 178 |
+
self,
|
| 179 |
+
pipeline: FLitePipeline,
|
| 180 |
+
gen_config: GenerateImageConfig,
|
| 181 |
+
conditional_embeds: PromptEmbeds,
|
| 182 |
+
unconditional_embeds: PromptEmbeds,
|
| 183 |
+
generator: torch.Generator,
|
| 184 |
+
extra: dict,
|
| 185 |
+
):
|
| 186 |
+
|
| 187 |
+
extra['negative_prompt_embeds'] = unconditional_embeds.text_embeds
|
| 188 |
+
|
| 189 |
+
img = pipeline(
|
| 190 |
+
prompt_embeds=conditional_embeds.text_embeds,
|
| 191 |
+
negative_prompt_embeds=unconditional_embeds.text_embeds,
|
| 192 |
+
height=gen_config.height,
|
| 193 |
+
width=gen_config.width,
|
| 194 |
+
num_inference_steps=gen_config.num_inference_steps,
|
| 195 |
+
guidance_scale=gen_config.guidance_scale,
|
| 196 |
+
latents=gen_config.latents,
|
| 197 |
+
generator=generator,
|
| 198 |
+
).images[0]
|
| 199 |
+
return img
|
| 200 |
+
|
| 201 |
+
def get_noise_prediction(
|
| 202 |
+
self,
|
| 203 |
+
latent_model_input: torch.Tensor,
|
| 204 |
+
timestep: torch.Tensor, # 0 to 1000 scale
|
| 205 |
+
text_embeddings: PromptEmbeds,
|
| 206 |
+
**kwargs
|
| 207 |
+
):
|
| 208 |
+
cast_dtype = self.unet.dtype
|
| 209 |
+
|
| 210 |
+
noise_pred = self.unet(
|
| 211 |
+
latent_model_input.to(
|
| 212 |
+
self.device_torch, cast_dtype
|
| 213 |
+
),
|
| 214 |
+
text_embeddings.text_embeds.to(
|
| 215 |
+
self.device_torch, cast_dtype
|
| 216 |
+
),
|
| 217 |
+
timestep / 1000,
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
if isinstance(noise_pred, QTensor):
|
| 221 |
+
noise_pred = noise_pred.dequantize()
|
| 222 |
+
|
| 223 |
+
return noise_pred
|
| 224 |
+
|
| 225 |
+
def get_prompt_embeds(self, prompt: str) -> PromptEmbeds:
|
| 226 |
+
if isinstance(prompt, str):
|
| 227 |
+
prompts = [prompt]
|
| 228 |
+
else:
|
| 229 |
+
prompts = prompt
|
| 230 |
+
if self.pipeline.text_encoder.device != self.device_torch:
|
| 231 |
+
self.pipeline.text_encoder.to(self.device_torch)
|
| 232 |
+
|
| 233 |
+
prompt_embeds, negative_embeds = self.pipeline.encode_prompt(
|
| 234 |
+
prompt=prompts,
|
| 235 |
+
negative_prompt=None,
|
| 236 |
+
device=self.text_encoder[0].device,
|
| 237 |
+
dtype=self.torch_dtype,
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
pe = PromptEmbeds(prompt_embeds)
|
| 241 |
+
|
| 242 |
+
return pe
|
| 243 |
+
|
| 244 |
+
def get_model_has_grad(self):
|
| 245 |
+
# return from a weight if it has grad
|
| 246 |
+
return False
|
| 247 |
+
|
| 248 |
+
def get_te_has_grad(self):
|
| 249 |
+
# return from a weight if it has grad
|
| 250 |
+
return False
|
| 251 |
+
|
| 252 |
+
def save_model(self, output_path, meta, save_dtype):
|
| 253 |
+
# only save the unet
|
| 254 |
+
transformer: DiT = unwrap_model(self.model)
|
| 255 |
+
# diffusers
|
| 256 |
+
# only save the unet
|
| 257 |
+
transformer: DiT = unwrap_model(self.transformer)
|
| 258 |
+
transformer.save_pretrained(
|
| 259 |
+
save_directory=os.path.join(output_path, 'dit_model'),
|
| 260 |
+
safe_serialization=True,
|
| 261 |
+
)
|
| 262 |
+
# save out meta config
|
| 263 |
+
meta_path = os.path.join(output_path, 'aitk_meta.yaml')
|
| 264 |
+
with open(meta_path, 'w') as f:
|
| 265 |
+
yaml.dump(meta, f)
|
| 266 |
+
|
| 267 |
+
def get_loss_target(self, *args, **kwargs):
|
| 268 |
+
noise = kwargs.get('noise')
|
| 269 |
+
batch = kwargs.get('batch')
|
| 270 |
+
# return (noise - batch.latents).detach()
|
| 271 |
+
return (batch.latents - noise).detach()
|
| 272 |
+
|
| 273 |
+
def convert_lora_weights_before_save(self, state_dict):
|
| 274 |
+
# currently starte with transformer. but needs to start with diffusion_model. for comfyui
|
| 275 |
+
new_sd = {}
|
| 276 |
+
for key, value in state_dict.items():
|
| 277 |
+
new_key = key.replace("transformer.", "diffusion_model.")
|
| 278 |
+
new_sd[new_key] = value
|
| 279 |
+
return new_sd
|
| 280 |
+
|
| 281 |
+
def convert_lora_weights_before_load(self, state_dict):
|
| 282 |
+
# saved as diffusion_model. but needs to be transformer. for ai-toolkit
|
| 283 |
+
new_sd = {}
|
| 284 |
+
for key, value in state_dict.items():
|
| 285 |
+
new_key = key.replace("diffusion_model.", "transformer.")
|
| 286 |
+
new_sd[new_key] = value
|
| 287 |
+
return new_sd
|
| 288 |
+
|
| 289 |
+
def get_base_model_version(self):
|
| 290 |
+
return "f-lite"
|
| 291 |
+
|
| 292 |
+
def get_stepped_pred(self, pred, noise):
|
| 293 |
+
# just used for DFE support
|
| 294 |
+
latents = pred + noise
|
| 295 |
+
return latents
|