comdoleger commited on
Commit
272ed4b
·
verified ·
1 Parent(s): de9690e

Upload extensions_built_in/flex2/flex2.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. extensions_built_in/flex2/flex2.py +527 -0
extensions_built_in/flex2/flex2.py ADDED
@@ -0,0 +1,527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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 .pipeline import Flex2Pipeline
23
+ from einops import rearrange, repeat
24
+ import random
25
+ import torch.nn.functional as F
26
+
27
+ if TYPE_CHECKING:
28
+ from toolkit.data_transfer_object.data_loader import DataLoaderBatchDTO
29
+
30
+ scheduler_config = {
31
+ "base_image_seq_len": 256,
32
+ "base_shift": 0.5,
33
+ "max_image_seq_len": 4096,
34
+ "max_shift": 1.15,
35
+ "num_train_timesteps": 1000,
36
+ "shift": 3.0,
37
+ "use_dynamic_shifting": True
38
+ }
39
+
40
+
41
+ def random_blur(img, min_kernel_size=3, max_kernel_size=23, p=0.5):
42
+ if random.random() < p:
43
+ kernel_size = random.randint(min_kernel_size, max_kernel_size)
44
+ # make sure it is odd
45
+ if kernel_size % 2 == 0:
46
+ kernel_size += 1
47
+ img = torchvision.transforms.functional.gaussian_blur(img, kernel_size=kernel_size)
48
+ return img
49
+
50
+ class Flex2(BaseModel):
51
+ arch = "flex2"
52
+
53
+ def __init__(
54
+ self,
55
+ device,
56
+ model_config: ModelConfig,
57
+ dtype='bf16',
58
+ custom_pipeline=None,
59
+ noise_scheduler=None,
60
+ **kwargs
61
+ ):
62
+ super().__init__(
63
+ device,
64
+ model_config,
65
+ dtype,
66
+ custom_pipeline,
67
+ noise_scheduler,
68
+ **kwargs
69
+ )
70
+ self.is_flow_matching = True
71
+ self.is_transformer = True
72
+ self.target_lora_modules = ['FluxTransformer2DModel']
73
+
74
+ # for training, pass these as kwargs
75
+ self.invert_inpaint_mask_chance = model_config.model_kwargs.get('invert_inpaint_mask_chance', 0.0)
76
+ self.inpaint_dropout = model_config.model_kwargs.get('inpaint_dropout', 0.0)
77
+ self.control_dropout = model_config.model_kwargs.get('control_dropout', 0.0)
78
+ self.inpaint_random_chance = model_config.model_kwargs.get('inpaint_random_chance', 0.0)
79
+ self.random_blur_mask = model_config.model_kwargs.get('random_blur_mask', False)
80
+ self.random_dialate_mask = model_config.model_kwargs.get('random_dialate_mask', False)
81
+ self.do_random_inpainting = model_config.model_kwargs.get('do_random_inpainting', False)
82
+
83
+ # static method to get the noise scheduler
84
+ @staticmethod
85
+ def get_train_scheduler():
86
+ return CustomFlowMatchEulerDiscreteScheduler(**scheduler_config)
87
+
88
+ def get_bucket_divisibility(self):
89
+ return 16
90
+
91
+ def load_model(self):
92
+ dtype = self.torch_dtype
93
+ self.print_and_status_update("Loading Flux2 model")
94
+ # will be updated if we detect a existing checkpoint in training folder
95
+ model_path = self.model_config.name_or_path
96
+ # this is the original path put in the model directory
97
+ # it is here because for finetuning we only save the transformer usually
98
+ # so we need this for the VAE, te, etc
99
+ base_model_path = self.model_config.name_or_path_original
100
+
101
+ transformer_path = model_path
102
+ transformer_subfolder = 'transformer'
103
+ if os.path.exists(transformer_path):
104
+ transformer_subfolder = None
105
+ transformer_path = os.path.join(transformer_path, 'transformer')
106
+ # check if the path is a full checkpoint.
107
+ te_folder_path = os.path.join(model_path, 'text_encoder')
108
+ # if we have the te, this folder is a full checkpoint, use it as the base
109
+ if os.path.exists(te_folder_path):
110
+ base_model_path = model_path
111
+
112
+ self.print_and_status_update("Loading transformer")
113
+ transformer = FluxTransformer2DModel.from_pretrained(
114
+ transformer_path,
115
+ subfolder=transformer_subfolder,
116
+ torch_dtype=dtype,
117
+ )
118
+ transformer.to(self.quantize_device, dtype=dtype)
119
+
120
+ if self.model_config.quantize:
121
+ # patch the state dict method
122
+ patch_dequantization_on_save(transformer)
123
+ quantization_type = get_qtype(self.model_config.qtype)
124
+ self.print_and_status_update("Quantizing transformer")
125
+ quantize(transformer, weights=quantization_type,
126
+ **self.model_config.quantize_kwargs)
127
+ freeze(transformer)
128
+ transformer.to(self.device_torch)
129
+ else:
130
+ transformer.to(self.device_torch, dtype=dtype)
131
+
132
+ flush()
133
+
134
+ self.print_and_status_update("Loading T5")
135
+ tokenizer_2 = T5TokenizerFast.from_pretrained(
136
+ base_model_path, subfolder="tokenizer_2", torch_dtype=dtype
137
+ )
138
+ text_encoder_2 = T5EncoderModel.from_pretrained(
139
+ base_model_path, subfolder="text_encoder_2", torch_dtype=dtype
140
+ )
141
+ text_encoder_2.to(self.device_torch, dtype=dtype)
142
+ flush()
143
+
144
+ if self.model_config.quantize_te:
145
+ self.print_and_status_update("Quantizing T5")
146
+ quantize(text_encoder_2, weights=get_qtype(
147
+ self.model_config.qtype))
148
+ freeze(text_encoder_2)
149
+ flush()
150
+
151
+ self.print_and_status_update("Loading CLIP")
152
+ text_encoder = CLIPTextModel.from_pretrained(
153
+ base_model_path, subfolder="text_encoder", torch_dtype=dtype)
154
+ tokenizer = CLIPTokenizer.from_pretrained(
155
+ base_model_path, subfolder="tokenizer", torch_dtype=dtype)
156
+ text_encoder.to(self.device_torch, dtype=dtype)
157
+
158
+ self.print_and_status_update("Loading VAE")
159
+ vae = AutoencoderKL.from_pretrained(
160
+ base_model_path, subfolder="vae", torch_dtype=dtype)
161
+
162
+ self.noise_scheduler = Flex2.get_train_scheduler()
163
+
164
+ self.print_and_status_update("Making pipe")
165
+
166
+ pipe: Flex2Pipeline = Flex2Pipeline(
167
+ scheduler=self.noise_scheduler,
168
+ text_encoder=text_encoder,
169
+ tokenizer=tokenizer,
170
+ text_encoder_2=None,
171
+ tokenizer_2=tokenizer_2,
172
+ vae=vae,
173
+ transformer=None,
174
+ )
175
+ # for quantization, it works best to do these after making the pipe
176
+ pipe.text_encoder_2 = text_encoder_2
177
+ pipe.transformer = transformer
178
+
179
+ self.print_and_status_update("Preparing Model")
180
+
181
+ text_encoder = [pipe.text_encoder, pipe.text_encoder_2]
182
+ tokenizer = [pipe.tokenizer, pipe.tokenizer_2]
183
+
184
+ pipe.transformer = pipe.transformer.to(self.device_torch)
185
+
186
+ flush()
187
+ # just to make sure everything is on the right device and dtype
188
+ text_encoder[0].to(self.device_torch)
189
+ text_encoder[0].requires_grad_(False)
190
+ text_encoder[0].eval()
191
+ text_encoder[1].to(self.device_torch)
192
+ text_encoder[1].requires_grad_(False)
193
+ text_encoder[1].eval()
194
+ pipe.transformer = pipe.transformer.to(self.device_torch)
195
+ flush()
196
+
197
+ # save it to the model class
198
+ self.vae = vae
199
+ self.text_encoder = text_encoder # list of text encoders
200
+ self.tokenizer = tokenizer # list of tokenizers
201
+ self.model = pipe.transformer
202
+ self.pipeline = pipe
203
+ self.print_and_status_update("Model Loaded")
204
+
205
+ def get_generation_pipeline(self):
206
+ scheduler = Flex2.get_train_scheduler()
207
+
208
+ pipeline: Flex2Pipeline = Flex2Pipeline(
209
+ scheduler=scheduler,
210
+ text_encoder=unwrap_model(self.text_encoder[0]),
211
+ tokenizer=self.tokenizer[0],
212
+ text_encoder_2=unwrap_model(self.text_encoder[1]),
213
+ tokenizer_2=self.tokenizer[1],
214
+ vae=unwrap_model(self.vae),
215
+ transformer=unwrap_model(self.transformer)
216
+ )
217
+
218
+ pipeline = pipeline.to(self.device_torch)
219
+
220
+ return pipeline
221
+
222
+ def generate_single_image(
223
+ self,
224
+ pipeline: Flex2Pipeline,
225
+ gen_config: GenerateImageConfig,
226
+ conditional_embeds: PromptEmbeds,
227
+ unconditional_embeds: PromptEmbeds,
228
+ generator: torch.Generator,
229
+ extra: dict,
230
+ ):
231
+ if gen_config.ctrl_img is None:
232
+ control_img = None
233
+ else:
234
+ control_img = Image.open(gen_config.ctrl_img)
235
+ if ".inpaint." not in gen_config.ctrl_img:
236
+ control_img = control_img.convert("RGB")
237
+ else:
238
+ # make sure it has an alpha
239
+ if control_img.mode != "RGBA":
240
+ raise ValueError("Inpainting images must have an alpha channel")
241
+ img = pipeline(
242
+ prompt_embeds=conditional_embeds.text_embeds,
243
+ pooled_prompt_embeds=conditional_embeds.pooled_embeds,
244
+ height=gen_config.height,
245
+ width=gen_config.width,
246
+ num_inference_steps=gen_config.num_inference_steps,
247
+ guidance_scale=gen_config.guidance_scale,
248
+ latents=gen_config.latents,
249
+ generator=generator,
250
+ control_image=control_img,
251
+ control_image_idx=gen_config.ctrl_idx,
252
+ **extra
253
+ ).images[0]
254
+ return img
255
+
256
+ def get_noise_prediction(
257
+ self,
258
+ latent_model_input: torch.Tensor,
259
+ timestep: torch.Tensor, # 0 to 1000 scale
260
+ text_embeddings: PromptEmbeds,
261
+ guidance_embedding_scale: float,
262
+ bypass_guidance_embedding: bool,
263
+ **kwargs
264
+ ):
265
+ with torch.no_grad():
266
+ bs, c, h, w = latent_model_input.shape
267
+ latent_model_input_packed = rearrange(
268
+ latent_model_input,
269
+ "b c (h ph) (w pw) -> b (h w) (c ph pw)",
270
+ ph=2,
271
+ pw=2
272
+ )
273
+
274
+ img_ids = torch.zeros(h // 2, w // 2, 3)
275
+ img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[:, None]
276
+ img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, :]
277
+ img_ids = repeat(img_ids, "h w c -> b (h w) c",
278
+ b=bs).to(self.device_torch)
279
+
280
+ txt_ids = torch.zeros(
281
+ bs, text_embeddings.text_embeds.shape[1], 3).to(self.device_torch)
282
+
283
+ # # handle guidance
284
+ if self.unet_unwrapped.config.guidance_embeds:
285
+ if isinstance(guidance_embedding_scale, list):
286
+ guidance = torch.tensor(
287
+ guidance_embedding_scale, device=self.device_torch)
288
+ else:
289
+ guidance = torch.tensor(
290
+ [guidance_embedding_scale], device=self.device_torch)
291
+ guidance = guidance.expand(latent_model_input.shape[0])
292
+ else:
293
+ guidance = None
294
+
295
+ if bypass_guidance_embedding:
296
+ bypass_flux_guidance(self.unet)
297
+
298
+ cast_dtype = self.unet.dtype
299
+ # changes from orig implementation
300
+ if txt_ids.ndim == 3:
301
+ txt_ids = txt_ids[0]
302
+ if img_ids.ndim == 3:
303
+ img_ids = img_ids[0]
304
+
305
+ noise_pred = self.unet(
306
+ hidden_states=latent_model_input_packed.to(
307
+ self.device_torch, cast_dtype),
308
+ timestep=timestep / 1000,
309
+ encoder_hidden_states=text_embeddings.text_embeds.to(
310
+ self.device_torch, cast_dtype),
311
+ pooled_projections=text_embeddings.pooled_embeds.to(
312
+ self.device_torch, cast_dtype),
313
+ txt_ids=txt_ids,
314
+ img_ids=img_ids,
315
+ guidance=guidance,
316
+ return_dict=False,
317
+ **kwargs,
318
+ )[0]
319
+
320
+ if isinstance(noise_pred, QTensor):
321
+ noise_pred = noise_pred.dequantize()
322
+
323
+ noise_pred = rearrange(
324
+ noise_pred,
325
+ "b (h w) (c ph pw) -> b c (h ph) (w pw)",
326
+ h=latent_model_input.shape[2] // 2,
327
+ w=latent_model_input.shape[3] // 2,
328
+ ph=2,
329
+ pw=2,
330
+ c=self.vae.config.latent_channels
331
+ )
332
+
333
+ if bypass_guidance_embedding:
334
+ restore_flux_guidance(self.unet)
335
+
336
+ return noise_pred
337
+
338
+ def get_prompt_embeds(self, prompt: str) -> PromptEmbeds:
339
+ if self.pipeline.text_encoder.device != self.device_torch:
340
+ self.pipeline.text_encoder.to(self.device_torch)
341
+ prompt_embeds, pooled_prompt_embeds = train_tools.encode_prompts_flux(
342
+ self.tokenizer,
343
+ self.text_encoder,
344
+ prompt,
345
+ max_length=512,
346
+ )
347
+ pe = PromptEmbeds(
348
+ prompt_embeds
349
+ )
350
+ pe.pooled_embeds = pooled_prompt_embeds
351
+ return pe
352
+
353
+ def get_model_has_grad(self):
354
+ # return from a weight if it has grad
355
+ return self.model.proj_out.weight.requires_grad
356
+
357
+ def get_te_has_grad(self):
358
+ # return from a weight if it has grad
359
+ return self.text_encoder[1].encoder.block[0].layer[0].SelfAttention.q.weight.requires_grad
360
+
361
+ def save_model(self, output_path, meta, save_dtype):
362
+ # only save the unet
363
+ transformer: FluxTransformer2DModel = unwrap_model(self.model)
364
+ transformer.save_pretrained(
365
+ save_directory=os.path.join(output_path, 'transformer'),
366
+ safe_serialization=True,
367
+ )
368
+
369
+ meta_path = os.path.join(output_path, 'aitk_meta.yaml')
370
+ with open(meta_path, 'w') as f:
371
+ yaml.dump(meta, f)
372
+
373
+ def get_loss_target(self, *args, **kwargs):
374
+ noise = kwargs.get('noise')
375
+ batch = kwargs.get('batch')
376
+ return (noise - batch.latents).detach()
377
+
378
+ def condition_noisy_latents(self, latents: torch.Tensor, batch:'DataLoaderBatchDTO'):
379
+ with torch.no_grad():
380
+ # inpainting input is 0-1 (bs, 4, h, w) on batch.inpaint_tensor
381
+ # 4th channel is the mask with 1 being keep area and 0 being area to inpaint.
382
+ # todo handle dropout on a batch item level, this frops out the entire batch
383
+ do_dropout = random.random() < self.inpaint_dropout if self.inpaint_dropout > 0.0 else False
384
+ # do random mask if we dont have one
385
+ inpaint_tensor = batch.inpaint_tensor
386
+ if inpaint_tensor is None and batch.mask_tensor is not None:
387
+ # we have a mask tensor, use it
388
+ inpaint_tensor = batch.mask_tensor
389
+
390
+ if self.inpaint_random_chance > 0.0:
391
+ do_random = random.random() < self.inpaint_random_chance
392
+ if do_random:
393
+ # force a random tensor
394
+ inpaint_tensor = None
395
+
396
+ if inpaint_tensor is None and not do_dropout and self.do_random_inpainting:
397
+ # generate a random one since we dont have one
398
+ # this will make random blobs, invert the blobs for now as we normanlly inpaint the alpha
399
+ inpaint_tensor = 1 - generate_random_mask(
400
+ batch_size=latents.shape[0],
401
+ height=latents.shape[2],
402
+ width=latents.shape[3],
403
+ device=latents.device,
404
+ ).to(latents.device, latents.dtype)
405
+ if inpaint_tensor is not None and not do_dropout:
406
+
407
+ if inpaint_tensor.shape[1] == 4:
408
+ # get just the mask
409
+ inpainting_tensor_mask = inpaint_tensor[:, 3:4, :, :].to(latents.device, dtype=latents.dtype)
410
+ elif inpaint_tensor.shape[1] == 3:
411
+ # rgb mask. Just get one channel
412
+ inpainting_tensor_mask = inpaint_tensor[:, 0:1, :, :].to(latents.device, dtype=latents.dtype)
413
+ # mask is 0-1 with 1 being inpaint area, we need to invert it for now, it is re inverted later
414
+ inpaint_tensor = 1 - inpaint_tensor
415
+ else:
416
+ inpainting_tensor_mask = inpaint_tensor
417
+
418
+ # # use our batch latents so we cna avoid encoding again
419
+ inpainting_latent = batch.latents
420
+
421
+ # resize the mask to match the new encoded size
422
+ inpainting_tensor_mask = F.interpolate(inpainting_tensor_mask, size=(inpainting_latent.shape[2], inpainting_latent.shape[3]), mode='bilinear')
423
+ inpainting_tensor_mask = inpainting_tensor_mask.to(latents.device, latents.dtype)
424
+
425
+ if self.random_blur_mask:
426
+ # blur the mask
427
+ # Give it a channel dim of 1
428
+ if len(inpainting_tensor_mask.shape) == 3:
429
+ # if it is 3d, add a channel dim
430
+ inpainting_tensor_mask = inpainting_tensor_mask.unsqueeze(1)
431
+ # we are at latent size, so keep kernel smaller
432
+ inpainting_tensor_mask = random_blur(
433
+ inpainting_tensor_mask,
434
+ min_kernel_size=3,
435
+ max_kernel_size=8,
436
+ p=0.5
437
+ )
438
+
439
+ do_mask_invert = False
440
+ if self.invert_inpaint_mask_chance > 0.0:
441
+ do_mask_invert = random.random() < self.invert_inpaint_mask_chance
442
+ if do_mask_invert:
443
+ # invert the mask
444
+ inpainting_tensor_mask = 1 - inpainting_tensor_mask
445
+
446
+ # mask out the inpainting area, it is currently 0 for inpaint area, and 1 for keep area
447
+ # we are zeroing our the latents in the inpaint area not on the pixel space.
448
+ inpainting_latent = inpainting_latent * inpainting_tensor_mask
449
+
450
+ # do the random dialation after the mask is applied so it does not match perfectly.
451
+ # this will make the model learn to prevent weird edges
452
+ if self.random_dialate_mask:
453
+ inpainting_tensor_mask = random_dialate_mask(
454
+ inpainting_tensor_mask,
455
+ max_percent=0.05
456
+ )
457
+
458
+ # mask needs to be 1 for inpaint area and 0 for area to leave alone. So flip it.
459
+ inpainting_tensor_mask = 1 - inpainting_tensor_mask
460
+ # leave the mask as 0-1 and concat on channel of latents
461
+ inpainting_latent = torch.cat((inpainting_latent, inpainting_tensor_mask), dim=1)
462
+ else:
463
+ # we have iinpainting but didnt get a control. or we are doing a dropout
464
+ # the input needs to be all zeros for the latents and all 1s for the mask
465
+ inpainting_latent = torch.zeros_like(latents)
466
+ # add ones for the mask since we are technically inpainting everything
467
+ inpainting_latent = torch.cat((inpainting_latent, torch.ones_like(inpainting_latent[:, :1, :, :])), dim=1)
468
+
469
+ control_tensor = batch.control_tensor
470
+ if control_tensor is None:
471
+ # concat random normal noise onto the latents
472
+ # check dimension, this is before they are rearranged
473
+ # it is latent_model_input = torch.cat([latents, control_image], dim=2) after rearranging
474
+ ctrl = torch.zeros(
475
+ latents.shape[0], # bs
476
+ latents.shape[1],
477
+ latents.shape[2],
478
+ latents.shape[3],
479
+ device=latents.device,
480
+ dtype=latents.dtype
481
+ )
482
+ # inpainting always comes first
483
+ ctrl = torch.cat((inpainting_latent, ctrl), dim=1)
484
+ latents = torch.cat((latents, ctrl), dim=1)
485
+ return latents.detach()
486
+ # if we have multiple control tensors, they come in like [bs, num_control_images, ch, h, w]
487
+ # if we have 1, it comes in like [bs, ch, h, w]
488
+ # stack out control tensors to be [bs, ch * num_control_images, h, w]
489
+
490
+ control_tensor_list = []
491
+ if len(control_tensor.shape) == 4:
492
+ control_tensor_list.append(control_tensor)
493
+ else:
494
+ num_control_images = control_tensor.shape[1]
495
+ # reshape
496
+ control_tensor = control_tensor.view(
497
+ control_tensor.shape[0],
498
+ control_tensor.shape[1] * control_tensor.shape[2],
499
+ control_tensor.shape[3],
500
+ control_tensor.shape[4]
501
+ )
502
+ control_tensor_list = control_tensor.chunk(num_control_images, dim=1)
503
+
504
+ do_dropout = random.random() < self.control_dropout if self.control_dropout > 0.0 else False
505
+ if do_dropout:
506
+ # dropout with zeros
507
+ control_latent = torch.zeros_like(batch.latents)
508
+ else:
509
+ # we only have one control so we randomly pick from this list
510
+ control_tensor = random.choice(control_tensor_list)
511
+ # it is 0-1 need to convert to -1 to 1
512
+ control_tensor = control_tensor * 2 - 1
513
+
514
+ control_tensor = control_tensor.to(self.vae_device_torch, dtype=self.torch_dtype)
515
+
516
+ # if it is not the size of batch.tensor, (bs,ch,h,w) then we need to resize it
517
+ if control_tensor.shape[2] != batch.tensor.shape[2] or control_tensor.shape[3] != batch.tensor.shape[3]:
518
+ control_tensor = F.interpolate(control_tensor, size=(batch.tensor.shape[2], batch.tensor.shape[3]), mode='bilinear')
519
+
520
+ # encode it
521
+ control_latent = self.encode_images(control_tensor).to(latents.device, latents.dtype)
522
+
523
+ # inpainting always comes first
524
+ control_latent = torch.cat((inpainting_latent, control_latent), dim=1)
525
+ # concat it onto the latents
526
+ latents = torch.cat((latents, control_latent), dim=1)
527
+ return latents.detach()