comdoleger commited on
Commit
4d9b624
·
verified ·
1 Parent(s): de9d804

Upload extensions_built_in/diffusion_models/chroma/chroma_radiance_model.py with huggingface_hub

Browse files
extensions_built_in/diffusion_models/chroma/chroma_radiance_model.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import TYPE_CHECKING
3
+
4
+ import torch
5
+ from toolkit.config_modules import GenerateImageConfig, ModelConfig
6
+ from PIL import Image
7
+ from toolkit.models.base_model import BaseModel
8
+ from toolkit.basic import flush
9
+ from diffusers import AutoencoderKL
10
+ # from toolkit.pixel_shuffle_encoder import AutoencoderPixelMixer
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, CLIPTextModel, CLIPTokenizer
18
+ from .pipeline import ChromaPipeline, prepare_latent_image_ids
19
+ from einops import rearrange, repeat
20
+ import random
21
+ import torch.nn.functional as F
22
+ from .src.radiance import Chroma, chroma_params
23
+ from safetensors.torch import load_file, save_file
24
+ from toolkit.metadata import get_meta_for_safetensors
25
+ from toolkit.models.FakeVAE import FakeVAE
26
+ import huggingface_hub
27
+
28
+ if TYPE_CHECKING:
29
+ from toolkit.data_transfer_object.data_loader import DataLoaderBatchDTO
30
+
31
+ scheduler_config = {
32
+ "base_image_seq_len": 256,
33
+ "base_shift": 0.5,
34
+ "max_image_seq_len": 4096,
35
+ "max_shift": 1.15,
36
+ "num_train_timesteps": 1000,
37
+ "shift": 3.0,
38
+ "use_dynamic_shifting": True
39
+ }
40
+
41
+ class FakeConfig:
42
+ # for diffusers compatability
43
+ def __init__(self):
44
+ self.attention_head_dim = 128
45
+ self.guidance_embeds = True
46
+ self.in_channels = 64
47
+ self.joint_attention_dim = 4096
48
+ self.num_attention_heads = 24
49
+ self.num_layers = 19
50
+ self.num_single_layers = 38
51
+ self.patch_size = 1
52
+
53
+ class FakeCLIP(torch.nn.Module):
54
+ def __init__(self):
55
+ super().__init__()
56
+ self.dtype = torch.bfloat16
57
+ self.device = 'cuda'
58
+ self.text_model = None
59
+ self.tokenizer = None
60
+ self.model_max_length = 77
61
+
62
+ def forward(self, *args, **kwargs):
63
+ return torch.zeros(1, 1, 1).to(self.device)
64
+
65
+
66
+ class ChromaRadianceModel(BaseModel):
67
+ arch = "chroma_radiance"
68
+
69
+ def __init__(
70
+ self,
71
+ device,
72
+ model_config: ModelConfig,
73
+ dtype='bf16',
74
+ custom_pipeline=None,
75
+ noise_scheduler=None,
76
+ **kwargs
77
+ ):
78
+ super().__init__(
79
+ device,
80
+ model_config,
81
+ dtype,
82
+ custom_pipeline,
83
+ noise_scheduler,
84
+ **kwargs
85
+ )
86
+ self.is_flow_matching = True
87
+ self.is_transformer = True
88
+ self.target_lora_modules = ['Chroma']
89
+
90
+ # static method to get the noise scheduler
91
+ @staticmethod
92
+ def get_train_scheduler():
93
+ return CustomFlowMatchEulerDiscreteScheduler(**scheduler_config)
94
+
95
+ def get_bucket_divisibility(self):
96
+ # return the bucket divisibility for the model
97
+ return 32
98
+
99
+ def load_model(self):
100
+ dtype = self.torch_dtype
101
+
102
+ # will be updated if we detect a existing checkpoint in training folder
103
+ model_path = self.model_config.name_or_path
104
+
105
+ if model_path == "lodestones/Chroma":
106
+ print("Looking for latest Chroma checkpoint")
107
+ # get the latest checkpoint
108
+ files_list = huggingface_hub.list_repo_files(model_path)
109
+ print(files_list)
110
+ latest_version = 28 # current latest version at time of writing
111
+ while True:
112
+ if f"chroma-unlocked-v{latest_version}.safetensors" not in files_list:
113
+ latest_version -= 1
114
+ break
115
+ else:
116
+ latest_version += 1
117
+ print(f"Using latest Chroma version: v{latest_version}")
118
+
119
+ # make sure we have it
120
+ model_path = huggingface_hub.hf_hub_download(
121
+ repo_id=model_path,
122
+ filename=f"chroma-unlocked-v{latest_version}.safetensors",
123
+ )
124
+ elif model_path.startswith("lodestones/Chroma/v"):
125
+ # get the version number
126
+ version = model_path.split("/")[-1].split("v")[-1]
127
+ print(f"Using Chroma version: v{version}")
128
+ # make sure we have it
129
+ model_path = huggingface_hub.hf_hub_download(
130
+ repo_id='lodestones/Chroma',
131
+ filename=f"chroma-unlocked-v{version}.safetensors",
132
+ )
133
+ elif model_path.startswith("lodestones/Chroma1-"):
134
+ # will have a file in the repo that is Chroma1-whatever.safetensors
135
+ model_path = huggingface_hub.hf_hub_download(
136
+ repo_id=model_path,
137
+ filename=f"{model_path.split('/')[-1]}.safetensors",
138
+ )
139
+
140
+ else:
141
+ # check if the model path is a local file
142
+ if os.path.exists(model_path):
143
+ print(f"Using local model: {model_path}")
144
+ else:
145
+ raise ValueError(f"Model path {model_path} does not exist")
146
+
147
+ # extras_path = 'black-forest-labs/FLUX.1-schnell'
148
+ # schnell model is gated now, use flex instead
149
+ extras_path = 'ostris/Flex.1-alpha'
150
+
151
+ self.print_and_status_update("Loading transformer")
152
+
153
+ if model_path.endswith('.pth') or model_path.endswith('.pt'):
154
+ chroma_state_dict = torch.load(model_path, map_location='cpu', weights_only=True)
155
+ else:
156
+ chroma_state_dict = load_file(model_path, 'cpu')
157
+
158
+ # determine number of double and single blocks
159
+ double_blocks = 0
160
+ single_blocks = 0
161
+ for key in chroma_state_dict.keys():
162
+ if "double_blocks" in key:
163
+ block_num = int(key.split(".")[1]) + 1
164
+ if block_num > double_blocks:
165
+ double_blocks = block_num
166
+ elif "single_blocks" in key:
167
+ block_num = int(key.split(".")[1]) + 1
168
+ if block_num > single_blocks:
169
+ single_blocks = block_num
170
+ print(f"Double Blocks: {double_blocks}")
171
+ print(f"Single Blocks: {single_blocks}")
172
+
173
+ chroma_params.depth = double_blocks
174
+ chroma_params.depth_single_blocks = single_blocks
175
+ transformer = Chroma(chroma_params)
176
+
177
+ # add dtype, not sure why it doesnt have it
178
+ transformer.dtype = dtype
179
+ # load the state dict into the model
180
+ transformer.load_state_dict(chroma_state_dict)
181
+
182
+ transformer.to(self.quantize_device, dtype=dtype)
183
+
184
+ transformer.config = FakeConfig()
185
+ transformer.config.num_layers = double_blocks
186
+ transformer.config.num_single_layers = single_blocks
187
+
188
+ if self.model_config.quantize:
189
+ # patch the state dict method
190
+ patch_dequantization_on_save(transformer)
191
+ quantization_type = get_qtype(self.model_config.qtype)
192
+ self.print_and_status_update("Quantizing transformer")
193
+ quantize(transformer, weights=quantization_type,
194
+ **self.model_config.quantize_kwargs)
195
+ freeze(transformer)
196
+ transformer.to(self.device_torch)
197
+ else:
198
+ transformer.to(self.device_torch, dtype=dtype)
199
+
200
+ flush()
201
+
202
+ self.print_and_status_update("Loading T5")
203
+ tokenizer_2 = T5TokenizerFast.from_pretrained(
204
+ extras_path, subfolder="tokenizer_2", torch_dtype=dtype
205
+ )
206
+ text_encoder_2 = T5EncoderModel.from_pretrained(
207
+ extras_path, subfolder="text_encoder_2", torch_dtype=dtype
208
+ )
209
+ text_encoder_2.to(self.device_torch, dtype=dtype)
210
+ flush()
211
+
212
+ if self.model_config.quantize_te:
213
+ self.print_and_status_update("Quantizing T5")
214
+ quantize(text_encoder_2, weights=get_qtype(
215
+ self.model_config.qtype))
216
+ freeze(text_encoder_2)
217
+ flush()
218
+
219
+ # self.print_and_status_update("Loading CLIP")
220
+ text_encoder = FakeCLIP()
221
+ tokenizer = FakeCLIP()
222
+ text_encoder.to(self.device_torch, dtype=dtype)
223
+
224
+ self.noise_scheduler = ChromaRadianceModel.get_train_scheduler()
225
+
226
+ self.print_and_status_update("Loading VAE")
227
+ # vae = AutoencoderKL.from_pretrained(
228
+ # extras_path,
229
+ # subfolder="vae",
230
+ # torch_dtype=dtype
231
+ # )
232
+ vae = FakeVAE()
233
+ vae = vae.to(self.device_torch, dtype=dtype)
234
+
235
+ self.print_and_status_update("Making pipe")
236
+
237
+ pipe: ChromaPipeline = ChromaPipeline(
238
+ scheduler=self.noise_scheduler,
239
+ text_encoder=text_encoder,
240
+ tokenizer=tokenizer,
241
+ text_encoder_2=None,
242
+ tokenizer_2=tokenizer_2,
243
+ vae=vae,
244
+ transformer=None,
245
+ is_radiance=True,
246
+ )
247
+ # for quantization, it works best to do these after making the pipe
248
+ pipe.text_encoder_2 = text_encoder_2
249
+ pipe.transformer = transformer
250
+
251
+ self.print_and_status_update("Preparing Model")
252
+
253
+ text_encoder = [pipe.text_encoder, pipe.text_encoder_2]
254
+ tokenizer = [pipe.tokenizer, pipe.tokenizer_2]
255
+
256
+ pipe.transformer = pipe.transformer.to(self.device_torch)
257
+
258
+ flush()
259
+ # just to make sure everything is on the right device and dtype
260
+ text_encoder[0].to(self.device_torch)
261
+ text_encoder[0].requires_grad_(False)
262
+ text_encoder[0].eval()
263
+ text_encoder[1].to(self.device_torch)
264
+ text_encoder[1].requires_grad_(False)
265
+ text_encoder[1].eval()
266
+ pipe.transformer = pipe.transformer.to(self.device_torch)
267
+ flush()
268
+
269
+ # save it to the model class
270
+ self.vae = vae
271
+ self.text_encoder = text_encoder # list of text encoders
272
+ self.tokenizer = tokenizer # list of tokenizers
273
+ self.model = pipe.transformer
274
+ self.pipeline = pipe
275
+ self.print_and_status_update("Model Loaded")
276
+
277
+ def get_generation_pipeline(self):
278
+ scheduler = ChromaRadianceModel.get_train_scheduler()
279
+ pipeline = ChromaPipeline(
280
+ scheduler=scheduler,
281
+ text_encoder=unwrap_model(self.text_encoder[0]),
282
+ tokenizer=self.tokenizer[0],
283
+ text_encoder_2=unwrap_model(self.text_encoder[1]),
284
+ tokenizer_2=self.tokenizer[1],
285
+ vae=unwrap_model(self.vae),
286
+ transformer=unwrap_model(self.transformer),
287
+ is_radiance=True,
288
+ )
289
+
290
+ # pipeline = pipeline.to(self.device_torch)
291
+
292
+ return pipeline
293
+
294
+ def generate_single_image(
295
+ self,
296
+ pipeline: ChromaPipeline,
297
+ gen_config: GenerateImageConfig,
298
+ conditional_embeds: PromptEmbeds,
299
+ unconditional_embeds: PromptEmbeds,
300
+ generator: torch.Generator,
301
+ extra: dict,
302
+ ):
303
+
304
+ extra['negative_prompt_embeds'] = unconditional_embeds.text_embeds
305
+ extra['negative_prompt_attn_mask'] = unconditional_embeds.attention_mask
306
+
307
+ img = pipeline(
308
+ prompt_embeds=conditional_embeds.text_embeds,
309
+ prompt_attn_mask=conditional_embeds.attention_mask,
310
+ height=gen_config.height,
311
+ width=gen_config.width,
312
+ num_inference_steps=gen_config.num_inference_steps,
313
+ guidance_scale=gen_config.guidance_scale,
314
+ latents=gen_config.latents,
315
+ generator=generator,
316
+ **extra
317
+ ).images[0]
318
+ return img
319
+
320
+ def get_noise_prediction(
321
+ self,
322
+ latent_model_input: torch.Tensor,
323
+ timestep: torch.Tensor, # 0 to 1000 scale
324
+ text_embeddings: PromptEmbeds,
325
+ **kwargs
326
+ ):
327
+ with torch.no_grad():
328
+ bs, c, h, w = latent_model_input.shape
329
+
330
+ img_ids = prepare_latent_image_ids(
331
+ bs, h, w, patch_size=16
332
+ ).to(self.device_torch)
333
+
334
+ txt_ids = torch.zeros(
335
+ bs, text_embeddings.text_embeds.shape[1], 3).to(self.device_torch)
336
+
337
+ guidance = torch.full([1], 0, device=self.device_torch, dtype=torch.float32)
338
+ guidance = guidance.expand(bs)
339
+
340
+ cast_dtype = self.unet.dtype
341
+
342
+ noise_pred = self.unet(
343
+ img=latent_model_input.to(
344
+ self.device_torch, cast_dtype
345
+ ),
346
+ img_ids=img_ids,
347
+ txt=text_embeddings.text_embeds.to(
348
+ self.device_torch, cast_dtype
349
+ ),
350
+ txt_ids=txt_ids,
351
+ txt_mask=text_embeddings.attention_mask.to(
352
+ self.device_torch, cast_dtype
353
+ ),
354
+ timesteps=timestep / 1000,
355
+ guidance=guidance
356
+ )
357
+
358
+ if isinstance(noise_pred, QTensor):
359
+ noise_pred = noise_pred.dequantize()
360
+
361
+ return noise_pred
362
+
363
+ def get_prompt_embeds(self, prompt: str) -> PromptEmbeds:
364
+ if isinstance(prompt, str):
365
+ prompts = [prompt]
366
+ else:
367
+ prompts = prompt
368
+ if self.pipeline.text_encoder.device != self.device_torch:
369
+ self.pipeline.text_encoder.to(self.device_torch)
370
+
371
+ max_length = 512
372
+
373
+ device = self.text_encoder[1].device
374
+ dtype = self.text_encoder[1].dtype
375
+
376
+ # T5
377
+ text_inputs = self.tokenizer[1](
378
+ prompts,
379
+ padding="max_length",
380
+ max_length=max_length,
381
+ truncation=True,
382
+ return_length=False,
383
+ return_overflowing_tokens=False,
384
+ return_tensors="pt",
385
+ )
386
+ text_input_ids = text_inputs.input_ids
387
+
388
+ prompt_embeds = self.text_encoder[1](text_input_ids.to(device), output_hidden_states=False)[0]
389
+
390
+ dtype = self.text_encoder[1].dtype
391
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
392
+
393
+ prompt_attention_mask = text_inputs["attention_mask"]
394
+
395
+ pe = PromptEmbeds(
396
+ prompt_embeds
397
+ )
398
+ pe.attention_mask = prompt_attention_mask
399
+ return pe
400
+
401
+ def get_model_has_grad(self):
402
+ # return from a weight if it has grad
403
+ return False
404
+ def get_te_has_grad(self):
405
+ # return from a weight if it has grad
406
+ return False
407
+
408
+ def save_model(self, output_path, meta, save_dtype):
409
+ if not output_path.endswith(".safetensors"):
410
+ output_path = output_path + ".safetensors"
411
+ # only save the unet
412
+ transformer: Chroma = unwrap_model(self.model)
413
+ state_dict = transformer.state_dict()
414
+ save_dict = {}
415
+ for k, v in state_dict.items():
416
+ if isinstance(v, QTensor):
417
+ v = v.dequantize()
418
+ save_dict[k] = v.clone().to('cpu', dtype=save_dtype)
419
+
420
+ meta = get_meta_for_safetensors(meta, name='chroma')
421
+ save_file(save_dict, output_path, metadata=meta)
422
+
423
+ def get_loss_target(self, *args, **kwargs):
424
+ noise = kwargs.get('noise')
425
+ batch = kwargs.get('batch')
426
+ return (noise - batch.latents).detach()
427
+
428
+ def convert_lora_weights_before_save(self, state_dict):
429
+ # currently starte with transformer. but needs to start with diffusion_model. for comfyui
430
+ new_sd = {}
431
+ for key, value in state_dict.items():
432
+ new_key = key.replace("transformer.", "diffusion_model.")
433
+ new_sd[new_key] = value
434
+ return new_sd
435
+
436
+ def convert_lora_weights_before_load(self, state_dict):
437
+ # saved as diffusion_model. but needs to be transformer. for ai-toolkit
438
+ new_sd = {}
439
+ for key, value in state_dict.items():
440
+ new_key = key.replace("diffusion_model.", "transformer.")
441
+ new_sd[new_key] = value
442
+ return new_sd
443
+
444
+ def get_base_model_version(self):
445
+ return "chroma_radiance"