windsingai commited on
Commit
7086891
·
verified ·
1 Parent(s): dd26514

Upload flux_kontext.py

Browse files
Files changed (1) hide show
  1. flux_kontext.py +436 -0
flux_kontext.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import TYPE_CHECKING, List
3
+
4
+ import torch
5
+ import torchvision
6
+ import yaml
7
+ from toolkit import train_tools
8
+ from toolkit.config_modules import GenerateImageConfig, ModelConfig
9
+ from PIL import Image
10
+ from toolkit.models.base_model import BaseModel
11
+ from diffusers import FluxTransformer2DModel, AutoencoderKL, FluxKontextPipeline
12
+ from toolkit.basic import flush
13
+ from toolkit.prompt_utils import PromptEmbeds
14
+ from toolkit.samplers.custom_flowmatch_sampler import CustomFlowMatchEulerDiscreteScheduler
15
+ from toolkit.models.flux import add_model_gpu_splitter_to_flux, bypass_flux_guidance, restore_flux_guidance
16
+ from toolkit.dequantize import patch_dequantization_on_save
17
+ from toolkit.accelerator import get_accelerator, unwrap_model
18
+ from optimum.quanto import freeze, QTensor
19
+ from toolkit.util.mask import generate_random_mask, random_dialate_mask
20
+ from toolkit.util.quantize import quantize, get_qtype
21
+ from transformers import T5TokenizerFast, T5EncoderModel, CLIPTextModel, CLIPTokenizer
22
+ from einops import rearrange, repeat
23
+ import random
24
+ import torch.nn.functional as F
25
+
26
+ if TYPE_CHECKING:
27
+ from toolkit.data_transfer_object.data_loader import DataLoaderBatchDTO
28
+
29
+ scheduler_config = {
30
+ "base_image_seq_len": 256,
31
+ "base_shift": 0.5,
32
+ "max_image_seq_len": 4096,
33
+ "max_shift": 1.15,
34
+ "num_train_timesteps": 1000,
35
+ "shift": 3.0,
36
+ "use_dynamic_shifting": True
37
+ }
38
+
39
+
40
+
41
+ class FluxKontextModel(BaseModel):
42
+ arch = "flux_kontext"
43
+
44
+ def __init__(
45
+ self,
46
+ device,
47
+ model_config: ModelConfig,
48
+ dtype='bf16',
49
+ custom_pipeline=None,
50
+ noise_scheduler=None,
51
+ **kwargs
52
+ ):
53
+ super().__init__(
54
+ device,
55
+ model_config,
56
+ dtype,
57
+ custom_pipeline,
58
+ noise_scheduler,
59
+ **kwargs
60
+ )
61
+ self.is_flow_matching = True
62
+ self.is_transformer = True
63
+ self.target_lora_modules = ['FluxTransformer2DModel']
64
+
65
+ # static method to get the noise scheduler
66
+ @staticmethod
67
+ def get_train_scheduler():
68
+ return CustomFlowMatchEulerDiscreteScheduler(**scheduler_config)
69
+
70
+ def get_bucket_divisibility(self):
71
+ return 16
72
+
73
+ def load_model(self):
74
+ dtype = self.torch_dtype
75
+ self.print_and_status_update("Loading Flux Kontext model")
76
+ # will be updated if we detect a existing checkpoint in training folder
77
+ model_path = self.model_config.name_or_path
78
+ # this is the original path put in the model directory
79
+ # it is here because for finetuning we only save the transformer usually
80
+ # so we need this for the VAE, te, etc
81
+ base_model_path = self.model_config.extras_name_or_path
82
+
83
+ transformer_path = model_path
84
+ transformer_subfolder = 'transformer'
85
+
86
+ # Check if model_path is a .safetensors file
87
+ if model_path.endswith('.safetensors'):
88
+ # Load transformer from safetensors file
89
+ self.print_and_status_update("Loading transformer from safetensors file")
90
+ from safetensors.torch import load_file
91
+ from diffusers.models.transformers.transformer_flux import FluxTransformer2DModel
92
+
93
+ # Load the config from base model (extras_name_or_path)
94
+ transformer_config_path = os.path.join(base_model_path, 'transformer', 'config.json')
95
+ if not os.path.exists(transformer_config_path):
96
+ # Fallback to downloading config from HF
97
+ transformer = FluxTransformer2DModel.from_pretrained(
98
+ "black-forest-labs/FLUX.1-dev",
99
+ subfolder="transformer",
100
+ torch_dtype=dtype
101
+ )
102
+ else:
103
+ transformer = FluxTransformer2DModel.from_pretrained(
104
+ base_model_path,
105
+ subfolder="transformer",
106
+ torch_dtype=dtype
107
+ )
108
+
109
+ # Load the weights from safetensors file
110
+ state_dict = load_file(model_path)
111
+ transformer.load_state_dict(state_dict, strict=False)
112
+ else:
113
+ # Original logic for directory-based models
114
+ if os.path.exists(transformer_path):
115
+ transformer_subfolder = None
116
+ transformer_path = os.path.join(transformer_path, 'transformer')
117
+ # check if the path is a full checkpoint.
118
+ te_folder_path = os.path.join(model_path, 'text_encoder')
119
+ # if we have the te, this folder is a full checkpoint, use it as the base
120
+ if os.path.exists(te_folder_path):
121
+ base_model_path = model_path
122
+
123
+ self.print_and_status_update("Loading transformer")
124
+ transformer = FluxTransformer2DModel.from_pretrained(
125
+ transformer_path,
126
+ subfolder=transformer_subfolder,
127
+ torch_dtype=dtype
128
+ )
129
+ transformer.to(self.quantize_device, dtype=dtype)
130
+
131
+ if self.model_config.quantize:
132
+ # patch the state dict method
133
+ patch_dequantization_on_save(transformer)
134
+ quantization_type = get_qtype(self.model_config.qtype)
135
+ self.print_and_status_update("Quantizing transformer")
136
+ quantize(transformer, weights=quantization_type,
137
+ **self.model_config.quantize_kwargs)
138
+ freeze(transformer)
139
+ transformer.to(self.device_torch)
140
+ else:
141
+ transformer.to(self.device_torch, dtype=dtype)
142
+
143
+ flush()
144
+
145
+ self.print_and_status_update("Loading T5")
146
+ tokenizer_2 = T5TokenizerFast.from_pretrained(
147
+ base_model_path, subfolder="tokenizer_2", torch_dtype=dtype
148
+ )
149
+ text_encoder_2 = T5EncoderModel.from_pretrained(
150
+ base_model_path, subfolder="text_encoder_2", torch_dtype=dtype
151
+ )
152
+ text_encoder_2.to(self.device_torch, dtype=dtype)
153
+ flush()
154
+
155
+ if self.model_config.quantize_te:
156
+ self.print_and_status_update("Quantizing T5")
157
+ quantize(text_encoder_2, weights=get_qtype(
158
+ self.model_config.qtype))
159
+ freeze(text_encoder_2)
160
+ flush()
161
+
162
+ self.print_and_status_update("Loading CLIP")
163
+ text_encoder = CLIPTextModel.from_pretrained(
164
+ base_model_path, subfolder="text_encoder", torch_dtype=dtype)
165
+ tokenizer = CLIPTokenizer.from_pretrained(
166
+ base_model_path, subfolder="tokenizer", torch_dtype=dtype)
167
+ text_encoder.to(self.device_torch, dtype=dtype)
168
+
169
+ self.print_and_status_update("Loading VAE")
170
+ vae = AutoencoderKL.from_pretrained(
171
+ base_model_path, subfolder="vae", torch_dtype=dtype)
172
+
173
+ self.noise_scheduler = FluxKontextModel.get_train_scheduler()
174
+
175
+ self.print_and_status_update("Making pipe")
176
+
177
+ pipe: FluxKontextPipeline = FluxKontextPipeline(
178
+ scheduler=self.noise_scheduler,
179
+ text_encoder=text_encoder,
180
+ tokenizer=tokenizer,
181
+ text_encoder_2=None,
182
+ tokenizer_2=tokenizer_2,
183
+ vae=vae,
184
+ transformer=None,
185
+ )
186
+ # for quantization, it works best to do these after making the pipe
187
+ pipe.text_encoder_2 = text_encoder_2
188
+ pipe.transformer = transformer
189
+
190
+ self.print_and_status_update("Preparing Model")
191
+
192
+ text_encoder = [pipe.text_encoder, pipe.text_encoder_2]
193
+ tokenizer = [pipe.tokenizer, pipe.tokenizer_2]
194
+
195
+ pipe.transformer = pipe.transformer.to(self.device_torch)
196
+
197
+ flush()
198
+ # just to make sure everything is on the right device and dtype
199
+ text_encoder[0].to(self.device_torch)
200
+ text_encoder[0].requires_grad_(False)
201
+ text_encoder[0].eval()
202
+ text_encoder[1].to(self.device_torch)
203
+ text_encoder[1].requires_grad_(False)
204
+ text_encoder[1].eval()
205
+ pipe.transformer = pipe.transformer.to(self.device_torch)
206
+ flush()
207
+
208
+ # save it to the model class
209
+ self.vae = vae
210
+ self.text_encoder = text_encoder # list of text encoders
211
+ self.tokenizer = tokenizer # list of tokenizers
212
+ self.model = pipe.transformer
213
+ self.pipeline = pipe
214
+ self.print_and_status_update("Model Loaded")
215
+
216
+ def get_generation_pipeline(self):
217
+ scheduler = FluxKontextModel.get_train_scheduler()
218
+
219
+ pipeline: FluxKontextPipeline = FluxKontextPipeline(
220
+ scheduler=scheduler,
221
+ text_encoder=unwrap_model(self.text_encoder[0]),
222
+ tokenizer=self.tokenizer[0],
223
+ text_encoder_2=unwrap_model(self.text_encoder[1]),
224
+ tokenizer_2=self.tokenizer[1],
225
+ vae=unwrap_model(self.vae),
226
+ transformer=unwrap_model(self.transformer)
227
+ )
228
+
229
+ pipeline = pipeline.to(self.device_torch)
230
+
231
+ return pipeline
232
+
233
+ def generate_single_image(
234
+ self,
235
+ pipeline: FluxKontextPipeline,
236
+ gen_config: GenerateImageConfig,
237
+ conditional_embeds: PromptEmbeds,
238
+ unconditional_embeds: PromptEmbeds,
239
+ generator: torch.Generator,
240
+ extra: dict,
241
+ ):
242
+ if gen_config.ctrl_img is None:
243
+ raise ValueError(
244
+ "Control image is required for Flux Kontext model generation."
245
+ )
246
+ else:
247
+ control_img = Image.open(gen_config.ctrl_img)
248
+ control_img = control_img.convert("RGB")
249
+ img = pipeline(
250
+ image=control_img,
251
+ prompt_embeds=conditional_embeds.text_embeds,
252
+ pooled_prompt_embeds=conditional_embeds.pooled_embeds,
253
+ height=gen_config.height,
254
+ width=gen_config.width,
255
+ num_inference_steps=gen_config.num_inference_steps,
256
+ guidance_scale=gen_config.guidance_scale,
257
+ latents=gen_config.latents,
258
+ generator=generator,
259
+ **extra
260
+ ).images[0]
261
+ return img
262
+
263
+ def get_noise_prediction(
264
+ self,
265
+ latent_model_input: torch.Tensor,
266
+ timestep: torch.Tensor, # 0 to 1000 scale
267
+ text_embeddings: PromptEmbeds,
268
+ guidance_embedding_scale: float,
269
+ bypass_guidance_embedding: bool,
270
+ **kwargs
271
+ ):
272
+ with torch.no_grad():
273
+ bs, c, h, w = latent_model_input.shape
274
+ # if we have a control on the channel dimension, put it on the batch for packing
275
+ has_control = False
276
+ if latent_model_input.shape[1] == 32:
277
+ # chunk it and stack it on batch dimension
278
+ # dont update batch size for img_its
279
+ lat, control = torch.chunk(latent_model_input, 2, dim=1)
280
+ latent_model_input = torch.cat([lat, control], dim=0)
281
+ has_control = True
282
+
283
+ latent_model_input_packed = rearrange(
284
+ latent_model_input,
285
+ "b c (h ph) (w pw) -> b (h w) (c ph pw)",
286
+ ph=2,
287
+ pw=2
288
+ )
289
+
290
+ img_ids = torch.zeros(h // 2, w // 2, 3)
291
+ img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[:, None]
292
+ img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, :]
293
+ img_ids = repeat(img_ids, "h w c -> b (h w) c",
294
+ b=bs).to(self.device_torch)
295
+
296
+ # handle control image ids
297
+ if has_control:
298
+ ctrl_ids = img_ids.clone()
299
+ ctrl_ids[..., 0] = 1
300
+ img_ids = torch.cat([img_ids, ctrl_ids], dim=1)
301
+
302
+
303
+ txt_ids = torch.zeros(
304
+ bs, text_embeddings.text_embeds.shape[1], 3).to(self.device_torch)
305
+
306
+ # # handle guidance
307
+ if self.unet_unwrapped.config.guidance_embeds:
308
+ if isinstance(guidance_embedding_scale, list):
309
+ guidance = torch.tensor(
310
+ guidance_embedding_scale, device=self.device_torch)
311
+ else:
312
+ guidance = torch.tensor(
313
+ [guidance_embedding_scale], device=self.device_torch)
314
+ guidance = guidance.expand(latent_model_input.shape[0])
315
+ else:
316
+ guidance = None
317
+
318
+ if bypass_guidance_embedding:
319
+ bypass_flux_guidance(self.unet)
320
+
321
+ cast_dtype = self.unet.dtype
322
+ # changes from orig implementation
323
+ if txt_ids.ndim == 3:
324
+ txt_ids = txt_ids[0]
325
+ if img_ids.ndim == 3:
326
+ img_ids = img_ids[0]
327
+
328
+ latent_size = latent_model_input_packed.shape[1]
329
+ # move the kontext channels. We have them on batch dimension to here, but need to put them on the latent dimension
330
+ if has_control:
331
+ latent, control = torch.chunk(latent_model_input_packed, 2, dim=0)
332
+ latent_model_input_packed = torch.cat(
333
+ [latent, control], dim=1
334
+ )
335
+ latent_size = latent.shape[1]
336
+
337
+ noise_pred = self.unet(
338
+ hidden_states=latent_model_input_packed.to(
339
+ self.device_torch, cast_dtype),
340
+ timestep=timestep / 1000,
341
+ encoder_hidden_states=text_embeddings.text_embeds.to(
342
+ self.device_torch, cast_dtype),
343
+ pooled_projections=text_embeddings.pooled_embeds.to(
344
+ self.device_torch, cast_dtype),
345
+ txt_ids=txt_ids,
346
+ img_ids=img_ids,
347
+ guidance=guidance,
348
+ return_dict=False,
349
+ **kwargs,
350
+ )[0]
351
+
352
+ # remove kontext image conditioning
353
+ noise_pred = noise_pred[:, :latent_size]
354
+
355
+ if isinstance(noise_pred, QTensor):
356
+ noise_pred = noise_pred.dequantize()
357
+
358
+ noise_pred = rearrange(
359
+ noise_pred,
360
+ "b (h w) (c ph pw) -> b c (h ph) (w pw)",
361
+ h=latent_model_input.shape[2] // 2,
362
+ w=latent_model_input.shape[3] // 2,
363
+ ph=2,
364
+ pw=2,
365
+ c=self.vae.config.latent_channels
366
+ )
367
+
368
+ if bypass_guidance_embedding:
369
+ restore_flux_guidance(self.unet)
370
+
371
+ return noise_pred
372
+
373
+ def get_prompt_embeds(self, prompt: str) -> PromptEmbeds:
374
+ if self.pipeline.text_encoder.device != self.device_torch:
375
+ self.pipeline.text_encoder.to(self.device_torch)
376
+ prompt_embeds, pooled_prompt_embeds = train_tools.encode_prompts_flux(
377
+ self.tokenizer,
378
+ self.text_encoder,
379
+ prompt,
380
+ max_length=512,
381
+ )
382
+ pe = PromptEmbeds(
383
+ prompt_embeds
384
+ )
385
+ pe.pooled_embeds = pooled_prompt_embeds
386
+ return pe
387
+
388
+ def get_model_has_grad(self):
389
+ # return from a weight if it has grad
390
+ return self.model.proj_out.weight.requires_grad
391
+
392
+ def get_te_has_grad(self):
393
+ # return from a weight if it has grad
394
+ return self.text_encoder[1].encoder.block[0].layer[0].SelfAttention.q.weight.requires_grad
395
+
396
+ def save_model(self, output_path, meta, save_dtype):
397
+ # only save the unet
398
+ transformer: FluxTransformer2DModel = unwrap_model(self.model)
399
+ transformer.save_pretrained(
400
+ save_directory=os.path.join(output_path, 'transformer'),
401
+ safe_serialization=True,
402
+ )
403
+
404
+ meta_path = os.path.join(output_path, 'aitk_meta.yaml')
405
+ with open(meta_path, 'w') as f:
406
+ yaml.dump(meta, f)
407
+
408
+ def get_loss_target(self, *args, **kwargs):
409
+ noise = kwargs.get('noise')
410
+ batch = kwargs.get('batch')
411
+ return (noise - batch.latents).detach()
412
+
413
+ def condition_noisy_latents(self, latents: torch.Tensor, batch:'DataLoaderBatchDTO'):
414
+ with torch.no_grad():
415
+ control_tensor = batch.control_tensor
416
+ if control_tensor is not None:
417
+ self.vae.to(self.device_torch)
418
+ # we are not packed here, so we just need to pass them so we can pack them later
419
+ control_tensor = control_tensor * 2 - 1
420
+ control_tensor = control_tensor.to(self.vae_device_torch, dtype=self.torch_dtype)
421
+
422
+ # if it is not the size of batch.tensor, (bs,ch,h,w) then we need to resize it
423
+ if batch.tensor is not None:
424
+ target_h, target_w = batch.tensor.shape[2], batch.tensor.shape[3]
425
+ else:
426
+ # When caching latents, batch.tensor is None. We get the size from the file_items instead.
427
+ target_h = batch.file_items[0].crop_height
428
+ target_w = batch.file_items[0].crop_width
429
+
430
+ if control_tensor.shape[2] != target_h or control_tensor.shape[3] != target_w:
431
+ control_tensor = F.interpolate(control_tensor, size=(target_h, target_w), mode='bilinear')
432
+
433
+ control_latent = self.encode_images(control_tensor).to(latents.device, latents.dtype)
434
+ latents = torch.cat((latents, control_latent), dim=1)
435
+
436
+ return latents.detach()