aryadomain commited on
Commit
18e07e6
·
verified ·
1 Parent(s): 45acb5f

Add files using upload-large-folder tool

Browse files
.gitattributes CHANGED
@@ -38,3 +38,4 @@ evaluation/image0.png filter=lfs diff=lfs merge=lfs -text
38
  Reward_sana_idealized/RESULTS/pickapic/one_step_rectification_config_sana_600m_512/run_2/rewards_curve.png filter=lfs diff=lfs merge=lfs -text
39
  Reward_sana_idealized/RESULTS/pickapic/one_step_rectification_config_sana_600m_512/run_3/rewards_curve.png filter=lfs diff=lfs merge=lfs -text
40
  lrm/lrm_sana/vqa_aes_clip_score_mp.csv filter=lfs diff=lfs merge=lfs -text
 
 
38
  Reward_sana_idealized/RESULTS/pickapic/one_step_rectification_config_sana_600m_512/run_2/rewards_curve.png filter=lfs diff=lfs merge=lfs -text
39
  Reward_sana_idealized/RESULTS/pickapic/one_step_rectification_config_sana_600m_512/run_3/rewards_curve.png filter=lfs diff=lfs merge=lfs -text
40
  lrm/lrm_sana/vqa_aes_clip_score_mp.csv filter=lfs diff=lfs merge=lfs -text
41
+ lrm/flux/vqa_aes_clip_score_mp.csv filter=lfs diff=lfs merge=lfs -text
lrm/flux/trainer/accelerators/__pycache__/base_accelerator.cpython-310.pyc ADDED
Binary file (16.5 kB). View file
 
lrm/flux/trainer/configs/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (662 Bytes). View file
 
lrm/flux/trainer/configs/__pycache__/configs.cpython-310.pyc ADDED
Binary file (3.54 kB). View file
 
lrm/flux/trainer/configs/__pycache__/configs.cpython-311.pyc ADDED
Binary file (5.75 kB). View file
 
lrm/flux/trainer/configs/__pycache__/step_flux_configs.cpython-310.pyc ADDED
Binary file (3.6 kB). View file
 
lrm/flux/trainer/configs/__pycache__/step_flux_configs.cpython-311.pyc ADDED
Binary file (5.81 kB). View file
 
lrm/flux/trainer/criterions/__pycache__/step_clip_criterion_flux.cpython-310.pyc ADDED
Binary file (6.07 kB). View file
 
lrm/flux/trainer/models/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from hydra.core.config_store import ConfigStore
2
+
3
+ from trainer.models.flux_preference_model import FluxPreferenceModelConfig
4
+
5
+ cs = ConfigStore.instance()
6
+ cs.store(group="model", name="step_flux_base", node=FluxPreferenceModelConfig)
7
+
8
+
9
+
lrm/flux/trainer/models/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (362 Bytes). View file
 
lrm/flux/trainer/models/__pycache__/base_model.cpython-310.pyc ADDED
Binary file (341 Bytes). View file
 
lrm/flux/trainer/models/__pycache__/base_model.cpython-311.pyc ADDED
Binary file (482 Bytes). View file
 
lrm/flux/trainer/models/__pycache__/flux_preference_model.cpython-311.pyc ADDED
Binary file (19.5 kB). View file
 
lrm/flux/trainer/models/__pycache__/unet_2d_condition_reward.cpython-310.pyc ADDED
Binary file (40.8 kB). View file
 
lrm/flux/trainer/models/base_model.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+
4
+
5
+ @dataclass
6
+ class BaseModelConfig:
7
+ pass
lrm/flux/trainer/models/flux_preference_model.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from dataclasses import dataclass
4
+ from io import BytesIO
5
+ from pathlib import Path
6
+
7
+ import torch
8
+ from PIL import Image
9
+ from torch import nn
10
+ from torchvision import transforms
11
+ from diffusers import AutoencoderKL, FlowMatchEulerDiscreteScheduler
12
+ from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
13
+
14
+ # Ensure sibling project modules (information_related_to_flux) are importable
15
+ _PROJECT_ROOT = Path(__file__).resolve().parents[3]
16
+ if str(_PROJECT_ROOT) not in sys.path:
17
+ sys.path.append(str(_PROJECT_ROOT))
18
+
19
+ from information_related_to_flux.dit import FluxTransformer2DModel
20
+ from information_related_to_flux.pipeline import FluxPipeline
21
+ from trainer.models.base_model import BaseModelConfig
22
+
23
+
24
+ @dataclass
25
+ class FluxPreferenceModelConfig(BaseModelConfig):
26
+ _target_: str = "trainer.models.flux_preference_model.FluxPreferenceModel"
27
+ pretrained_model_name_or_path: str = "black-forest-labs/FLUX.1-schnell"
28
+ pretrained_vae_name_or_path: str = "black-forest-labs/FLUX.1-schnell"
29
+ projection_dim: int = 1024
30
+ text_embed_dim: int = 768
31
+ logit_scale_init_value: float = 2.6592
32
+ freeze_text_encoder: bool = False
33
+ guidance_scale: float = 0.0
34
+ noise_offset: bool = False
35
+ noise_offset_coeff: float = 0.05
36
+ max_sequence_length: int = 512
37
+ image_size: int = 1024
38
+
39
+
40
+ class FluxPreferenceModel(nn.Module):
41
+ def __init__(self, cfg: FluxPreferenceModelConfig):
42
+ super().__init__()
43
+ self.cfg = cfg
44
+
45
+ offline_mode = os.getenv("HF_HUB_OFFLINE", "0").strip().lower() in {"1", "true", "yes", "on"}
46
+ cache_dir = os.getenv("HF_HUB_CACHE") or os.getenv("HUGGINGFACE_HUB_CACHE")
47
+ pretrained_kwargs = {
48
+ "local_files_only": offline_mode,
49
+ }
50
+ if cache_dir:
51
+ pretrained_kwargs["cache_dir"] = cache_dir
52
+
53
+ # Keep weights in the requested mixed precision to avoid fp32 VRAM blowups.
54
+ precision = os.getenv("ACCELERATE_MIXED_PRECISION", "").strip().lower()
55
+ model_dtype = None
56
+ if precision == "bf16":
57
+ model_dtype = torch.bfloat16
58
+ elif precision == "fp16":
59
+ model_dtype = torch.float16
60
+
61
+ module_load_kwargs = dict(pretrained_kwargs)
62
+ if model_dtype is not None:
63
+ module_load_kwargs["torch_dtype"] = model_dtype
64
+
65
+ self.vae = AutoencoderKL.from_pretrained(
66
+ cfg.pretrained_vae_name_or_path,
67
+ subfolder="vae",
68
+ **module_load_kwargs,
69
+ )
70
+ self.scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
71
+ cfg.pretrained_model_name_or_path,
72
+ subfolder="scheduler",
73
+ **pretrained_kwargs,
74
+ )
75
+ self.transformer = FluxTransformer2DModel.from_pretrained(
76
+ cfg.pretrained_model_name_or_path,
77
+ subfolder="transformer",
78
+ **module_load_kwargs,
79
+ )
80
+ self.tokenizer = CLIPTokenizer.from_pretrained(
81
+ cfg.pretrained_model_name_or_path,
82
+ subfolder="tokenizer",
83
+ **pretrained_kwargs,
84
+ )
85
+ self.tokenizer_2 = T5TokenizerFast.from_pretrained(
86
+ cfg.pretrained_model_name_or_path,
87
+ subfolder="tokenizer_2",
88
+ **pretrained_kwargs,
89
+ )
90
+ self.text_encoder = CLIPTextModel.from_pretrained(
91
+ cfg.pretrained_model_name_or_path,
92
+ subfolder="text_encoder",
93
+ **module_load_kwargs,
94
+ )
95
+ self.text_encoder_2 = T5EncoderModel.from_pretrained(
96
+ cfg.pretrained_model_name_or_path,
97
+ subfolder="text_encoder_2",
98
+ **module_load_kwargs,
99
+ )
100
+
101
+ self.vae.requires_grad_(False)
102
+ if cfg.freeze_text_encoder:
103
+ self.text_encoder.requires_grad_(False)
104
+ self.text_encoder_2.requires_grad_(False)
105
+
106
+ text_in_dim = self.text_encoder.config.hidden_size
107
+ image_in_dim = self.transformer.config.in_channels
108
+
109
+ self.text_projection = nn.Linear(text_in_dim, cfg.projection_dim, bias=False)
110
+ self.visual_projection = nn.Linear(image_in_dim, cfg.projection_dim, bias=False)
111
+ nn.init.normal_(self.text_projection.weight, std=0.02)
112
+ nn.init.normal_(self.visual_projection.weight, std=0.02)
113
+
114
+ self.logit_scale = nn.Parameter(torch.ones([]) * cfg.logit_scale_init_value)
115
+
116
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
117
+ self.height = cfg.image_size
118
+ self.width = cfg.image_size
119
+ self.val_transform = transforms.Compose(
120
+ [
121
+ transforms.Resize((self.height, self.width), interpolation=transforms.InterpolationMode.BILINEAR),
122
+ transforms.ToTensor(),
123
+ transforms.Normalize([0.5], [0.5]),
124
+ ]
125
+ )
126
+
127
+ def _get_sigmas_from_indices(self, timestep_indices: torch.Tensor, n_dim: int, dtype: torch.dtype):
128
+ all_sigmas = self.scheduler.sigmas.to(device=timestep_indices.device, dtype=dtype)
129
+ max_index = all_sigmas.shape[0] - 1
130
+ timestep_indices = timestep_indices.clamp(0, max_index).long()
131
+ sigma = all_sigmas[timestep_indices].flatten()
132
+ while len(sigma.shape) < n_dim:
133
+ sigma = sigma.unsqueeze(-1)
134
+ return sigma
135
+
136
+ def _encode_prompt(self, text_input_ids: torch.Tensor, text_input_ids_2: torch.Tensor):
137
+ clip_out = self.text_encoder(text_input_ids, output_hidden_states=False)
138
+ pooled_prompt_embeds = clip_out.pooler_output
139
+ prompt_embeds = self.text_encoder_2(text_input_ids_2, output_hidden_states=False)[0]
140
+
141
+ pooled_prompt_embeds = pooled_prompt_embeds.to(dtype=self.text_encoder.dtype, device=text_input_ids.device)
142
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=text_input_ids_2.device)
143
+
144
+ text_ids = torch.zeros(prompt_embeds.shape[1], 3, device=prompt_embeds.device, dtype=prompt_embeds.dtype)
145
+ text_features = self.text_projection(pooled_prompt_embeds)
146
+ return prompt_embeds, pooled_prompt_embeds, text_ids, text_features
147
+
148
+ def _encode_images(self, image_inputs: torch.Tensor):
149
+ vae_param = next(self.vae.parameters())
150
+ image_inputs = image_inputs.to(device=vae_param.device, dtype=vae_param.dtype)
151
+ with torch.no_grad():
152
+ latents = self.vae.encode(image_inputs).latent_dist.sample()
153
+ latents = (latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
154
+ return latents
155
+
156
+ def get_image_features(
157
+ self,
158
+ encoder_hidden_states: torch.Tensor,
159
+ pooled_prompt_embeds: torch.Tensor,
160
+ text_ids: torch.Tensor,
161
+ image_inputs: torch.Tensor,
162
+ time_cond: torch.Tensor,
163
+ generator=None,
164
+ ):
165
+ latents = self._encode_images(image_inputs)
166
+
167
+ if generator is not None:
168
+ noise = torch.randn(latents.size(), generator=generator, dtype=latents.dtype, device=latents.device)
169
+ else:
170
+ noise = torch.randn_like(latents)
171
+
172
+ if self.cfg.noise_offset:
173
+ noise = noise + self.cfg.noise_offset_coeff * torch.randn(
174
+ (latents.shape[0], latents.shape[1], 1, 1),
175
+ device=latents.device,
176
+ dtype=latents.dtype,
177
+ )
178
+
179
+ sigmas = self._get_sigmas_from_indices(time_cond, n_dim=latents.ndim, dtype=latents.dtype)
180
+ noisy_latents = (1.0 - sigmas) * latents + sigmas * noise
181
+
182
+ packed_noisy_latents = FluxPipeline._pack_latents(
183
+ noisy_latents,
184
+ batch_size=latents.shape[0],
185
+ num_channels_latents=latents.shape[1],
186
+ height=latents.shape[2],
187
+ width=latents.shape[3],
188
+ )
189
+
190
+ latent_image_ids = FluxPipeline._prepare_latent_image_ids(
191
+ latents.shape[0],
192
+ latents.shape[2] // 2,
193
+ latents.shape[3] // 2,
194
+ latents.device,
195
+ latents.dtype,
196
+ )
197
+
198
+ guidance = None
199
+ if self.transformer.config.guidance_embeds:
200
+ guidance = torch.full(
201
+ (latents.shape[0],),
202
+ self.cfg.guidance_scale,
203
+ device=latents.device,
204
+ dtype=latents.dtype,
205
+ )
206
+
207
+ scheduler_timesteps = self.scheduler.timesteps.to(device=time_cond.device)
208
+ timestep = scheduler_timesteps[time_cond.long()].to(device=latents.device, dtype=latents.dtype)
209
+ model_pred = self.transformer(
210
+ hidden_states=packed_noisy_latents,
211
+ timestep=timestep / 1000,
212
+ guidance=guidance,
213
+ pooled_projections=pooled_prompt_embeds,
214
+ encoder_hidden_states=encoder_hidden_states,
215
+ txt_ids=text_ids,
216
+ img_ids=latent_image_ids,
217
+ return_dict=False,
218
+ )[0]
219
+
220
+ pooled_tokens = model_pred.mean(dim=1)
221
+ image_features = self.visual_projection(pooled_tokens)
222
+ return image_features
223
+
224
+ def forward(self, text_input_ids, text_input_ids_2, image_inputs, time_cond, generator=None):
225
+ n_prompts = text_input_ids.shape[0]
226
+ n_images = image_inputs.shape[0]
227
+
228
+ encoder_hidden_states, pooled_prompt_embeds, text_ids, text_features = self._encode_prompt(
229
+ text_input_ids,
230
+ text_input_ids_2,
231
+ )
232
+
233
+ if n_images == 2 * n_prompts:
234
+ encoder_hidden_states = torch.cat([encoder_hidden_states, encoder_hidden_states], dim=0)
235
+ pooled_prompt_embeds = torch.cat([pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
236
+
237
+ image_features = self.get_image_features(
238
+ encoder_hidden_states=encoder_hidden_states,
239
+ pooled_prompt_embeds=pooled_prompt_embeds,
240
+ text_ids=text_ids,
241
+ image_inputs=image_inputs,
242
+ time_cond=time_cond,
243
+ generator=generator,
244
+ )
245
+
246
+ return text_features, image_features
247
+
248
+ def save(self, path):
249
+ self.transformer.save_pretrained(os.path.join(path, "transformer"), safe_serialization=True)
250
+ if not self.cfg.freeze_text_encoder:
251
+ self.text_encoder.save_pretrained(os.path.join(path, "text_encoder"), safe_serialization=True)
252
+ self.text_encoder_2.save_pretrained(os.path.join(path, "text_encoder_2"), safe_serialization=True)
253
+
254
+ state_dict = {
255
+ "visual_projection": self.visual_projection.state_dict(),
256
+ "text_projection": self.text_projection.state_dict(),
257
+ "logit_scale": self.logit_scale.data.item(),
258
+ }
259
+ torch.save(state_dict, os.path.join(path, "state_dict.pt"))
260
+
261
+ def load(self, path):
262
+ self.transformer = self.transformer.from_pretrained(os.path.join(path, "transformer"))
263
+ if not self.cfg.freeze_text_encoder:
264
+ self.text_encoder = self.text_encoder.from_pretrained(os.path.join(path, "text_encoder"))
265
+ self.text_encoder_2 = self.text_encoder_2.from_pretrained(os.path.join(path, "text_encoder_2"))
266
+
267
+ state_dict = torch.load(os.path.join(path, "state_dict.pt"), map_location="cpu")
268
+ self.visual_projection.load_state_dict(state_dict["visual_projection"])
269
+ self.text_projection.load_state_dict(state_dict["text_projection"])
270
+ self.logit_scale.data = torch.tensor(state_dict["logit_scale"])
271
+
272
+ def encode_prompt(self, prompt):
273
+ text_input_ids = self.tokenizer(
274
+ prompt,
275
+ padding="max_length",
276
+ max_length=self.tokenizer.model_max_length,
277
+ truncation=True,
278
+ return_tensors="pt",
279
+ ).input_ids
280
+ text_input_ids_2 = self.tokenizer_2(
281
+ prompt,
282
+ padding="max_length",
283
+ max_length=self.cfg.max_sequence_length,
284
+ truncation=True,
285
+ return_tensors="pt",
286
+ ).input_ids
287
+ return text_input_ids, text_input_ids_2
288
+
289
+ def preprocess_image(self, images):
290
+ if not isinstance(images, list):
291
+ images = [images]
292
+
293
+ image_inputs = []
294
+ for image in images:
295
+ if isinstance(image, dict):
296
+ image = image["bytes"]
297
+ if isinstance(image, bytes):
298
+ image = Image.open(BytesIO(image))
299
+ elif isinstance(image, str):
300
+ image = Image.open(image)
301
+ image = image.convert("RGB")
302
+ image = self.val_transform(image)
303
+ image_inputs.append(image)
304
+ image_inputs = torch.stack(image_inputs, dim=0)
305
+ return image_inputs
306
+
307
+ def get_preference_scores(self, prompt, images, timesteps, generator=None):
308
+ image_inputs = self.preprocess_image(images).to(self.vae.device, dtype=self.vae.dtype)
309
+ text_input_ids, text_input_ids_2 = self.encode_prompt(prompt)
310
+ text_input_ids = text_input_ids.to(self.text_encoder.device)
311
+ text_input_ids_2 = text_input_ids_2.to(self.text_encoder_2.device)
312
+ timestep_indices = torch.tensor([timesteps] * image_inputs.shape[0], dtype=torch.long, device=self.vae.device)
313
+
314
+ with torch.no_grad():
315
+ text_embs, image_embs = self.forward(
316
+ text_input_ids,
317
+ text_input_ids_2,
318
+ image_inputs,
319
+ timestep_indices,
320
+ generator=generator,
321
+ )
322
+
323
+ image_embs = image_embs / torch.norm(image_embs, dim=-1, keepdim=True)
324
+ text_embs = text_embs / torch.norm(text_embs, dim=-1, keepdim=True)
325
+
326
+ scores = self.logit_scale.exp() * (text_embs @ image_embs.T)[0]
327
+ probs = torch.softmax(scores, dim=-1)
328
+
329
+ return scores.cpu().tolist(), probs.cpu().tolist()
330
+
lrm/flux/trainer/models/unet_2d_condition_reward.py ADDED
@@ -0,0 +1,1334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from dataclasses import dataclass
15
+ from typing import Any, Dict, List, Optional, Tuple, Union
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.utils.checkpoint
20
+
21
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
22
+ from diffusers.loaders import PeftAdapterMixin, UNet2DConditionLoadersMixin
23
+ from diffusers.loaders.single_file_model import FromOriginalModelMixin
24
+ from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, logging, scale_lora_layers, unscale_lora_layers
25
+ from diffusers.models.activations import get_activation
26
+ from diffusers.models.attention_processor import (
27
+ ADDED_KV_ATTENTION_PROCESSORS,
28
+ CROSS_ATTENTION_PROCESSORS,
29
+ Attention,
30
+ AttentionProcessor,
31
+ AttnAddedKVProcessor,
32
+ AttnProcessor,
33
+ FusedAttnProcessor2_0,
34
+ )
35
+ from diffusers.models.embeddings import (
36
+ GaussianFourierProjection,
37
+ GLIGENTextBoundingboxProjection,
38
+ ImageHintTimeEmbedding,
39
+ ImageProjection,
40
+ ImageTimeEmbedding,
41
+ TextImageProjection,
42
+ TextImageTimeEmbedding,
43
+ TextTimeEmbedding,
44
+ TimestepEmbedding,
45
+ Timesteps,
46
+ )
47
+ from diffusers.models.modeling_utils import ModelMixin
48
+ from diffusers.models.unets.unet_2d_blocks import (
49
+ get_down_block,
50
+ get_mid_block,
51
+ get_up_block,
52
+ )
53
+
54
+
55
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
56
+
57
+
58
+ @dataclass
59
+ class UNet2DConditionOutput(BaseOutput):
60
+ """
61
+ The output of [`UNet2DConditionModel`].
62
+
63
+ Args:
64
+ sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
65
+ The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.
66
+ """
67
+
68
+ sample: torch.Tensor = None
69
+
70
+
71
+ class UNet2DConditionModel(
72
+ ModelMixin, ConfigMixin, FromOriginalModelMixin, UNet2DConditionLoadersMixin, PeftAdapterMixin
73
+ ):
74
+ r"""
75
+ A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample
76
+ shaped output.
77
+
78
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
79
+ for all models (such as downloading or saving).
80
+
81
+ Parameters:
82
+ sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
83
+ Height and width of input/output sample.
84
+ in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample.
85
+ out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.
86
+ center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
87
+ flip_sin_to_cos (`bool`, *optional*, defaults to `True`):
88
+ Whether to flip the sin to cos in the time embedding.
89
+ freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
90
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
91
+ The tuple of downsample blocks to use.
92
+ mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
93
+ Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or
94
+ `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped.
95
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`):
96
+ The tuple of upsample blocks to use.
97
+ only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):
98
+ Whether to include self-attention in the basic transformer blocks, see
99
+ [`~models.attention.BasicTransformerBlock`].
100
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
101
+ The tuple of output channels for each block.
102
+ layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
103
+ downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
104
+ mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
105
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
106
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
107
+ norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
108
+ If `None`, normalization and activation layers is skipped in post-processing.
109
+ norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
110
+ cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):
111
+ The dimension of the cross attention features.
112
+ transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):
113
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
114
+ [`~models.unets.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unets.unet_2d_blocks.CrossAttnUpBlock2D`],
115
+ [`~models.unets.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
116
+ reverse_transformer_layers_per_block : (`Tuple[Tuple]`, *optional*, defaults to None):
117
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`], in the upsampling
118
+ blocks of the U-Net. Only relevant if `transformer_layers_per_block` is of type `Tuple[Tuple]` and for
119
+ [`~models.unets.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unets.unet_2d_blocks.CrossAttnUpBlock2D`],
120
+ [`~models.unets.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
121
+ encoder_hid_dim (`int`, *optional*, defaults to None):
122
+ If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
123
+ dimension to `cross_attention_dim`.
124
+ encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
125
+ If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
126
+ embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
127
+ attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
128
+ num_attention_heads (`int`, *optional*):
129
+ The number of attention heads. If not defined, defaults to `attention_head_dim`
130
+ resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
131
+ for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
132
+ class_embed_type (`str`, *optional*, defaults to `None`):
133
+ The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
134
+ `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
135
+ addition_embed_type (`str`, *optional*, defaults to `None`):
136
+ Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
137
+ "text". "text" will use the `TextTimeEmbedding` layer.
138
+ addition_time_embed_dim: (`int`, *optional*, defaults to `None`):
139
+ Dimension for the timestep embeddings.
140
+ num_class_embeds (`int`, *optional*, defaults to `None`):
141
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
142
+ class conditioning with `class_embed_type` equal to `None`.
143
+ time_embedding_type (`str`, *optional*, defaults to `positional`):
144
+ The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.
145
+ time_embedding_dim (`int`, *optional*, defaults to `None`):
146
+ An optional override for the dimension of the projected time embedding.
147
+ time_embedding_act_fn (`str`, *optional*, defaults to `None`):
148
+ Optional activation function to use only once on the time embeddings before they are passed to the rest of
149
+ the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`.
150
+ timestep_post_act (`str`, *optional*, defaults to `None`):
151
+ The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.
152
+ time_cond_proj_dim (`int`, *optional*, defaults to `None`):
153
+ The dimension of `cond_proj` layer in the timestep embedding.
154
+ conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer.
155
+ conv_out_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_out` layer.
156
+ projection_class_embeddings_input_dim (`int`, *optional*): The dimension of the `class_labels` input when
157
+ `class_embed_type="projection"`. Required when `class_embed_type="projection"`.
158
+ class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time
159
+ embeddings with the class embeddings.
160
+ mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`):
161
+ Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If
162
+ `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the
163
+ `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False`
164
+ otherwise.
165
+ """
166
+
167
+ _supports_gradient_checkpointing = True
168
+ _no_split_modules = ["BasicTransformerBlock", "ResnetBlock2D", "CrossAttnUpBlock2D"]
169
+
170
+ @register_to_config
171
+ def __init__(
172
+ self,
173
+ sample_size: Optional[int] = None,
174
+ in_channels: int = 4,
175
+ out_channels: int = 4,
176
+ center_input_sample: bool = False,
177
+ flip_sin_to_cos: bool = True,
178
+ freq_shift: int = 0,
179
+ down_block_types: Tuple[str] = (
180
+ "CrossAttnDownBlock2D",
181
+ "CrossAttnDownBlock2D",
182
+ "CrossAttnDownBlock2D",
183
+ "DownBlock2D",
184
+ ),
185
+ mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
186
+ up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
187
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
188
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
189
+ layers_per_block: Union[int, Tuple[int]] = 2,
190
+ downsample_padding: int = 1,
191
+ mid_block_scale_factor: float = 1,
192
+ dropout: float = 0.0,
193
+ act_fn: str = "silu",
194
+ norm_num_groups: Optional[int] = 32,
195
+ norm_eps: float = 1e-5,
196
+ cross_attention_dim: Union[int, Tuple[int]] = 1280,
197
+ transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
198
+ reverse_transformer_layers_per_block: Optional[Tuple[Tuple[int]]] = None,
199
+ encoder_hid_dim: Optional[int] = None,
200
+ encoder_hid_dim_type: Optional[str] = None,
201
+ attention_head_dim: Union[int, Tuple[int]] = 8,
202
+ num_attention_heads: Optional[Union[int, Tuple[int]]] = None,
203
+ dual_cross_attention: bool = False,
204
+ use_linear_projection: bool = False,
205
+ class_embed_type: Optional[str] = None,
206
+ addition_embed_type: Optional[str] = None,
207
+ addition_time_embed_dim: Optional[int] = None,
208
+ num_class_embeds: Optional[int] = None,
209
+ upcast_attention: bool = False,
210
+ resnet_time_scale_shift: str = "default",
211
+ resnet_skip_time_act: bool = False,
212
+ resnet_out_scale_factor: float = 1.0,
213
+ time_embedding_type: str = "positional",
214
+ time_embedding_dim: Optional[int] = None,
215
+ time_embedding_act_fn: Optional[str] = None,
216
+ timestep_post_act: Optional[str] = None,
217
+ time_cond_proj_dim: Optional[int] = None,
218
+ conv_in_kernel: int = 3,
219
+ conv_out_kernel: int = 3,
220
+ projection_class_embeddings_input_dim: Optional[int] = None,
221
+ attention_type: str = "default",
222
+ class_embeddings_concat: bool = False,
223
+ mid_block_only_cross_attention: Optional[bool] = None,
224
+ cross_attention_norm: Optional[str] = None,
225
+ addition_embed_type_num_heads: int = 64,
226
+ ):
227
+ super().__init__()
228
+
229
+ self.sample_size = sample_size
230
+
231
+ if num_attention_heads is not None:
232
+ raise ValueError(
233
+ "At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19."
234
+ )
235
+
236
+ # If `num_attention_heads` is not defined (which is the case for most models)
237
+ # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
238
+ # The reason for this behavior is to correct for incorrectly named variables that were introduced
239
+ # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
240
+ # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
241
+ # which is why we correct for the naming here.
242
+ num_attention_heads = num_attention_heads or attention_head_dim
243
+
244
+ # Check inputs
245
+ self._check_config(
246
+ down_block_types=down_block_types,
247
+ up_block_types=up_block_types,
248
+ only_cross_attention=only_cross_attention,
249
+ block_out_channels=block_out_channels,
250
+ layers_per_block=layers_per_block,
251
+ cross_attention_dim=cross_attention_dim,
252
+ transformer_layers_per_block=transformer_layers_per_block,
253
+ reverse_transformer_layers_per_block=reverse_transformer_layers_per_block,
254
+ attention_head_dim=attention_head_dim,
255
+ num_attention_heads=num_attention_heads,
256
+ )
257
+
258
+ # input
259
+ conv_in_padding = (conv_in_kernel - 1) // 2
260
+ self.conv_in = nn.Conv2d(
261
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
262
+ )
263
+
264
+ # time
265
+ time_embed_dim, timestep_input_dim = self._set_time_proj(
266
+ time_embedding_type,
267
+ block_out_channels=block_out_channels,
268
+ flip_sin_to_cos=flip_sin_to_cos,
269
+ freq_shift=freq_shift,
270
+ time_embedding_dim=time_embedding_dim,
271
+ )
272
+
273
+ self.time_embedding = TimestepEmbedding(
274
+ timestep_input_dim,
275
+ time_embed_dim,
276
+ act_fn=act_fn,
277
+ post_act_fn=timestep_post_act,
278
+ cond_proj_dim=time_cond_proj_dim,
279
+ )
280
+
281
+ self._set_encoder_hid_proj(
282
+ encoder_hid_dim_type,
283
+ cross_attention_dim=cross_attention_dim,
284
+ encoder_hid_dim=encoder_hid_dim,
285
+ )
286
+
287
+ # class embedding
288
+ self._set_class_embedding(
289
+ class_embed_type,
290
+ act_fn=act_fn,
291
+ num_class_embeds=num_class_embeds,
292
+ projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,
293
+ time_embed_dim=time_embed_dim,
294
+ timestep_input_dim=timestep_input_dim,
295
+ )
296
+
297
+ self._set_add_embedding(
298
+ addition_embed_type,
299
+ addition_embed_type_num_heads=addition_embed_type_num_heads,
300
+ addition_time_embed_dim=addition_time_embed_dim,
301
+ cross_attention_dim=cross_attention_dim,
302
+ encoder_hid_dim=encoder_hid_dim,
303
+ flip_sin_to_cos=flip_sin_to_cos,
304
+ freq_shift=freq_shift,
305
+ projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,
306
+ time_embed_dim=time_embed_dim,
307
+ )
308
+
309
+ if time_embedding_act_fn is None:
310
+ self.time_embed_act = None
311
+ else:
312
+ self.time_embed_act = get_activation(time_embedding_act_fn)
313
+
314
+ self.down_blocks = nn.ModuleList([])
315
+ self.up_blocks = nn.ModuleList([])
316
+
317
+ if isinstance(only_cross_attention, bool):
318
+ if mid_block_only_cross_attention is None:
319
+ mid_block_only_cross_attention = only_cross_attention
320
+
321
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
322
+
323
+ if mid_block_only_cross_attention is None:
324
+ mid_block_only_cross_attention = False
325
+
326
+ if isinstance(num_attention_heads, int):
327
+ num_attention_heads = (num_attention_heads,) * len(down_block_types)
328
+
329
+ if isinstance(attention_head_dim, int):
330
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
331
+
332
+ if isinstance(cross_attention_dim, int):
333
+ cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
334
+
335
+ if isinstance(layers_per_block, int):
336
+ layers_per_block = [layers_per_block] * len(down_block_types)
337
+
338
+ if isinstance(transformer_layers_per_block, int):
339
+ transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
340
+
341
+ if class_embeddings_concat:
342
+ # The time embeddings are concatenated with the class embeddings. The dimension of the
343
+ # time embeddings passed to the down, middle, and up blocks is twice the dimension of the
344
+ # regular time embeddings
345
+ blocks_time_embed_dim = time_embed_dim * 2
346
+ else:
347
+ blocks_time_embed_dim = time_embed_dim
348
+
349
+ # down
350
+ output_channel = block_out_channels[0]
351
+ for i, down_block_type in enumerate(down_block_types):
352
+ input_channel = output_channel
353
+ output_channel = block_out_channels[i]
354
+ is_final_block = i == len(block_out_channels) - 1
355
+
356
+ down_block = get_down_block(
357
+ down_block_type,
358
+ num_layers=layers_per_block[i],
359
+ transformer_layers_per_block=transformer_layers_per_block[i],
360
+ in_channels=input_channel,
361
+ out_channels=output_channel,
362
+ temb_channels=blocks_time_embed_dim,
363
+ add_downsample=not is_final_block,
364
+ resnet_eps=norm_eps,
365
+ resnet_act_fn=act_fn,
366
+ resnet_groups=norm_num_groups,
367
+ cross_attention_dim=cross_attention_dim[i],
368
+ num_attention_heads=num_attention_heads[i],
369
+ downsample_padding=downsample_padding,
370
+ dual_cross_attention=dual_cross_attention,
371
+ use_linear_projection=use_linear_projection,
372
+ only_cross_attention=only_cross_attention[i],
373
+ upcast_attention=upcast_attention,
374
+ resnet_time_scale_shift=resnet_time_scale_shift,
375
+ attention_type=attention_type,
376
+ resnet_skip_time_act=resnet_skip_time_act,
377
+ resnet_out_scale_factor=resnet_out_scale_factor,
378
+ cross_attention_norm=cross_attention_norm,
379
+ attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
380
+ dropout=dropout,
381
+ )
382
+ self.down_blocks.append(down_block)
383
+
384
+ # mid
385
+ self.mid_block = get_mid_block(
386
+ mid_block_type,
387
+ temb_channels=blocks_time_embed_dim,
388
+ in_channels=block_out_channels[-1],
389
+ resnet_eps=norm_eps,
390
+ resnet_act_fn=act_fn,
391
+ resnet_groups=norm_num_groups,
392
+ output_scale_factor=mid_block_scale_factor,
393
+ transformer_layers_per_block=transformer_layers_per_block[-1],
394
+ num_attention_heads=num_attention_heads[-1],
395
+ cross_attention_dim=cross_attention_dim[-1],
396
+ dual_cross_attention=dual_cross_attention,
397
+ use_linear_projection=use_linear_projection,
398
+ mid_block_only_cross_attention=mid_block_only_cross_attention,
399
+ upcast_attention=upcast_attention,
400
+ resnet_time_scale_shift=resnet_time_scale_shift,
401
+ attention_type=attention_type,
402
+ resnet_skip_time_act=resnet_skip_time_act,
403
+ cross_attention_norm=cross_attention_norm,
404
+ attention_head_dim=attention_head_dim[-1],
405
+ dropout=dropout,
406
+ )
407
+
408
+ # count how many layers upsample the images
409
+ self.num_upsamplers = 0
410
+
411
+ # up
412
+ reversed_block_out_channels = list(reversed(block_out_channels))
413
+ reversed_num_attention_heads = list(reversed(num_attention_heads))
414
+ reversed_layers_per_block = list(reversed(layers_per_block))
415
+ reversed_cross_attention_dim = list(reversed(cross_attention_dim))
416
+ reversed_transformer_layers_per_block = (
417
+ list(reversed(transformer_layers_per_block))
418
+ if reverse_transformer_layers_per_block is None
419
+ else reverse_transformer_layers_per_block
420
+ )
421
+ only_cross_attention = list(reversed(only_cross_attention))
422
+
423
+ output_channel = reversed_block_out_channels[0]
424
+ for i, up_block_type in enumerate(up_block_types):
425
+ is_final_block = i == len(block_out_channels) - 1
426
+
427
+ prev_output_channel = output_channel
428
+ output_channel = reversed_block_out_channels[i]
429
+ input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
430
+
431
+ # add upsample block for all BUT final layer
432
+ if not is_final_block:
433
+ add_upsample = True
434
+ self.num_upsamplers += 1
435
+ else:
436
+ add_upsample = False
437
+
438
+ up_block = get_up_block(
439
+ up_block_type,
440
+ num_layers=reversed_layers_per_block[i] + 1,
441
+ transformer_layers_per_block=reversed_transformer_layers_per_block[i],
442
+ in_channels=input_channel,
443
+ out_channels=output_channel,
444
+ prev_output_channel=prev_output_channel,
445
+ temb_channels=blocks_time_embed_dim,
446
+ add_upsample=add_upsample,
447
+ resnet_eps=norm_eps,
448
+ resnet_act_fn=act_fn,
449
+ resolution_idx=i,
450
+ resnet_groups=norm_num_groups,
451
+ cross_attention_dim=reversed_cross_attention_dim[i],
452
+ num_attention_heads=reversed_num_attention_heads[i],
453
+ dual_cross_attention=dual_cross_attention,
454
+ use_linear_projection=use_linear_projection,
455
+ only_cross_attention=only_cross_attention[i],
456
+ upcast_attention=upcast_attention,
457
+ resnet_time_scale_shift=resnet_time_scale_shift,
458
+ attention_type=attention_type,
459
+ resnet_skip_time_act=resnet_skip_time_act,
460
+ resnet_out_scale_factor=resnet_out_scale_factor,
461
+ cross_attention_norm=cross_attention_norm,
462
+ attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
463
+ dropout=dropout,
464
+ )
465
+ self.up_blocks.append(up_block)
466
+ prev_output_channel = output_channel
467
+
468
+ # out
469
+ if norm_num_groups is not None:
470
+ self.conv_norm_out = nn.GroupNorm(
471
+ num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
472
+ )
473
+
474
+ self.conv_act = get_activation(act_fn)
475
+
476
+ else:
477
+ self.conv_norm_out = None
478
+ self.conv_act = None
479
+
480
+ conv_out_padding = (conv_out_kernel - 1) // 2
481
+ self.conv_out = nn.Conv2d(
482
+ block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding
483
+ )
484
+
485
+ self._set_pos_net_if_use_gligen(attention_type=attention_type, cross_attention_dim=cross_attention_dim)
486
+
487
+ def _check_config(
488
+ self,
489
+ down_block_types: Tuple[str],
490
+ up_block_types: Tuple[str],
491
+ only_cross_attention: Union[bool, Tuple[bool]],
492
+ block_out_channels: Tuple[int],
493
+ layers_per_block: Union[int, Tuple[int]],
494
+ cross_attention_dim: Union[int, Tuple[int]],
495
+ transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple[int]]],
496
+ reverse_transformer_layers_per_block: bool,
497
+ attention_head_dim: int,
498
+ num_attention_heads: Optional[Union[int, Tuple[int]]],
499
+ ):
500
+ if len(down_block_types) != len(up_block_types):
501
+ raise ValueError(
502
+ f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}."
503
+ )
504
+
505
+ if len(block_out_channels) != len(down_block_types):
506
+ raise ValueError(
507
+ f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."
508
+ )
509
+
510
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
511
+ raise ValueError(
512
+ f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
513
+ )
514
+
515
+ if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
516
+ raise ValueError(
517
+ f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}."
518
+ )
519
+
520
+ if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
521
+ raise ValueError(
522
+ f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
523
+ )
524
+
525
+ if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types):
526
+ raise ValueError(
527
+ f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}."
528
+ )
529
+
530
+ if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types):
531
+ raise ValueError(
532
+ f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}."
533
+ )
534
+ if isinstance(transformer_layers_per_block, list) and reverse_transformer_layers_per_block is None:
535
+ for layer_number_per_block in transformer_layers_per_block:
536
+ if isinstance(layer_number_per_block, list):
537
+ raise ValueError("Must provide 'reverse_transformer_layers_per_block` if using asymmetrical UNet.")
538
+
539
+ def _set_time_proj(
540
+ self,
541
+ time_embedding_type: str,
542
+ block_out_channels: int,
543
+ flip_sin_to_cos: bool,
544
+ freq_shift: float,
545
+ time_embedding_dim: int,
546
+ ) -> Tuple[int, int]:
547
+ if time_embedding_type == "fourier":
548
+ time_embed_dim = time_embedding_dim or block_out_channels[0] * 2
549
+ if time_embed_dim % 2 != 0:
550
+ raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.")
551
+ self.time_proj = GaussianFourierProjection(
552
+ time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos
553
+ )
554
+ timestep_input_dim = time_embed_dim
555
+ elif time_embedding_type == "positional":
556
+ time_embed_dim = time_embedding_dim or block_out_channels[0] * 4
557
+
558
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
559
+ timestep_input_dim = block_out_channels[0]
560
+ else:
561
+ raise ValueError(
562
+ f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`."
563
+ )
564
+
565
+ return time_embed_dim, timestep_input_dim
566
+
567
+ def _set_encoder_hid_proj(
568
+ self,
569
+ encoder_hid_dim_type: Optional[str],
570
+ cross_attention_dim: Union[int, Tuple[int]],
571
+ encoder_hid_dim: Optional[int],
572
+ ):
573
+ if encoder_hid_dim_type is None and encoder_hid_dim is not None:
574
+ encoder_hid_dim_type = "text_proj"
575
+ self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
576
+ logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.")
577
+
578
+ if encoder_hid_dim is None and encoder_hid_dim_type is not None:
579
+ raise ValueError(
580
+ f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
581
+ )
582
+
583
+ if encoder_hid_dim_type == "text_proj":
584
+ self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
585
+ elif encoder_hid_dim_type == "text_image_proj":
586
+ # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
587
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
588
+ # case when `addition_embed_type == "text_image_proj"` (Kandinsky 2.1)`
589
+ self.encoder_hid_proj = TextImageProjection(
590
+ text_embed_dim=encoder_hid_dim,
591
+ image_embed_dim=cross_attention_dim,
592
+ cross_attention_dim=cross_attention_dim,
593
+ )
594
+ elif encoder_hid_dim_type == "image_proj":
595
+ # Kandinsky 2.2
596
+ self.encoder_hid_proj = ImageProjection(
597
+ image_embed_dim=encoder_hid_dim,
598
+ cross_attention_dim=cross_attention_dim,
599
+ )
600
+ elif encoder_hid_dim_type is not None:
601
+ raise ValueError(
602
+ f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'."
603
+ )
604
+ else:
605
+ self.encoder_hid_proj = None
606
+
607
+ def _set_class_embedding(
608
+ self,
609
+ class_embed_type: Optional[str],
610
+ act_fn: str,
611
+ num_class_embeds: Optional[int],
612
+ projection_class_embeddings_input_dim: Optional[int],
613
+ time_embed_dim: int,
614
+ timestep_input_dim: int,
615
+ ):
616
+ if class_embed_type is None and num_class_embeds is not None:
617
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
618
+ elif class_embed_type == "timestep":
619
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn)
620
+ elif class_embed_type == "identity":
621
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
622
+ elif class_embed_type == "projection":
623
+ if projection_class_embeddings_input_dim is None:
624
+ raise ValueError(
625
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
626
+ )
627
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
628
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
629
+ # 2. it projects from an arbitrary input dimension.
630
+ #
631
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
632
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
633
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
634
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
635
+ elif class_embed_type == "simple_projection":
636
+ if projection_class_embeddings_input_dim is None:
637
+ raise ValueError(
638
+ "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set"
639
+ )
640
+ self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim)
641
+ else:
642
+ self.class_embedding = None
643
+
644
+ def _set_add_embedding(
645
+ self,
646
+ addition_embed_type: str,
647
+ addition_embed_type_num_heads: int,
648
+ addition_time_embed_dim: Optional[int],
649
+ flip_sin_to_cos: bool,
650
+ freq_shift: float,
651
+ cross_attention_dim: Optional[int],
652
+ encoder_hid_dim: Optional[int],
653
+ projection_class_embeddings_input_dim: Optional[int],
654
+ time_embed_dim: int,
655
+ ):
656
+ if addition_embed_type == "text":
657
+ if encoder_hid_dim is not None:
658
+ text_time_embedding_from_dim = encoder_hid_dim
659
+ else:
660
+ text_time_embedding_from_dim = cross_attention_dim
661
+
662
+ self.add_embedding = TextTimeEmbedding(
663
+ text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads
664
+ )
665
+ elif addition_embed_type == "text_image":
666
+ # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
667
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
668
+ # case when `addition_embed_type == "text_image"` (Kandinsky 2.1)`
669
+ self.add_embedding = TextImageTimeEmbedding(
670
+ text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim
671
+ )
672
+ elif addition_embed_type == "text_time":
673
+ self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)
674
+ self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
675
+ elif addition_embed_type == "image":
676
+ # Kandinsky 2.2
677
+ self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
678
+ elif addition_embed_type == "image_hint":
679
+ # Kandinsky 2.2 ControlNet
680
+ self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
681
+ elif addition_embed_type is not None:
682
+ raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.")
683
+
684
+ def _set_pos_net_if_use_gligen(self, attention_type: str, cross_attention_dim: int):
685
+ if attention_type in ["gated", "gated-text-image"]:
686
+ positive_len = 768
687
+ if isinstance(cross_attention_dim, int):
688
+ positive_len = cross_attention_dim
689
+ elif isinstance(cross_attention_dim, (list, tuple)):
690
+ positive_len = cross_attention_dim[0]
691
+
692
+ feature_type = "text-only" if attention_type == "gated" else "text-image"
693
+ self.position_net = GLIGENTextBoundingboxProjection(
694
+ positive_len=positive_len, out_dim=cross_attention_dim, feature_type=feature_type
695
+ )
696
+
697
+ @property
698
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
699
+ r"""
700
+ Returns:
701
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
702
+ indexed by its weight name.
703
+ """
704
+ # set recursively
705
+ processors = {}
706
+
707
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
708
+ if hasattr(module, "get_processor"):
709
+ processors[f"{name}.processor"] = module.get_processor()
710
+
711
+ for sub_name, child in module.named_children():
712
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
713
+
714
+ return processors
715
+
716
+ for name, module in self.named_children():
717
+ fn_recursive_add_processors(name, module, processors)
718
+
719
+ return processors
720
+
721
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
722
+ r"""
723
+ Sets the attention processor to use to compute attention.
724
+
725
+ Parameters:
726
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
727
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
728
+ for **all** `Attention` layers.
729
+
730
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
731
+ processor. This is strongly recommended when setting trainable attention processors.
732
+
733
+ """
734
+ count = len(self.attn_processors.keys())
735
+
736
+ if isinstance(processor, dict) and len(processor) != count:
737
+ raise ValueError(
738
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
739
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
740
+ )
741
+
742
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
743
+ if hasattr(module, "set_processor"):
744
+ if not isinstance(processor, dict):
745
+ module.set_processor(processor)
746
+ else:
747
+ module.set_processor(processor.pop(f"{name}.processor"))
748
+
749
+ for sub_name, child in module.named_children():
750
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
751
+
752
+ for name, module in self.named_children():
753
+ fn_recursive_attn_processor(name, module, processor)
754
+
755
+ def set_default_attn_processor(self):
756
+ """
757
+ Disables custom attention processors and sets the default attention implementation.
758
+ """
759
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
760
+ processor = AttnAddedKVProcessor()
761
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
762
+ processor = AttnProcessor()
763
+ else:
764
+ raise ValueError(
765
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
766
+ )
767
+
768
+ self.set_attn_processor(processor)
769
+
770
+ def set_attention_slice(self, slice_size: Union[str, int, List[int]] = "auto"):
771
+ r"""
772
+ Enable sliced attention computation.
773
+
774
+ When this option is enabled, the attention module splits the input tensor in slices to compute attention in
775
+ several steps. This is useful for saving some memory in exchange for a small decrease in speed.
776
+
777
+ Args:
778
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
779
+ When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
780
+ `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
781
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
782
+ must be a multiple of `slice_size`.
783
+ """
784
+ sliceable_head_dims = []
785
+
786
+ def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
787
+ if hasattr(module, "set_attention_slice"):
788
+ sliceable_head_dims.append(module.sliceable_head_dim)
789
+
790
+ for child in module.children():
791
+ fn_recursive_retrieve_sliceable_dims(child)
792
+
793
+ # retrieve number of attention layers
794
+ for module in self.children():
795
+ fn_recursive_retrieve_sliceable_dims(module)
796
+
797
+ num_sliceable_layers = len(sliceable_head_dims)
798
+
799
+ if slice_size == "auto":
800
+ # half the attention head size is usually a good trade-off between
801
+ # speed and memory
802
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
803
+ elif slice_size == "max":
804
+ # make smallest slice possible
805
+ slice_size = num_sliceable_layers * [1]
806
+
807
+ slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
808
+
809
+ if len(slice_size) != len(sliceable_head_dims):
810
+ raise ValueError(
811
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
812
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
813
+ )
814
+
815
+ for i in range(len(slice_size)):
816
+ size = slice_size[i]
817
+ dim = sliceable_head_dims[i]
818
+ if size is not None and size > dim:
819
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
820
+
821
+ # Recursively walk through all the children.
822
+ # Any children which exposes the set_attention_slice method
823
+ # gets the message
824
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
825
+ if hasattr(module, "set_attention_slice"):
826
+ module.set_attention_slice(slice_size.pop())
827
+
828
+ for child in module.children():
829
+ fn_recursive_set_attention_slice(child, slice_size)
830
+
831
+ reversed_slice_size = list(reversed(slice_size))
832
+ for module in self.children():
833
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
834
+
835
+ def _set_gradient_checkpointing(self, module, value=False):
836
+ if hasattr(module, "gradient_checkpointing"):
837
+ module.gradient_checkpointing = value
838
+
839
+ def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
840
+ r"""Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497.
841
+
842
+ The suffixes after the scaling factors represent the stage blocks where they are being applied.
843
+
844
+ Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that
845
+ are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
846
+
847
+ Args:
848
+ s1 (`float`):
849
+ Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
850
+ mitigate the "oversmoothing effect" in the enhanced denoising process.
851
+ s2 (`float`):
852
+ Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
853
+ mitigate the "oversmoothing effect" in the enhanced denoising process.
854
+ b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
855
+ b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
856
+ """
857
+ for i, upsample_block in enumerate(self.up_blocks):
858
+ setattr(upsample_block, "s1", s1)
859
+ setattr(upsample_block, "s2", s2)
860
+ setattr(upsample_block, "b1", b1)
861
+ setattr(upsample_block, "b2", b2)
862
+
863
+ def disable_freeu(self):
864
+ """Disables the FreeU mechanism."""
865
+ freeu_keys = {"s1", "s2", "b1", "b2"}
866
+ for i, upsample_block in enumerate(self.up_blocks):
867
+ for k in freeu_keys:
868
+ if hasattr(upsample_block, k) or getattr(upsample_block, k, None) is not None:
869
+ setattr(upsample_block, k, None)
870
+
871
+ def fuse_qkv_projections(self):
872
+ """
873
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
874
+ are fused. For cross-attention modules, key and value projection matrices are fused.
875
+
876
+ <Tip warning={true}>
877
+
878
+ This API is 🧪 experimental.
879
+
880
+ </Tip>
881
+ """
882
+ self.original_attn_processors = None
883
+
884
+ for _, attn_processor in self.attn_processors.items():
885
+ if "Added" in str(attn_processor.__class__.__name__):
886
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
887
+
888
+ self.original_attn_processors = self.attn_processors
889
+
890
+ for module in self.modules():
891
+ if isinstance(module, Attention):
892
+ module.fuse_projections(fuse=True)
893
+
894
+ self.set_attn_processor(FusedAttnProcessor2_0())
895
+
896
+ def unfuse_qkv_projections(self):
897
+ """Disables the fused QKV projection if enabled.
898
+
899
+ <Tip warning={true}>
900
+
901
+ This API is 🧪 experimental.
902
+
903
+ </Tip>
904
+
905
+ """
906
+ if self.original_attn_processors is not None:
907
+ self.set_attn_processor(self.original_attn_processors)
908
+
909
+ def get_time_embed(
910
+ self, sample: torch.Tensor, timestep: Union[torch.Tensor, float, int]
911
+ ) -> Optional[torch.Tensor]:
912
+ timesteps = timestep
913
+ if not torch.is_tensor(timesteps):
914
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
915
+ # This would be a good case for the `match` statement (Python 3.10+)
916
+ is_mps = sample.device.type == "mps"
917
+ if isinstance(timestep, float):
918
+ dtype = torch.float32 if is_mps else torch.float64
919
+ else:
920
+ dtype = torch.int32 if is_mps else torch.int64
921
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
922
+ elif len(timesteps.shape) == 0:
923
+ timesteps = timesteps[None].to(sample.device)
924
+
925
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
926
+ timesteps = timesteps.expand(sample.shape[0])
927
+
928
+ t_emb = self.time_proj(timesteps)
929
+ # `Timesteps` does not contain any weights and will always return f32 tensors
930
+ # but time_embedding might actually be running in fp16. so we need to cast here.
931
+ # there might be better ways to encapsulate this.
932
+ t_emb = t_emb.to(dtype=sample.dtype)
933
+ return t_emb
934
+
935
+ def get_class_embed(self, sample: torch.Tensor, class_labels: Optional[torch.Tensor]) -> Optional[torch.Tensor]:
936
+ class_emb = None
937
+ if self.class_embedding is not None:
938
+ if class_labels is None:
939
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
940
+
941
+ if self.config.class_embed_type == "timestep":
942
+ class_labels = self.time_proj(class_labels)
943
+
944
+ # `Timesteps` does not contain any weights and will always return f32 tensors
945
+ # there might be better ways to encapsulate this.
946
+ class_labels = class_labels.to(dtype=sample.dtype)
947
+
948
+ class_emb = self.class_embedding(class_labels).to(dtype=sample.dtype)
949
+ return class_emb
950
+
951
+ def get_aug_embed(
952
+ self, emb: torch.Tensor, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
953
+ ) -> Optional[torch.Tensor]:
954
+ aug_emb = None
955
+ if self.config.addition_embed_type == "text":
956
+ aug_emb = self.add_embedding(encoder_hidden_states)
957
+ elif self.config.addition_embed_type == "text_image":
958
+ # Kandinsky 2.1 - style
959
+ if "image_embeds" not in added_cond_kwargs:
960
+ raise ValueError(
961
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`"
962
+ )
963
+
964
+ image_embs = added_cond_kwargs.get("image_embeds")
965
+ text_embs = added_cond_kwargs.get("text_embeds", encoder_hidden_states)
966
+ aug_emb = self.add_embedding(text_embs, image_embs)
967
+ elif self.config.addition_embed_type == "text_time":
968
+ # SDXL - style
969
+ if "text_embeds" not in added_cond_kwargs:
970
+ raise ValueError(
971
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `text_embeds` to be passed in `added_cond_kwargs`"
972
+ )
973
+ text_embeds = added_cond_kwargs.get("text_embeds")
974
+ if "time_ids" not in added_cond_kwargs:
975
+ raise ValueError(
976
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `time_ids` to be passed in `added_cond_kwargs`"
977
+ )
978
+ time_ids = added_cond_kwargs.get("time_ids")
979
+ time_embeds = self.add_time_proj(time_ids.flatten())
980
+ time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
981
+ add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
982
+ add_embeds = add_embeds.to(emb.dtype)
983
+ aug_emb = self.add_embedding(add_embeds)
984
+ elif self.config.addition_embed_type == "image":
985
+ # Kandinsky 2.2 - style
986
+ if "image_embeds" not in added_cond_kwargs:
987
+ raise ValueError(
988
+ f"{self.__class__} has the config param `addition_embed_type` set to 'image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`"
989
+ )
990
+ image_embs = added_cond_kwargs.get("image_embeds")
991
+ aug_emb = self.add_embedding(image_embs)
992
+ elif self.config.addition_embed_type == "image_hint":
993
+ # Kandinsky 2.2 - style
994
+ if "image_embeds" not in added_cond_kwargs or "hint" not in added_cond_kwargs:
995
+ raise ValueError(
996
+ f"{self.__class__} has the config param `addition_embed_type` set to 'image_hint' which requires the keyword arguments `image_embeds` and `hint` to be passed in `added_cond_kwargs`"
997
+ )
998
+ image_embs = added_cond_kwargs.get("image_embeds")
999
+ hint = added_cond_kwargs.get("hint")
1000
+ aug_emb = self.add_embedding(image_embs, hint)
1001
+ return aug_emb
1002
+
1003
+ def process_encoder_hidden_states(
1004
+ self, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
1005
+ ) -> torch.Tensor:
1006
+ if self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_proj":
1007
+ encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states)
1008
+ elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_image_proj":
1009
+ # Kandinsky 2.1 - style
1010
+ if "image_embeds" not in added_cond_kwargs:
1011
+ raise ValueError(
1012
+ f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'text_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
1013
+ )
1014
+
1015
+ image_embeds = added_cond_kwargs.get("image_embeds")
1016
+ encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states, image_embeds)
1017
+ elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "image_proj":
1018
+ # Kandinsky 2.2 - style
1019
+ if "image_embeds" not in added_cond_kwargs:
1020
+ raise ValueError(
1021
+ f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
1022
+ )
1023
+ image_embeds = added_cond_kwargs.get("image_embeds")
1024
+ encoder_hidden_states = self.encoder_hid_proj(image_embeds)
1025
+ elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "ip_image_proj":
1026
+ if "image_embeds" not in added_cond_kwargs:
1027
+ raise ValueError(
1028
+ f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'ip_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
1029
+ )
1030
+
1031
+ if hasattr(self, "text_encoder_hid_proj") and self.text_encoder_hid_proj is not None:
1032
+ encoder_hidden_states = self.text_encoder_hid_proj(encoder_hidden_states)
1033
+
1034
+ image_embeds = added_cond_kwargs.get("image_embeds")
1035
+ image_embeds = self.encoder_hid_proj(image_embeds)
1036
+ encoder_hidden_states = (encoder_hidden_states, image_embeds)
1037
+ return encoder_hidden_states
1038
+
1039
+ def forward(
1040
+ self,
1041
+ sample: torch.Tensor,
1042
+ timestep: Union[torch.Tensor, float, int],
1043
+ encoder_hidden_states: torch.Tensor,
1044
+ class_labels: Optional[torch.Tensor] = None,
1045
+ timestep_cond: Optional[torch.Tensor] = None,
1046
+ attention_mask: Optional[torch.Tensor] = None,
1047
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1048
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
1049
+ down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
1050
+ mid_block_additional_residual: Optional[torch.Tensor] = None,
1051
+ down_intrablock_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
1052
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1053
+ use_up_blocks: bool = False,
1054
+ return_dict: bool = True,
1055
+ ) -> Union[UNet2DConditionOutput, Tuple]:
1056
+ r"""
1057
+ The [`UNet2DConditionModel`] forward method.
1058
+
1059
+ Args:
1060
+ sample (`torch.Tensor`):
1061
+ The noisy input tensor with the following shape `(batch, channel, height, width)`.
1062
+ timestep (`torch.Tensor` or `float` or `int`): The number of timesteps to denoise an input.
1063
+ encoder_hidden_states (`torch.Tensor`):
1064
+ The encoder hidden states with shape `(batch, sequence_length, feature_dim)`.
1065
+ class_labels (`torch.Tensor`, *optional*, defaults to `None`):
1066
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
1067
+ timestep_cond: (`torch.Tensor`, *optional*, defaults to `None`):
1068
+ Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed
1069
+ through the `self.time_embedding` layer to obtain the timestep embeddings.
1070
+ attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
1071
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
1072
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
1073
+ negative values to the attention scores corresponding to "discard" tokens.
1074
+ cross_attention_kwargs (`dict`, *optional*):
1075
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1076
+ `self.processor` in
1077
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1078
+ added_cond_kwargs: (`dict`, *optional*):
1079
+ A kwargs dictionary containing additional embeddings that if specified are added to the embeddings that
1080
+ are passed along to the UNet blocks.
1081
+ down_block_additional_residuals: (`tuple` of `torch.Tensor`, *optional*):
1082
+ A tuple of tensors that if specified are added to the residuals of down unet blocks.
1083
+ mid_block_additional_residual: (`torch.Tensor`, *optional*):
1084
+ A tensor that if specified is added to the residual of the middle unet block.
1085
+ down_intrablock_additional_residuals (`tuple` of `torch.Tensor`, *optional*):
1086
+ additional residuals to be added within UNet down blocks, for example from T2I-Adapter side model(s)
1087
+ encoder_attention_mask (`torch.Tensor`):
1088
+ A cross-attention mask of shape `(batch, sequence_length)` is applied to `encoder_hidden_states`. If
1089
+ `True` the mask is kept, otherwise if `False` it is discarded. Mask will be converted into a bias,
1090
+ which adds large negative values to the attention scores corresponding to "discard" tokens.
1091
+ return_dict (`bool`, *optional*, defaults to `True`):
1092
+ Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
1093
+ tuple.
1094
+
1095
+ Returns:
1096
+ [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
1097
+ If `return_dict` is True, an [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] is returned,
1098
+ otherwise a `tuple` is returned where the first element is the sample tensor.
1099
+ """
1100
+ # By default samples have to be AT least a multiple of the overall upsampling factor.
1101
+ # The overall upsampling factor is equal to 2 ** (# num of upsampling layers).
1102
+ # However, the upsampling interpolation output size can be forced to fit any upsampling size
1103
+ # on the fly if necessary.
1104
+ default_overall_up_factor = 2**self.num_upsamplers
1105
+
1106
+ # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
1107
+ forward_upsample_size = False
1108
+ upsample_size = None
1109
+
1110
+ # import time
1111
+ # torch.cuda.synchronize()
1112
+ # start_time = time.time()
1113
+
1114
+ for dim in sample.shape[-2:]:
1115
+ if dim % default_overall_up_factor != 0:
1116
+ # Forward upsample size to force interpolation output size.
1117
+ forward_upsample_size = True
1118
+ break
1119
+
1120
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension
1121
+ # expects mask of shape:
1122
+ # [batch, key_tokens]
1123
+ # adds singleton query_tokens dimension:
1124
+ # [batch, 1, key_tokens]
1125
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
1126
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
1127
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
1128
+ if attention_mask is not None:
1129
+ # assume that mask is expressed as:
1130
+ # (1 = keep, 0 = discard)
1131
+ # convert mask into a bias that can be added to attention scores:
1132
+ # (keep = +0, discard = -10000.0)
1133
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
1134
+ attention_mask = attention_mask.unsqueeze(1)
1135
+
1136
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
1137
+ if encoder_attention_mask is not None:
1138
+ encoder_attention_mask = (1 - encoder_attention_mask.to(sample.dtype)) * -10000.0
1139
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
1140
+
1141
+ # 0. center input if necessary
1142
+ if self.config.center_input_sample:
1143
+ sample = 2 * sample - 1.0
1144
+
1145
+ # 1. time
1146
+ t_emb = self.get_time_embed(sample=sample, timestep=timestep)
1147
+ emb = self.time_embedding(t_emb, timestep_cond)
1148
+ aug_emb = None
1149
+
1150
+ class_emb = self.get_class_embed(sample=sample, class_labels=class_labels)
1151
+ if class_emb is not None:
1152
+ if self.config.class_embeddings_concat:
1153
+ emb = torch.cat([emb, class_emb], dim=-1)
1154
+ else:
1155
+ emb = emb + class_emb
1156
+
1157
+ aug_emb = self.get_aug_embed(
1158
+ emb=emb, encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
1159
+ )
1160
+ if self.config.addition_embed_type == "image_hint":
1161
+ aug_emb, hint = aug_emb
1162
+ sample = torch.cat([sample, hint], dim=1)
1163
+
1164
+ emb = emb + aug_emb if aug_emb is not None else emb
1165
+
1166
+ if self.time_embed_act is not None:
1167
+ emb = self.time_embed_act(emb)
1168
+
1169
+ encoder_hidden_states = self.process_encoder_hidden_states(
1170
+ encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
1171
+ )
1172
+
1173
+ # 2. pre-process
1174
+ sample = self.conv_in(sample)
1175
+
1176
+ # 2.5 GLIGEN position net
1177
+ if cross_attention_kwargs is not None and cross_attention_kwargs.get("gligen", None) is not None:
1178
+ cross_attention_kwargs = cross_attention_kwargs.copy()
1179
+ gligen_args = cross_attention_kwargs.pop("gligen")
1180
+ cross_attention_kwargs["gligen"] = {"objs": self.position_net(**gligen_args)}
1181
+
1182
+ # 3. down
1183
+ # we're popping the `scale` instead of getting it because otherwise `scale` will be propagated
1184
+ # to the internal blocks and will raise deprecation warnings. this will be confusing for our users.
1185
+ if cross_attention_kwargs is not None:
1186
+ cross_attention_kwargs = cross_attention_kwargs.copy()
1187
+ lora_scale = cross_attention_kwargs.pop("scale", 1.0)
1188
+ else:
1189
+ lora_scale = 1.0
1190
+
1191
+ if USE_PEFT_BACKEND:
1192
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
1193
+ scale_lora_layers(self, lora_scale)
1194
+
1195
+ is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None
1196
+ # using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets
1197
+ is_adapter = down_intrablock_additional_residuals is not None
1198
+ # maintain backward compatibility for legacy usage, where
1199
+ # T2I-Adapter and ControlNet both use down_block_additional_residuals arg
1200
+ # but can only use one or the other
1201
+ if not is_adapter and mid_block_additional_residual is None and down_block_additional_residuals is not None:
1202
+ deprecate(
1203
+ "T2I should not use down_block_additional_residuals",
1204
+ "1.3.0",
1205
+ "Passing intrablock residual connections with `down_block_additional_residuals` is deprecated \
1206
+ and will be removed in diffusers 1.3.0. `down_block_additional_residuals` should only be used \
1207
+ for ControlNet. Please make sure use `down_intrablock_additional_residuals` instead. ",
1208
+ standard_warn=False,
1209
+ )
1210
+ down_intrablock_additional_residuals = down_block_additional_residuals
1211
+ is_adapter = True
1212
+
1213
+ # torch.cuda.synchronize()
1214
+ # logger.info(f"unet preprocess: {time.time() - start_time}")
1215
+
1216
+ # torch.cuda.synchronize()
1217
+ # start_time = time.time()
1218
+ down_block_res_samples = (sample,)
1219
+ for downsample_block in self.down_blocks:
1220
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
1221
+ # For t2i-adapter CrossAttnDownBlock2D
1222
+ additional_residuals = {}
1223
+ if is_adapter and len(down_intrablock_additional_residuals) > 0:
1224
+ additional_residuals["additional_residuals"] = down_intrablock_additional_residuals.pop(0)
1225
+
1226
+ sample, res_samples = downsample_block(
1227
+ hidden_states=sample,
1228
+ temb=emb,
1229
+ encoder_hidden_states=encoder_hidden_states,
1230
+ attention_mask=attention_mask,
1231
+ cross_attention_kwargs=cross_attention_kwargs,
1232
+ encoder_attention_mask=encoder_attention_mask,
1233
+ **additional_residuals,
1234
+ )
1235
+ else:
1236
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
1237
+ if is_adapter and len(down_intrablock_additional_residuals) > 0:
1238
+ sample += down_intrablock_additional_residuals.pop(0)
1239
+
1240
+ down_block_res_samples += res_samples
1241
+
1242
+ if is_controlnet:
1243
+ new_down_block_res_samples = ()
1244
+
1245
+ for down_block_res_sample, down_block_additional_residual in zip(
1246
+ down_block_res_samples, down_block_additional_residuals
1247
+ ):
1248
+ down_block_res_sample = down_block_res_sample + down_block_additional_residual
1249
+ new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)
1250
+
1251
+ down_block_res_samples = new_down_block_res_samples
1252
+ # torch.cuda.synchronize()
1253
+ # logger.info(f"unet down time: {time.time() - start_time}")
1254
+ # torch.cuda.synchronize()
1255
+ # start_time = time.time()
1256
+ # 4. mid
1257
+ if self.mid_block is not None:
1258
+ if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
1259
+ sample = self.mid_block(
1260
+ sample,
1261
+ emb,
1262
+ encoder_hidden_states=encoder_hidden_states,
1263
+ attention_mask=attention_mask,
1264
+ cross_attention_kwargs=cross_attention_kwargs,
1265
+ encoder_attention_mask=encoder_attention_mask,
1266
+ )
1267
+ else:
1268
+ sample = self.mid_block(sample, emb)
1269
+
1270
+ # To support T2I-Adapter-XL
1271
+ if (
1272
+ is_adapter
1273
+ and len(down_intrablock_additional_residuals) > 0
1274
+ and sample.shape == down_intrablock_additional_residuals[0].shape
1275
+ ):
1276
+ sample += down_intrablock_additional_residuals.pop(0)
1277
+
1278
+ if is_controlnet:
1279
+ sample = sample + mid_block_additional_residual
1280
+ # torch.cuda.synchronize()
1281
+ # logger.info(f"unet mid time: {time.time() - start_time}")
1282
+ mid_sample = sample
1283
+
1284
+ if use_up_blocks:
1285
+ # 5. up
1286
+ up_block_res_samples = ()
1287
+ for i, upsample_block in enumerate(self.up_blocks):
1288
+ is_final_block = i == len(self.up_blocks) - 1
1289
+
1290
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
1291
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
1292
+
1293
+ # if we have not reached the final block and need to forward the
1294
+ # upsample size, we do it here
1295
+ if not is_final_block and forward_upsample_size:
1296
+ upsample_size = down_block_res_samples[-1].shape[2:]
1297
+
1298
+ if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
1299
+ sample = upsample_block(
1300
+ hidden_states=sample,
1301
+ temb=emb,
1302
+ res_hidden_states_tuple=res_samples,
1303
+ encoder_hidden_states=encoder_hidden_states,
1304
+ cross_attention_kwargs=cross_attention_kwargs,
1305
+ upsample_size=upsample_size,
1306
+ attention_mask=attention_mask,
1307
+ encoder_attention_mask=encoder_attention_mask,
1308
+ )
1309
+ else:
1310
+ sample = upsample_block(
1311
+ hidden_states=sample,
1312
+ temb=emb,
1313
+ res_hidden_states_tuple=res_samples,
1314
+ upsample_size=upsample_size,
1315
+ )
1316
+ up_block_res_samples += (sample, )
1317
+
1318
+ # # 6. post-process
1319
+ # if self.conv_norm_out:
1320
+ # sample = self.conv_norm_out(sample)
1321
+ # sample = self.conv_act(sample)
1322
+ # sample = self.conv_out(sample)
1323
+
1324
+ if USE_PEFT_BACKEND:
1325
+ # remove `lora_scale` from each PEFT layer
1326
+ unscale_lora_layers(self, lora_scale)
1327
+
1328
+ if not return_dict:
1329
+ if use_up_blocks:
1330
+ return (mid_sample, down_block_res_samples, up_block_res_samples)
1331
+ else:
1332
+ return (mid_sample, down_block_res_samples)
1333
+
1334
+ return UNet2DConditionOutput(sample=sample)
lrm/flux/vqa_aes_clip_score_mp.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1096f5fca66e12c8f17b4b85f4239f36eab4e133c2b0b37eceec46bdc15d4d8
3
+ size 71832621