JOY-Huang commited on
Commit
aa79e9e
1 Parent(s): b4cad83

revitalize repo

Browse files
app.py CHANGED
@@ -1,7 +1,9 @@
1
  import os
2
  import torch
 
 
3
  import numpy as np
4
- import app as gr
5
  from PIL import Image
6
 
7
  from diffusers import DDPMScheduler
@@ -12,6 +14,31 @@ from pipelines.sdxl_instantir import InstantIRPipeline
12
 
13
  from huggingface_hub import hf_hub_download
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  if not os.path.exists("models/adapter.pt"):
16
  hf_hub_download(repo_id="InstantX/InstantIR", filename="models/adapter.pt", local_dir=".")
17
  if not os.path.exists("models/aggregator.pt"):
@@ -22,6 +49,7 @@ if not os.path.exists("models/previewer_lora_weights.bin"):
22
  device = "cuda" if torch.cuda.is_available() else "cpu"
23
  sdxl_repo_id = "stabilityai/stable-diffusion-xl-base-1.0"
24
  dinov2_repo_id = "facebook/dinov2-large"
 
25
 
26
  if torch.cuda.is_available():
27
  torch_dtype = torch.float16
@@ -29,7 +57,7 @@ else:
29
  torch_dtype = torch.float32
30
 
31
  # Load pretrained models.
32
- print("Loading SDXL...")
33
  pipe = InstantIRPipeline.from_pretrained(
34
  sdxl_repo_id,
35
  torch_dtype=torch_dtype,
@@ -46,7 +74,7 @@ load_adapter_to_pipe(
46
  # Prepare previewer
47
  lora_alpha = pipe.prepare_previewers("models")
48
  print(f"use lora alpha {lora_alpha}")
49
- lora_alpha = pipe.prepare_previewers("latent-consistency/lcm-lora-sdxl", use_lcm=True)
50
  print(f"use lora alpha {lora_alpha}")
51
  pipe.to(device=device, dtype=torch_dtype)
52
  pipe.scheduler = DDPMScheduler.from_pretrained(sdxl_repo_id, subfolder="scheduler")
@@ -63,7 +91,7 @@ aggregator_state_dict = torch.load(
63
  "models/aggregator.pt",
64
  map_location="cpu"
65
  )
66
- pipe.aggregator.load_state_dict(aggregator_state_dict, strict=True)
67
  pipe.aggregator.to(device=device, dtype=torch_dtype)
68
 
69
  MAX_SEED = np.iinfo(np.int32).max
@@ -92,8 +120,7 @@ def dynamic_guidance_slider(sampling_steps):
92
  def show_final_preview(preview_row):
93
  return preview_row[-1][0]
94
 
95
- # @spaces.GPU #[uncomment to use ZeroGPU]
96
- @torch.no_grad()
97
  def instantir_restore(
98
  lq, prompt="", steps=30, cfg_scale=7.0, guidance_end=1.0,
99
  creative_restoration=False, seed=3407, height=1024, width=1024, preview_start=0.0):
@@ -101,20 +128,23 @@ def instantir_restore(
101
  if "lcm" not in pipe.unet.active_adapters():
102
  pipe.unet.set_adapter('lcm')
103
  else:
104
- if "default" not in pipe.unet.active_adapters():
105
- pipe.unet.set_adapter('default')
106
 
107
  if isinstance(guidance_end, int):
108
  guidance_end = guidance_end / steps
 
 
109
  if isinstance(preview_start, int):
110
  preview_start = preview_start / steps
 
 
111
  lq = [resize_img(lq.convert("RGB"), size=(width, height))]
112
  generator = torch.Generator(device=device).manual_seed(seed)
113
  timesteps = [
114
  i * (1000//steps) + pipe.scheduler.config.steps_offset for i in range(0, steps)
115
  ]
116
  timesteps = timesteps[::-1]
117
- start_timestep = timesteps[0]
118
 
119
  prompt = PROMPT if len(prompt)==0 else prompt
120
  neg_prompt = NEG_PROMPT
 
1
  import os
2
  import torch
3
+ import spaces
4
+
5
  import numpy as np
6
+ import gradio as gr
7
  from PIL import Image
8
 
9
  from diffusers import DDPMScheduler
 
14
 
15
  from huggingface_hub import hf_hub_download
16
 
17
+
18
+ def resize_img(input_image, max_side=1280, min_side=1024, size=None,
19
+ pad_to_max_side=False, mode=Image.BILINEAR, base_pixel_number=64):
20
+
21
+ w, h = input_image.size
22
+ if size is not None:
23
+ w_resize_new, h_resize_new = size
24
+ else:
25
+ # ratio = min_side / min(h, w)
26
+ # w, h = round(ratio*w), round(ratio*h)
27
+ ratio = max_side / max(h, w)
28
+ input_image = input_image.resize([round(ratio*w), round(ratio*h)], mode)
29
+ w_resize_new = (round(ratio * w) // base_pixel_number) * base_pixel_number
30
+ h_resize_new = (round(ratio * h) // base_pixel_number) * base_pixel_number
31
+ input_image = input_image.resize([w_resize_new, h_resize_new], mode)
32
+
33
+ if pad_to_max_side:
34
+ res = np.ones([max_side, max_side, 3], dtype=np.uint8) * 255
35
+ offset_x = (max_side - w_resize_new) // 2
36
+ offset_y = (max_side - h_resize_new) // 2
37
+ res[offset_y:offset_y+h_resize_new, offset_x:offset_x+w_resize_new] = np.array(input_image)
38
+ input_image = Image.fromarray(res)
39
+ return input_image
40
+
41
+
42
  if not os.path.exists("models/adapter.pt"):
43
  hf_hub_download(repo_id="InstantX/InstantIR", filename="models/adapter.pt", local_dir=".")
44
  if not os.path.exists("models/aggregator.pt"):
 
49
  device = "cuda" if torch.cuda.is_available() else "cpu"
50
  sdxl_repo_id = "stabilityai/stable-diffusion-xl-base-1.0"
51
  dinov2_repo_id = "facebook/dinov2-large"
52
+ lcm_repo_id = "latent-consistency/lcm-lora-sdxl"
53
 
54
  if torch.cuda.is_available():
55
  torch_dtype = torch.float16
 
57
  torch_dtype = torch.float32
58
 
59
  # Load pretrained models.
60
+ print("Initializing pipeline...")
61
  pipe = InstantIRPipeline.from_pretrained(
62
  sdxl_repo_id,
63
  torch_dtype=torch_dtype,
 
74
  # Prepare previewer
75
  lora_alpha = pipe.prepare_previewers("models")
76
  print(f"use lora alpha {lora_alpha}")
77
+ lora_alpha = pipe.prepare_previewers(lcm_repo_id, use_lcm=True)
78
  print(f"use lora alpha {lora_alpha}")
79
  pipe.to(device=device, dtype=torch_dtype)
80
  pipe.scheduler = DDPMScheduler.from_pretrained(sdxl_repo_id, subfolder="scheduler")
 
91
  "models/aggregator.pt",
92
  map_location="cpu"
93
  )
94
+ pipe.aggregator.load_state_dict(aggregator_state_dict)
95
  pipe.aggregator.to(device=device, dtype=torch_dtype)
96
 
97
  MAX_SEED = np.iinfo(np.int32).max
 
120
  def show_final_preview(preview_row):
121
  return preview_row[-1][0]
122
 
123
+ @spaces.GPU
 
124
  def instantir_restore(
125
  lq, prompt="", steps=30, cfg_scale=7.0, guidance_end=1.0,
126
  creative_restoration=False, seed=3407, height=1024, width=1024, preview_start=0.0):
 
128
  if "lcm" not in pipe.unet.active_adapters():
129
  pipe.unet.set_adapter('lcm')
130
  else:
131
+ if "previewer" not in pipe.unet.active_adapters():
132
+ pipe.unet.set_adapter('previewer')
133
 
134
  if isinstance(guidance_end, int):
135
  guidance_end = guidance_end / steps
136
+ elif guidance_end > 1.0:
137
+ guidance_end = guidance_end / steps
138
  if isinstance(preview_start, int):
139
  preview_start = preview_start / steps
140
+ elif preview_start > 1.0:
141
+ preview_start = preview_start / steps
142
  lq = [resize_img(lq.convert("RGB"), size=(width, height))]
143
  generator = torch.Generator(device=device).manual_seed(seed)
144
  timesteps = [
145
  i * (1000//steps) + pipe.scheduler.config.steps_offset for i in range(0, steps)
146
  ]
147
  timesteps = timesteps[::-1]
 
148
 
149
  prompt = PROMPT if len(prompt)==0 else prompt
150
  neg_prompt = NEG_PROMPT
module/attention.py CHANGED
@@ -37,52 +37,6 @@ def create_custom_forward(module):
37
 
38
  return custom_forward
39
 
40
- def get_encoder_trainable_params(encoder):
41
- trainable_params = []
42
-
43
- for module in encoder.modules():
44
- if isinstance(module, ExtractKVTransformerBlock):
45
- # If LORA exists in attn1, train them. Otherwise, attn1 is frozen
46
- # NOTE: not sure if we want it under a different subset
47
- if module.attn1.to_k.lora_layer is not None:
48
- trainable_params.extend(module.attn1.to_k.lora_layer.parameters())
49
- trainable_params.extend(module.attn1.to_v.lora_layer.parameters())
50
- trainable_params.extend(module.attn1.to_q.lora_layer.parameters())
51
- trainable_params.extend(module.attn1.to_out[0].lora_layer.parameters())
52
-
53
- if module.attn2.to_k.lora_layer is not None:
54
- trainable_params.extend(module.attn2.to_k.lora_layer.parameters())
55
- trainable_params.extend(module.attn2.to_v.lora_layer.parameters())
56
- trainable_params.extend(module.attn2.to_q.lora_layer.parameters())
57
- trainable_params.extend(module.attn2.to_out[0].lora_layer.parameters())
58
-
59
- # If LORAs exist in kvcopy layers, train only them
60
- if module.extract_kv1.to_k.lora_layer is not None:
61
- trainable_params.extend(module.extract_kv1.to_k.lora_layer.parameters())
62
- trainable_params.extend(module.extract_kv1.to_v.lora_layer.parameters())
63
- else:
64
- trainable_params.extend(module.extract_kv1.to_k.parameters())
65
- trainable_params.extend(module.extract_kv1.to_v.parameters())
66
-
67
- return trainable_params
68
-
69
- def get_adapter_layers(encoder):
70
- adapter_layers = []
71
- for module in encoder.modules():
72
- if isinstance(module, ExtractKVTransformerBlock):
73
- adapter_layers.append(module.extract_kv2)
74
-
75
- return adapter_layers
76
-
77
- def get_adapter_trainable_params(encoder):
78
- adapter_layers = get_adapter_layers(encoder)
79
- trainable_params = []
80
- for layer in adapter_layers:
81
- trainable_params.extend(layer.to_v.parameters())
82
- trainable_params.extend(layer.to_k.parameters())
83
-
84
- return trainable_params
85
-
86
  def maybe_grad_checkpoint(resnet, attn, hidden_states, temb, encoder_hidden_states, adapter_hidden_states, do_ckpt=True):
87
 
88
  if do_ckpt:
@@ -303,354 +257,3 @@ class GatedSelfAttentionDense(nn.Module):
303
  x = x + self.alpha_dense.tanh() * self.ff(self.norm2(x))
304
 
305
  return x
306
-
307
-
308
- @maybe_allow_in_graph
309
- class ExtractKVTransformerBlock(nn.Module):
310
- r"""
311
- A Transformer block that also outputs KV metrics.
312
-
313
- Parameters:
314
- dim (`int`): The number of channels in the input and output.
315
- num_attention_heads (`int`): The number of heads to use for multi-head attention.
316
- attention_head_dim (`int`): The number of channels in each head.
317
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
318
- cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
319
- activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
320
- num_embeds_ada_norm (:
321
- obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
322
- attention_bias (:
323
- obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
324
- only_cross_attention (`bool`, *optional*):
325
- Whether to use only cross-attention layers. In this case two cross attention layers are used.
326
- double_self_attention (`bool`, *optional*):
327
- Whether to use two self-attention layers. In this case no cross attention layers are used.
328
- upcast_attention (`bool`, *optional*):
329
- Whether to upcast the attention computation to float32. This is useful for mixed precision training.
330
- norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
331
- Whether to use learnable elementwise affine parameters for normalization.
332
- norm_type (`str`, *optional*, defaults to `"layer_norm"`):
333
- The normalization layer to use. Can be `"layer_norm"`, `"ada_norm"` or `"ada_norm_zero"`.
334
- final_dropout (`bool` *optional*, defaults to False):
335
- Whether to apply a final dropout after the last feed-forward layer.
336
- attention_type (`str`, *optional*, defaults to `"default"`):
337
- The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`.
338
- positional_embeddings (`str`, *optional*, defaults to `None`):
339
- The type of positional embeddings to apply to.
340
- num_positional_embeddings (`int`, *optional*, defaults to `None`):
341
- The maximum number of positional embeddings to apply.
342
- """
343
-
344
- def __init__(
345
- self,
346
- dim: int, # Originally hidden_size
347
- num_attention_heads: int,
348
- attention_head_dim: int,
349
- dropout=0.0,
350
- cross_attention_dim: Optional[int] = None,
351
- activation_fn: str = "geglu",
352
- num_embeds_ada_norm: Optional[int] = None,
353
- attention_bias: bool = False,
354
- only_cross_attention: bool = False,
355
- double_self_attention: bool = False,
356
- upcast_attention: bool = False,
357
- norm_elementwise_affine: bool = True,
358
- norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single', 'ada_norm_continuous', 'layer_norm_i2vgen'
359
- norm_eps: float = 1e-5,
360
- final_dropout: bool = False,
361
- attention_type: str = "default",
362
- positional_embeddings: Optional[str] = None,
363
- num_positional_embeddings: Optional[int] = None,
364
- ada_norm_continous_conditioning_embedding_dim: Optional[int] = None,
365
- ada_norm_bias: Optional[int] = None,
366
- ff_inner_dim: Optional[int] = None,
367
- ff_bias: bool = True,
368
- attention_out_bias: bool = True,
369
- extract_self_attention_kv: bool = False,
370
- extract_cross_attention_kv: bool = False,
371
- ):
372
- super().__init__()
373
- self.only_cross_attention = only_cross_attention
374
-
375
- # We keep these boolean flags for backward-compatibility.
376
- self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
377
- self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
378
- self.use_ada_layer_norm_single = norm_type == "ada_norm_single"
379
- self.use_layer_norm = norm_type == "layer_norm"
380
- self.use_ada_layer_norm_continuous = norm_type == "ada_norm_continuous"
381
-
382
- if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
383
- raise ValueError(
384
- f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
385
- f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
386
- )
387
-
388
- self.norm_type = norm_type
389
- self.num_embeds_ada_norm = num_embeds_ada_norm
390
-
391
- if positional_embeddings and (num_positional_embeddings is None):
392
- raise ValueError(
393
- "If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined."
394
- )
395
-
396
- if positional_embeddings == "sinusoidal":
397
- self.pos_embed = SinusoidalPositionalEmbedding(dim, max_seq_length=num_positional_embeddings)
398
- else:
399
- self.pos_embed = None
400
-
401
- # Define 3 blocks. Each block has its own normalization layer.
402
- # 1. Self-Attn
403
- if norm_type == "ada_norm":
404
- self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
405
- elif norm_type == "ada_norm_zero":
406
- self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
407
- elif norm_type == "ada_norm_continuous":
408
- self.norm1 = AdaLayerNormContinuous(
409
- dim,
410
- ada_norm_continous_conditioning_embedding_dim,
411
- norm_elementwise_affine,
412
- norm_eps,
413
- ada_norm_bias,
414
- "rms_norm",
415
- )
416
- else:
417
- self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
418
-
419
- self.attn1 = Attention(
420
- query_dim=dim,
421
- heads=num_attention_heads,
422
- dim_head=attention_head_dim,
423
- dropout=dropout,
424
- bias=attention_bias,
425
- cross_attention_dim=cross_attention_dim if only_cross_attention else None,
426
- upcast_attention=upcast_attention,
427
- out_bias=attention_out_bias,
428
- )
429
- if extract_self_attention_kv:
430
- self.extract_kv1 = KVCopy(cross_attention_dim=cross_attention_dim if only_cross_attention else None, inner_dim=dim)
431
-
432
- # 2. Cross-Attn
433
- if cross_attention_dim is not None or double_self_attention:
434
- # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
435
- # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
436
- # the second cross attention block.
437
- if norm_type == "ada_norm":
438
- self.norm2 = AdaLayerNorm(dim, num_embeds_ada_norm)
439
- elif norm_type == "ada_norm_continuous":
440
- self.norm2 = AdaLayerNormContinuous(
441
- dim,
442
- ada_norm_continous_conditioning_embedding_dim,
443
- norm_elementwise_affine,
444
- norm_eps,
445
- ada_norm_bias,
446
- "rms_norm",
447
- )
448
- else:
449
- self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
450
-
451
- self.attn2 = Attention(
452
- query_dim=dim,
453
- cross_attention_dim=cross_attention_dim if not double_self_attention else None,
454
- heads=num_attention_heads,
455
- dim_head=attention_head_dim,
456
- dropout=dropout,
457
- bias=attention_bias,
458
- upcast_attention=upcast_attention,
459
- out_bias=attention_out_bias,
460
- ) # is self-attn if encoder_hidden_states is none
461
- if extract_cross_attention_kv:
462
- self.extract_kv2 = KVCopy(cross_attention_dim=None, inner_dim=dim)
463
- else:
464
- self.norm2 = None
465
- self.attn2 = None
466
-
467
- # 3. Feed-forward
468
- if norm_type == "ada_norm_continuous":
469
- self.norm3 = AdaLayerNormContinuous(
470
- dim,
471
- ada_norm_continous_conditioning_embedding_dim,
472
- norm_elementwise_affine,
473
- norm_eps,
474
- ada_norm_bias,
475
- "layer_norm",
476
- )
477
-
478
- elif norm_type in ["ada_norm_zero", "ada_norm", "layer_norm", "ada_norm_continuous"]:
479
- self.norm3 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
480
- elif norm_type == "layer_norm_i2vgen":
481
- self.norm3 = None
482
-
483
- self.ff = FeedForward(
484
- dim,
485
- dropout=dropout,
486
- activation_fn=activation_fn,
487
- final_dropout=final_dropout,
488
- inner_dim=ff_inner_dim,
489
- bias=ff_bias,
490
- )
491
-
492
- # 4. Fuser
493
- if attention_type == "gated" or attention_type == "gated-text-image":
494
- self.fuser = GatedSelfAttentionDense(dim, cross_attention_dim, num_attention_heads, attention_head_dim)
495
-
496
- # 5. Scale-shift for PixArt-Alpha.
497
- if norm_type == "ada_norm_single":
498
- self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)
499
-
500
- # let chunk size default to None
501
- self._chunk_size = None
502
- self._chunk_dim = 0
503
-
504
- def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
505
- # Sets chunk feed-forward
506
- self._chunk_size = chunk_size
507
- self._chunk_dim = dim
508
-
509
- def forward(
510
- self,
511
- hidden_states: torch.FloatTensor,
512
- attention_mask: Optional[torch.FloatTensor] = None,
513
- encoder_hidden_states: Optional[torch.FloatTensor] = None,
514
- encoder_attention_mask: Optional[torch.FloatTensor] = None,
515
- timestep: Optional[torch.LongTensor] = None,
516
- cross_attention_kwargs: Dict[str, Any] = None,
517
- class_labels: Optional[torch.LongTensor] = None,
518
- added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
519
- ) -> torch.FloatTensor:
520
- if cross_attention_kwargs is not None:
521
- if cross_attention_kwargs.get("scale", None) is not None:
522
- logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
523
-
524
- # Notice that normalization is always applied before the real computation in the following blocks.
525
- # 0. Self-Attention
526
- batch_size = hidden_states.shape[0]
527
-
528
- if self.norm_type == "ada_norm":
529
- norm_hidden_states = self.norm1(hidden_states, timestep)
530
- elif self.norm_type == "ada_norm_zero":
531
- norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
532
- hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
533
- )
534
- elif self.norm_type in ["layer_norm", "layer_norm_i2vgen"]:
535
- norm_hidden_states = self.norm1(hidden_states)
536
- elif self.norm_type == "ada_norm_continuous":
537
- norm_hidden_states = self.norm1(hidden_states, added_cond_kwargs["pooled_text_emb"])
538
- elif self.norm_type == "ada_norm_single":
539
- shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
540
- self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
541
- ).chunk(6, dim=1)
542
- norm_hidden_states = self.norm1(hidden_states)
543
- norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
544
- norm_hidden_states = norm_hidden_states.squeeze(1)
545
- else:
546
- raise ValueError("Incorrect norm used")
547
-
548
- if self.pos_embed is not None:
549
- norm_hidden_states = self.pos_embed(norm_hidden_states)
550
-
551
- # 1. Prepare GLIGEN inputs
552
- cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
553
- gligen_kwargs = cross_attention_kwargs.pop("gligen", None)
554
- kv_drop_idx = cross_attention_kwargs.pop("kv_drop_idx", None)
555
-
556
- if hasattr(self, "extract_kv1"):
557
- kv_out_self = self.extract_kv1(norm_hidden_states)
558
- if kv_drop_idx is not None:
559
- zero_kv_out_self_k = torch.zeros_like(kv_out_self.k)
560
- kv_out_self.k[kv_drop_idx] = zero_kv_out_self_k[kv_drop_idx]
561
- zero_kv_out_self_v = torch.zeros_like(kv_out_self.v)
562
- kv_out_self.v[kv_drop_idx] = zero_kv_out_self_v[kv_drop_idx]
563
- else:
564
- kv_out_self = None
565
- attn_output = self.attn1(
566
- norm_hidden_states,
567
- encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
568
- attention_mask=attention_mask,
569
- **cross_attention_kwargs,
570
- )
571
- if self.norm_type == "ada_norm_zero":
572
- attn_output = gate_msa.unsqueeze(1) * attn_output
573
- elif self.norm_type == "ada_norm_single":
574
- attn_output = gate_msa * attn_output
575
-
576
- hidden_states = attn_output + hidden_states
577
- if hidden_states.ndim == 4:
578
- hidden_states = hidden_states.squeeze(1)
579
-
580
- # 1.2 GLIGEN Control
581
- if gligen_kwargs is not None:
582
- hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"])
583
-
584
- # 3. Cross-Attention
585
- if self.attn2 is not None:
586
- if self.norm_type == "ada_norm":
587
- norm_hidden_states = self.norm2(hidden_states, timestep)
588
- elif self.norm_type in ["ada_norm_zero", "layer_norm", "layer_norm_i2vgen"]:
589
- norm_hidden_states = self.norm2(hidden_states)
590
- elif self.norm_type == "ada_norm_single":
591
- # For PixArt norm2 isn't applied here:
592
- # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
593
- norm_hidden_states = hidden_states
594
- elif self.norm_type == "ada_norm_continuous":
595
- norm_hidden_states = self.norm2(hidden_states, added_cond_kwargs["pooled_text_emb"])
596
- else:
597
- raise ValueError("Incorrect norm")
598
-
599
- if self.pos_embed is not None and self.norm_type != "ada_norm_single":
600
- norm_hidden_states = self.pos_embed(norm_hidden_states)
601
-
602
- attn_output = self.attn2(
603
- norm_hidden_states,
604
- encoder_hidden_states=encoder_hidden_states,
605
- attention_mask=encoder_attention_mask,
606
- temb=timestep,
607
- **cross_attention_kwargs,
608
- )
609
- hidden_states = attn_output + hidden_states
610
-
611
- if hasattr(self, "extract_kv2"):
612
- kv_out_cross = self.extract_kv2(hidden_states)
613
- if kv_drop_idx is not None:
614
- zero_kv_out_cross_k = torch.zeros_like(kv_out_cross.k)
615
- kv_out_cross.k[kv_drop_idx] = zero_kv_out_cross_k[kv_drop_idx]
616
- zero_kv_out_cross_v = torch.zeros_like(kv_out_cross.v)
617
- kv_out_cross.v[kv_drop_idx] = zero_kv_out_cross_v[kv_drop_idx]
618
- else:
619
- kv_out_cross = None
620
-
621
- # 4. Feed-forward
622
- # i2vgen doesn't have this norm 🤷‍♂️
623
- if self.norm_type == "ada_norm_continuous":
624
- norm_hidden_states = self.norm3(hidden_states, added_cond_kwargs["pooled_text_emb"])
625
- elif not self.norm_type == "ada_norm_single":
626
- norm_hidden_states = self.norm3(hidden_states)
627
-
628
- if self.norm_type == "ada_norm_zero":
629
- norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
630
-
631
- if self.norm_type == "ada_norm_single":
632
- norm_hidden_states = self.norm2(hidden_states)
633
- norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
634
-
635
- if self._chunk_size is not None:
636
- # "feed_forward_chunk_size" can be used to save memory
637
- ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size)
638
- else:
639
- ff_output = self.ff(norm_hidden_states)
640
-
641
- if self.norm_type == "ada_norm_zero":
642
- ff_output = gate_mlp.unsqueeze(1) * ff_output
643
- elif self.norm_type == "ada_norm_single":
644
- ff_output = gate_mlp * ff_output
645
-
646
- hidden_states = ff_output + hidden_states
647
- if hidden_states.ndim == 4:
648
- hidden_states = hidden_states.squeeze(1)
649
-
650
- return hidden_states, AttentionCache(self_attention=kv_out_self, cross_attention=kv_out_cross)
651
-
652
- def init_kv_extraction(self):
653
- if hasattr(self, "extract_kv1"):
654
- self.extract_kv1.init_kv_copy(self.attn1)
655
- if hasattr(self, "extract_kv2"):
656
- self.extract_kv2.init_kv_copy(self.attn1)
 
37
 
38
  return custom_forward
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  def maybe_grad_checkpoint(resnet, attn, hidden_states, temb, encoder_hidden_states, adapter_hidden_states, do_ckpt=True):
41
 
42
  if do_ckpt:
 
257
  x = x + self.alpha_dense.tanh() * self.ff(self.norm2(x))
258
 
259
  return x
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
module/transformers/transformer_2d_ExtractKV.py DELETED
@@ -1,595 +0,0 @@
1
- # Copy from diffusers.models.transformers.transformer_2d.py
2
-
3
- # Copyright 2024 The HuggingFace Team. All rights reserved.
4
- #
5
- # Licensed under the Apache License, Version 2.0 (the "License");
6
- # you may not use this file except in compliance with the License.
7
- # You may obtain a copy of the License at
8
- #
9
- # http://www.apache.org/licenses/LICENSE-2.0
10
- #
11
- # Unless required by applicable law or agreed to in writing, software
12
- # distributed under the License is distributed on an "AS IS" BASIS,
13
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- # See the License for the specific language governing permissions and
15
- # limitations under the License.
16
- from dataclasses import dataclass
17
- from typing import Any, Dict, Optional
18
-
19
- import torch
20
- import torch.nn.functional as F
21
- from torch import nn
22
-
23
- from diffusers.configuration_utils import ConfigMixin, register_to_config
24
- from diffusers.utils import BaseOutput, deprecate, is_torch_version, logging
25
- from diffusers.models.attention import BasicTransformerBlock
26
- from diffusers.models.embeddings import ImagePositionalEmbeddings, PatchEmbed, PixArtAlphaTextProjection
27
- from diffusers.models.modeling_utils import ModelMixin
28
- from diffusers.models.normalization import AdaLayerNormSingle
29
-
30
- from module.attention import ExtractKVTransformerBlock
31
-
32
-
33
- logger = logging.get_logger(__name__) # pylint: disable=invalid-name
34
-
35
-
36
- @dataclass
37
- class ExtractKVTransformer2DModelOutput(BaseOutput):
38
- """
39
- The output of [`ExtractKVTransformer2DModel`].
40
-
41
- Args:
42
- sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DModel`] is discrete):
43
- The hidden states output conditioned on the `encoder_hidden_states` input. If discrete, returns probability
44
- distributions for the unnoised latent pixels.
45
- """
46
-
47
- sample: torch.FloatTensor
48
- cached_kvs: Dict[str, Any] = None
49
-
50
-
51
- class ExtractKVTransformer2DModel(ModelMixin, ConfigMixin):
52
- """
53
- A 2D Transformer model for image-like data which also outputs CrossAttention KV metrics.
54
-
55
- Parameters:
56
- num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
57
- attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
58
- in_channels (`int`, *optional*):
59
- The number of channels in the input and output (specify if the input is **continuous**).
60
- num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
61
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
62
- cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
63
- sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**).
64
- This is fixed during training since it is used to learn a number of position embeddings.
65
- num_vector_embeds (`int`, *optional*):
66
- The number of classes of the vector embeddings of the latent pixels (specify if the input is **discrete**).
67
- Includes the class for the masked latent pixel.
68
- activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to use in feed-forward.
69
- num_embeds_ada_norm ( `int`, *optional*):
70
- The number of diffusion steps used during training. Pass if at least one of the norm_layers is
71
- `AdaLayerNorm`. This is fixed during training since it is used to learn a number of embeddings that are
72
- added to the hidden states.
73
-
74
- During inference, you can denoise for up to but not more steps than `num_embeds_ada_norm`.
75
- attention_bias (`bool`, *optional*):
76
- Configure if the `TransformerBlocks` attention should contain a bias parameter.
77
- """
78
-
79
- _supports_gradient_checkpointing = True
80
- _no_split_modules = ["BasicTransformerBlock"]
81
-
82
- @register_to_config
83
- def __init__(
84
- self,
85
- num_attention_heads: int = 16,
86
- attention_head_dim: int = 88,
87
- in_channels: Optional[int] = None,
88
- out_channels: Optional[int] = None,
89
- num_layers: int = 1,
90
- dropout: float = 0.0,
91
- norm_num_groups: int = 32,
92
- cross_attention_dim: Optional[int] = None,
93
- attention_bias: bool = False,
94
- sample_size: Optional[int] = None,
95
- num_vector_embeds: Optional[int] = None,
96
- patch_size: Optional[int] = None,
97
- activation_fn: str = "geglu",
98
- num_embeds_ada_norm: Optional[int] = None,
99
- use_linear_projection: bool = False,
100
- only_cross_attention: bool = False,
101
- double_self_attention: bool = False,
102
- upcast_attention: bool = False,
103
- norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single', 'ada_norm_continuous', 'layer_norm_i2vgen'
104
- norm_elementwise_affine: bool = True,
105
- norm_eps: float = 1e-5,
106
- attention_type: str = "default",
107
- caption_channels: int = None,
108
- interpolation_scale: float = None,
109
- use_additional_conditions: Optional[bool] = None,
110
- extract_self_attention_kv: bool = False,
111
- extract_cross_attention_kv: bool = False,
112
- ):
113
- super().__init__()
114
-
115
- # Validate inputs.
116
- if patch_size is not None:
117
- if norm_type not in ["ada_norm", "ada_norm_zero", "ada_norm_single"]:
118
- raise NotImplementedError(
119
- f"Forward pass is not implemented when `patch_size` is not None and `norm_type` is '{norm_type}'."
120
- )
121
- elif norm_type in ["ada_norm", "ada_norm_zero"] and num_embeds_ada_norm is None:
122
- raise ValueError(
123
- f"When using a `patch_size` and this `norm_type` ({norm_type}), `num_embeds_ada_norm` cannot be None."
124
- )
125
-
126
- # Set some common variables used across the board.
127
- self.use_linear_projection = use_linear_projection
128
- self.interpolation_scale = interpolation_scale
129
- self.caption_channels = caption_channels
130
- self.num_attention_heads = num_attention_heads
131
- self.attention_head_dim = attention_head_dim
132
- self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim
133
- self.in_channels = in_channels
134
- self.out_channels = in_channels if out_channels is None else out_channels
135
- self.gradient_checkpointing = False
136
- if use_additional_conditions is None:
137
- if norm_type == "ada_norm_single" and sample_size == 128:
138
- use_additional_conditions = True
139
- else:
140
- use_additional_conditions = False
141
- self.use_additional_conditions = use_additional_conditions
142
- self.extract_self_attention_kv = extract_self_attention_kv
143
- self.extract_cross_attention_kv = extract_cross_attention_kv
144
-
145
- # 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)`
146
- # Define whether input is continuous or discrete depending on configuration
147
- self.is_input_continuous = (in_channels is not None) and (patch_size is None)
148
- self.is_input_vectorized = num_vector_embeds is not None
149
- self.is_input_patches = in_channels is not None and patch_size is not None
150
-
151
- if norm_type == "layer_norm" and num_embeds_ada_norm is not None:
152
- deprecation_message = (
153
- f"The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or"
154
- " incorrectly set to `'layer_norm'`. Make sure to set `norm_type` to `'ada_norm'` in the config."
155
- " Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect"
156
- " results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it"
157
- " would be very nice if you could open a Pull request for the `transformer/config.json` file"
158
- )
159
- deprecate("norm_type!=num_embeds_ada_norm", "1.0.0", deprecation_message, standard_warn=False)
160
- norm_type = "ada_norm"
161
-
162
- if self.is_input_continuous and self.is_input_vectorized:
163
- raise ValueError(
164
- f"Cannot define both `in_channels`: {in_channels} and `num_vector_embeds`: {num_vector_embeds}. Make"
165
- " sure that either `in_channels` or `num_vector_embeds` is None."
166
- )
167
- elif self.is_input_vectorized and self.is_input_patches:
168
- raise ValueError(
169
- f"Cannot define both `num_vector_embeds`: {num_vector_embeds} and `patch_size`: {patch_size}. Make"
170
- " sure that either `num_vector_embeds` or `num_patches` is None."
171
- )
172
- elif not self.is_input_continuous and not self.is_input_vectorized and not self.is_input_patches:
173
- raise ValueError(
174
- f"Has to define `in_channels`: {in_channels}, `num_vector_embeds`: {num_vector_embeds}, or patch_size:"
175
- f" {patch_size}. Make sure that `in_channels`, `num_vector_embeds` or `num_patches` is not None."
176
- )
177
-
178
- # 2. Initialize the right blocks.
179
- # These functions follow a common structure:
180
- # a. Initialize the input blocks. b. Initialize the transformer blocks.
181
- # c. Initialize the output blocks and other projection blocks when necessary.
182
- if self.is_input_continuous:
183
- self._init_continuous_input(norm_type=norm_type)
184
- elif self.is_input_vectorized:
185
- self._init_vectorized_inputs(norm_type=norm_type)
186
- elif self.is_input_patches:
187
- self._init_patched_inputs(norm_type=norm_type)
188
-
189
- def _init_continuous_input(self, norm_type):
190
- self.norm = torch.nn.GroupNorm(
191
- num_groups=self.config.norm_num_groups, num_channels=self.in_channels, eps=1e-6, affine=True
192
- )
193
- if self.use_linear_projection:
194
- self.proj_in = torch.nn.Linear(self.in_channels, self.inner_dim)
195
- else:
196
- self.proj_in = torch.nn.Conv2d(self.in_channels, self.inner_dim, kernel_size=1, stride=1, padding=0)
197
-
198
- self.transformer_blocks = nn.ModuleList(
199
- [
200
- ExtractKVTransformerBlock(
201
- self.inner_dim,
202
- self.config.num_attention_heads,
203
- self.config.attention_head_dim,
204
- dropout=self.config.dropout,
205
- cross_attention_dim=self.config.cross_attention_dim,
206
- activation_fn=self.config.activation_fn,
207
- num_embeds_ada_norm=self.config.num_embeds_ada_norm,
208
- attention_bias=self.config.attention_bias,
209
- only_cross_attention=self.config.only_cross_attention,
210
- double_self_attention=self.config.double_self_attention,
211
- upcast_attention=self.config.upcast_attention,
212
- norm_type=norm_type,
213
- norm_elementwise_affine=self.config.norm_elementwise_affine,
214
- norm_eps=self.config.norm_eps,
215
- attention_type=self.config.attention_type,
216
- extract_self_attention_kv=self.config.extract_self_attention_kv,
217
- extract_cross_attention_kv=self.config.extract_cross_attention_kv,
218
- )
219
- for _ in range(self.config.num_layers)
220
- ]
221
- )
222
-
223
- if self.use_linear_projection:
224
- self.proj_out = torch.nn.Linear(self.inner_dim, self.out_channels)
225
- else:
226
- self.proj_out = torch.nn.Conv2d(self.inner_dim, self.out_channels, kernel_size=1, stride=1, padding=0)
227
-
228
- def _init_vectorized_inputs(self, norm_type):
229
- assert self.config.sample_size is not None, "Transformer2DModel over discrete input must provide sample_size"
230
- assert (
231
- self.config.num_vector_embeds is not None
232
- ), "Transformer2DModel over discrete input must provide num_embed"
233
-
234
- self.height = self.config.sample_size
235
- self.width = self.config.sample_size
236
- self.num_latent_pixels = self.height * self.width
237
-
238
- self.latent_image_embedding = ImagePositionalEmbeddings(
239
- num_embed=self.config.num_vector_embeds, embed_dim=self.inner_dim, height=self.height, width=self.width
240
- )
241
-
242
- self.transformer_blocks = nn.ModuleList(
243
- [
244
- ExtractKVTransformerBlock(
245
- self.inner_dim,
246
- self.config.num_attention_heads,
247
- self.config.attention_head_dim,
248
- dropout=self.config.dropout,
249
- cross_attention_dim=self.config.cross_attention_dim,
250
- activation_fn=self.config.activation_fn,
251
- num_embeds_ada_norm=self.config.num_embeds_ada_norm,
252
- attention_bias=self.config.attention_bias,
253
- only_cross_attention=self.config.only_cross_attention,
254
- double_self_attention=self.config.double_self_attention,
255
- upcast_attention=self.config.upcast_attention,
256
- norm_type=norm_type,
257
- norm_elementwise_affine=self.config.norm_elementwise_affine,
258
- norm_eps=self.config.norm_eps,
259
- attention_type=self.config.attention_type,
260
- extract_self_attention_kv=self.config.extract_self_attention_kv,
261
- extract_cross_attention_kv=self.config.extract_cross_attention_kv,
262
- )
263
- for _ in range(self.config.num_layers)
264
- ]
265
- )
266
-
267
- self.norm_out = nn.LayerNorm(self.inner_dim)
268
- self.out = nn.Linear(self.inner_dim, self.config.num_vector_embeds - 1)
269
-
270
- def _init_patched_inputs(self, norm_type):
271
- assert self.config.sample_size is not None, "Transformer2DModel over patched input must provide sample_size"
272
-
273
- self.height = self.config.sample_size
274
- self.width = self.config.sample_size
275
-
276
- self.patch_size = self.config.patch_size
277
- interpolation_scale = (
278
- self.config.interpolation_scale
279
- if self.config.interpolation_scale is not None
280
- else max(self.config.sample_size // 64, 1)
281
- )
282
- self.pos_embed = PatchEmbed(
283
- height=self.config.sample_size,
284
- width=self.config.sample_size,
285
- patch_size=self.config.patch_size,
286
- in_channels=self.in_channels,
287
- embed_dim=self.inner_dim,
288
- interpolation_scale=interpolation_scale,
289
- )
290
-
291
- self.transformer_blocks = nn.ModuleList(
292
- [
293
- ExtractKVTransformerBlock(
294
- self.inner_dim,
295
- self.config.num_attention_heads,
296
- self.config.attention_head_dim,
297
- dropout=self.config.dropout,
298
- cross_attention_dim=self.config.cross_attention_dim,
299
- activation_fn=self.config.activation_fn,
300
- num_embeds_ada_norm=self.config.num_embeds_ada_norm,
301
- attention_bias=self.config.attention_bias,
302
- only_cross_attention=self.config.only_cross_attention,
303
- double_self_attention=self.config.double_self_attention,
304
- upcast_attention=self.config.upcast_attention,
305
- norm_type=norm_type,
306
- norm_elementwise_affine=self.config.norm_elementwise_affine,
307
- norm_eps=self.config.norm_eps,
308
- attention_type=self.config.attention_type,
309
- extract_self_attention_kv=self.config.extract_self_attention_kv,
310
- extract_cross_attention_kv=self.config.extract_cross_attention_kv,
311
- )
312
- for _ in range(self.config.num_layers)
313
- ]
314
- )
315
-
316
- if self.config.norm_type != "ada_norm_single":
317
- self.norm_out = nn.LayerNorm(self.inner_dim, elementwise_affine=False, eps=1e-6)
318
- self.proj_out_1 = nn.Linear(self.inner_dim, 2 * self.inner_dim)
319
- self.proj_out_2 = nn.Linear(
320
- self.inner_dim, self.config.patch_size * self.config.patch_size * self.out_channels
321
- )
322
- elif self.config.norm_type == "ada_norm_single":
323
- self.norm_out = nn.LayerNorm(self.inner_dim, elementwise_affine=False, eps=1e-6)
324
- self.scale_shift_table = nn.Parameter(torch.randn(2, self.inner_dim) / self.inner_dim**0.5)
325
- self.proj_out = nn.Linear(
326
- self.inner_dim, self.config.patch_size * self.config.patch_size * self.out_channels
327
- )
328
-
329
- # PixArt-Alpha blocks.
330
- self.adaln_single = None
331
- if self.config.norm_type == "ada_norm_single":
332
- # TODO(Sayak, PVP) clean this, for now we use sample size to determine whether to use
333
- # additional conditions until we find better name
334
- self.adaln_single = AdaLayerNormSingle(
335
- self.inner_dim, use_additional_conditions=self.use_additional_conditions
336
- )
337
-
338
- self.caption_projection = None
339
- if self.caption_channels is not None:
340
- self.caption_projection = PixArtAlphaTextProjection(
341
- in_features=self.caption_channels, hidden_size=self.inner_dim
342
- )
343
-
344
- def _set_gradient_checkpointing(self, module, value=False):
345
- if hasattr(module, "gradient_checkpointing"):
346
- module.gradient_checkpointing = value
347
-
348
- def forward(
349
- self,
350
- hidden_states: torch.Tensor,
351
- encoder_hidden_states: Optional[torch.Tensor] = None,
352
- timestep: Optional[torch.LongTensor] = None,
353
- added_cond_kwargs: Dict[str, torch.Tensor] = None,
354
- class_labels: Optional[torch.LongTensor] = None,
355
- cross_attention_kwargs: Dict[str, Any] = None,
356
- attention_mask: Optional[torch.Tensor] = None,
357
- encoder_attention_mask: Optional[torch.Tensor] = None,
358
- return_dict: bool = True,
359
- ):
360
- """
361
- The [`Transformer2DModel`] forward method.
362
-
363
- Args:
364
- hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous):
365
- Input `hidden_states`.
366
- encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
367
- Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
368
- self-attention.
369
- timestep ( `torch.LongTensor`, *optional*):
370
- Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
371
- class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
372
- Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in
373
- `AdaLayerZeroNorm`.
374
- cross_attention_kwargs ( `Dict[str, Any]`, *optional*):
375
- A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
376
- `self.processor` in
377
- [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
378
- attention_mask ( `torch.Tensor`, *optional*):
379
- An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
380
- is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
381
- negative values to the attention scores corresponding to "discard" tokens.
382
- encoder_attention_mask ( `torch.Tensor`, *optional*):
383
- Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:
384
-
385
- * Mask `(batch, sequence_length)` True = keep, False = discard.
386
- * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard.
387
-
388
- If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format
389
- above. This bias will be added to the cross-attention scores.
390
- return_dict (`bool`, *optional*, defaults to `True`):
391
- Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
392
- tuple.
393
-
394
- Returns:
395
- If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
396
- `tuple` where the first element is the sample tensor.
397
- """
398
- if cross_attention_kwargs is not None:
399
- if cross_attention_kwargs.get("scale", None) is not None:
400
- logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
401
- # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
402
- # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
403
- # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
404
- # expects mask of shape:
405
- # [batch, key_tokens]
406
- # adds singleton query_tokens dimension:
407
- # [batch, 1, key_tokens]
408
- # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
409
- # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
410
- # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
411
- if attention_mask is not None and attention_mask.ndim == 2:
412
- # assume that mask is expressed as:
413
- # (1 = keep, 0 = discard)
414
- # convert mask into a bias that can be added to attention scores:
415
- # (keep = +0, discard = -10000.0)
416
- attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
417
- attention_mask = attention_mask.unsqueeze(1)
418
-
419
- # convert encoder_attention_mask to a bias the same way we do for attention_mask
420
- if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
421
- encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0
422
- encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
423
-
424
- # 1. Input
425
- if self.is_input_continuous:
426
- batch_size, _, height, width = hidden_states.shape
427
- residual = hidden_states
428
- hidden_states, inner_dim = self._operate_on_continuous_inputs(hidden_states)
429
- elif self.is_input_vectorized:
430
- hidden_states = self.latent_image_embedding(hidden_states)
431
- elif self.is_input_patches:
432
- height, width = hidden_states.shape[-2] // self.patch_size, hidden_states.shape[-1] // self.patch_size
433
- hidden_states, encoder_hidden_states, timestep, embedded_timestep = self._operate_on_patched_inputs(
434
- hidden_states, encoder_hidden_states, timestep, added_cond_kwargs
435
- )
436
-
437
- # 2. Blocks
438
- extracted_kvs = {}
439
- for block in self.transformer_blocks:
440
- if self.training and self.gradient_checkpointing:
441
-
442
- def create_custom_forward(module, return_dict=None):
443
- def custom_forward(*inputs):
444
- if return_dict is not None:
445
- return module(*inputs, return_dict=return_dict)
446
- else:
447
- return module(*inputs)
448
-
449
- return custom_forward
450
-
451
- ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
452
- hidden_states, extracted_kv = torch.utils.checkpoint.checkpoint(
453
- create_custom_forward(block),
454
- hidden_states,
455
- attention_mask,
456
- encoder_hidden_states,
457
- encoder_attention_mask,
458
- timestep,
459
- cross_attention_kwargs,
460
- class_labels,
461
- **ckpt_kwargs,
462
- )
463
- else:
464
- hidden_states, extracted_kv = block(
465
- hidden_states,
466
- attention_mask=attention_mask,
467
- encoder_hidden_states=encoder_hidden_states,
468
- encoder_attention_mask=encoder_attention_mask,
469
- timestep=timestep,
470
- cross_attention_kwargs=cross_attention_kwargs,
471
- class_labels=class_labels,
472
- )
473
-
474
- if extracted_kv:
475
- extracted_kvs[block.full_name] = extracted_kv
476
-
477
- # 3. Output
478
- if self.is_input_continuous:
479
- output = self._get_output_for_continuous_inputs(
480
- hidden_states=hidden_states,
481
- residual=residual,
482
- batch_size=batch_size,
483
- height=height,
484
- width=width,
485
- inner_dim=inner_dim,
486
- )
487
- elif self.is_input_vectorized:
488
- output = self._get_output_for_vectorized_inputs(hidden_states)
489
- elif self.is_input_patches:
490
- output = self._get_output_for_patched_inputs(
491
- hidden_states=hidden_states,
492
- timestep=timestep,
493
- class_labels=class_labels,
494
- embedded_timestep=embedded_timestep,
495
- height=height,
496
- width=width,
497
- )
498
-
499
- if not return_dict:
500
- return (output, extracted_kvs)
501
-
502
- return ExtractKVTransformer2DModelOutput(sample=output, cached_kvs=extracted_kvs)
503
-
504
- def init_kv_extraction(self):
505
- for block in self.transformer_blocks:
506
- block.init_kv_extraction()
507
-
508
- def _operate_on_continuous_inputs(self, hidden_states):
509
- batch, _, height, width = hidden_states.shape
510
- hidden_states = self.norm(hidden_states)
511
-
512
- if not self.use_linear_projection:
513
- hidden_states = self.proj_in(hidden_states)
514
- inner_dim = hidden_states.shape[1]
515
- hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)
516
- else:
517
- inner_dim = hidden_states.shape[1]
518
- hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)
519
- hidden_states = self.proj_in(hidden_states)
520
-
521
- return hidden_states, inner_dim
522
-
523
- def _operate_on_patched_inputs(self, hidden_states, encoder_hidden_states, timestep, added_cond_kwargs):
524
- batch_size = hidden_states.shape[0]
525
- hidden_states = self.pos_embed(hidden_states)
526
- embedded_timestep = None
527
-
528
- if self.adaln_single is not None:
529
- if self.use_additional_conditions and added_cond_kwargs is None:
530
- raise ValueError(
531
- "`added_cond_kwargs` cannot be None when using additional conditions for `adaln_single`."
532
- )
533
- timestep, embedded_timestep = self.adaln_single(
534
- timestep, added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_states.dtype
535
- )
536
-
537
- if self.caption_projection is not None:
538
- encoder_hidden_states = self.caption_projection(encoder_hidden_states)
539
- encoder_hidden_states = encoder_hidden_states.view(batch_size, -1, hidden_states.shape[-1])
540
-
541
- return hidden_states, encoder_hidden_states, timestep, embedded_timestep
542
-
543
- def _get_output_for_continuous_inputs(self, hidden_states, residual, batch_size, height, width, inner_dim):
544
- if not self.use_linear_projection:
545
- hidden_states = (
546
- hidden_states.reshape(batch_size, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()
547
- )
548
- hidden_states = self.proj_out(hidden_states)
549
- else:
550
- hidden_states = self.proj_out(hidden_states)
551
- hidden_states = (
552
- hidden_states.reshape(batch_size, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()
553
- )
554
-
555
- output = hidden_states + residual
556
- return output
557
-
558
- def _get_output_for_vectorized_inputs(self, hidden_states):
559
- hidden_states = self.norm_out(hidden_states)
560
- logits = self.out(hidden_states)
561
- # (batch, self.num_vector_embeds - 1, self.num_latent_pixels)
562
- logits = logits.permute(0, 2, 1)
563
- # log(p(x_0))
564
- output = F.log_softmax(logits.double(), dim=1).float()
565
- return output
566
-
567
- def _get_output_for_patched_inputs(
568
- self, hidden_states, timestep, class_labels, embedded_timestep, height=None, width=None
569
- ):
570
- if self.config.norm_type != "ada_norm_single":
571
- conditioning = self.transformer_blocks[0].norm1.emb(
572
- timestep, class_labels, hidden_dtype=hidden_states.dtype
573
- )
574
- shift, scale = self.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
575
- hidden_states = self.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
576
- hidden_states = self.proj_out_2(hidden_states)
577
- elif self.config.norm_type == "ada_norm_single":
578
- shift, scale = (self.scale_shift_table[None] + embedded_timestep[:, None]).chunk(2, dim=1)
579
- hidden_states = self.norm_out(hidden_states)
580
- # Modulation
581
- hidden_states = hidden_states * (1 + scale) + shift
582
- hidden_states = self.proj_out(hidden_states)
583
- hidden_states = hidden_states.squeeze(1)
584
-
585
- # unpatchify
586
- if self.adaln_single is None:
587
- height = width = int(hidden_states.shape[1] ** 0.5)
588
- hidden_states = hidden_states.reshape(
589
- shape=(-1, height, width, self.patch_size, self.patch_size, self.out_channels)
590
- )
591
- hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
592
- output = hidden_states.reshape(
593
- shape=(-1, self.out_channels, height * self.patch_size, width * self.patch_size)
594
- )
595
- return output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
module/unet/unet_2d_expandKV.py DELETED
@@ -1,164 +0,0 @@
1
- # Copy from diffusers.models.unets.unet_2d_condition.py
2
-
3
- # Copyright 2024 The HuggingFace Team. All rights reserved.
4
- #
5
- # Licensed under the Apache License, Version 2.0 (the "License");
6
- # you may not use this file except in compliance with the License.
7
- # You may obtain a copy of the License at
8
- #
9
- # http://www.apache.org/licenses/LICENSE-2.0
10
- #
11
- # Unless required by applicable law or agreed to in writing, software
12
- # distributed under the License is distributed on an "AS IS" BASIS,
13
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- # See the License for the specific language governing permissions and
15
- # limitations under the License.
16
- from typing import Any, Dict, List, Optional, Tuple, Union
17
-
18
- import torch
19
-
20
- from diffusers.utils import logging
21
- from diffusers.models.unets.unet_2d_condition import UNet2DConditionModel
22
-
23
-
24
- logger = logging.get_logger(__name__) # pylint: disable=invalid-name
25
-
26
-
27
- class ExpandKVUNet2DConditionModel(UNet2DConditionModel):
28
- r"""
29
- A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample
30
- shaped output.
31
-
32
- This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
33
- for all models (such as downloading or saving).
34
-
35
- Parameters:
36
- sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
37
- Height and width of input/output sample.
38
- in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample.
39
- out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.
40
- center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
41
- flip_sin_to_cos (`bool`, *optional*, defaults to `True`):
42
- Whether to flip the sin to cos in the time embedding.
43
- freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
44
- down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
45
- The tuple of downsample blocks to use.
46
- mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
47
- Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or
48
- `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped.
49
- up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`):
50
- The tuple of upsample blocks to use.
51
- only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):
52
- Whether to include self-attention in the basic transformer blocks, see
53
- [`~models.attention.BasicTransformerBlock`].
54
- block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
55
- The tuple of output channels for each block.
56
- layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
57
- downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
58
- mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
59
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
60
- act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
61
- norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
62
- If `None`, normalization and activation layers is skipped in post-processing.
63
- norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
64
- cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):
65
- The dimension of the cross attention features.
66
- transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):
67
- The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
68
- [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
69
- [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
70
- reverse_transformer_layers_per_block : (`Tuple[Tuple]`, *optional*, defaults to None):
71
- The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`], in the upsampling
72
- blocks of the U-Net. Only relevant if `transformer_layers_per_block` is of type `Tuple[Tuple]` and for
73
- [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
74
- [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
75
- encoder_hid_dim (`int`, *optional*, defaults to None):
76
- If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
77
- dimension to `cross_attention_dim`.
78
- encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
79
- If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
80
- embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
81
- attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
82
- num_attention_heads (`int`, *optional*):
83
- The number of attention heads. If not defined, defaults to `attention_head_dim`
84
- resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
85
- for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
86
- class_embed_type (`str`, *optional*, defaults to `None`):
87
- The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
88
- `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
89
- addition_embed_type (`str`, *optional*, defaults to `None`):
90
- Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
91
- "text". "text" will use the `TextTimeEmbedding` layer.
92
- addition_time_embed_dim: (`int`, *optional*, defaults to `None`):
93
- Dimension for the timestep embeddings.
94
- num_class_embeds (`int`, *optional*, defaults to `None`):
95
- Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
96
- class conditioning with `class_embed_type` equal to `None`.
97
- time_embedding_type (`str`, *optional*, defaults to `positional`):
98
- The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.
99
- time_embedding_dim (`int`, *optional*, defaults to `None`):
100
- An optional override for the dimension of the projected time embedding.
101
- time_embedding_act_fn (`str`, *optional*, defaults to `None`):
102
- Optional activation function to use only once on the time embeddings before they are passed to the rest of
103
- the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`.
104
- timestep_post_act (`str`, *optional*, defaults to `None`):
105
- The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.
106
- time_cond_proj_dim (`int`, *optional*, defaults to `None`):
107
- The dimension of `cond_proj` layer in the timestep embedding.
108
- conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer.
109
- conv_out_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_out` layer.
110
- projection_class_embeddings_input_dim (`int`, *optional*): The dimension of the `class_labels` input when
111
- `class_embed_type="projection"`. Required when `class_embed_type="projection"`.
112
- class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time
113
- embeddings with the class embeddings.
114
- mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`):
115
- Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If
116
- `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the
117
- `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False`
118
- otherwise.
119
- """
120
-
121
-
122
- def process_encoder_hidden_states(
123
- self, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
124
- ) -> torch.Tensor:
125
- if self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_proj":
126
- encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states)
127
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_image_proj":
128
- # Kandinsky 2.1 - style
129
- if "image_embeds" not in added_cond_kwargs:
130
- raise ValueError(
131
- 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`"
132
- )
133
-
134
- image_embeds = added_cond_kwargs.get("image_embeds")
135
- encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states, image_embeds)
136
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "image_proj":
137
- # Kandinsky 2.2 - style
138
- if "image_embeds" not in added_cond_kwargs:
139
- raise ValueError(
140
- 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`"
141
- )
142
- image_embeds = added_cond_kwargs.get("image_embeds")
143
- encoder_hidden_states = self.encoder_hid_proj(image_embeds)
144
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "ip_image_proj":
145
- if "image_embeds" not in added_cond_kwargs:
146
- raise ValueError(
147
- 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`"
148
- )
149
- image_embeds = added_cond_kwargs.get("image_embeds")
150
- image_embeds = self.encoder_hid_proj(image_embeds)
151
- encoder_hidden_states = (encoder_hidden_states, image_embeds)
152
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "instantir":
153
- if "image_embeds" not in added_cond_kwargs:
154
- raise ValueError(
155
- 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`"
156
- )
157
- if "extract_kvs" not in added_cond_kwargs:
158
- raise ValueError(
159
- 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`"
160
- )
161
- image_embeds = added_cond_kwargs.get("image_embeds")
162
- image_embeds = self.encoder_hid_proj(image_embeds)
163
- encoder_hidden_states = (encoder_hidden_states, image_embeds)
164
- return encoder_hidden_states
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
module/unet/unet_2d_extractKV.py DELETED
@@ -1,1347 +0,0 @@
1
- # Copy from diffusers.models.unets.unet_2d_condition.py
2
-
3
- # Copyright 2024 The HuggingFace Team. All rights reserved.
4
- #
5
- # Licensed under the Apache License, Version 2.0 (the "License");
6
- # you may not use this file except in compliance with the License.
7
- # You may obtain a copy of the License at
8
- #
9
- # http://www.apache.org/licenses/LICENSE-2.0
10
- #
11
- # Unless required by applicable law or agreed to in writing, software
12
- # distributed under the License is distributed on an "AS IS" BASIS,
13
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- # See the License for the specific language governing permissions and
15
- # limitations under the License.
16
- from dataclasses import dataclass
17
- from typing import Any, Dict, List, Optional, Tuple, Union
18
-
19
- import torch
20
- import torch.nn as nn
21
- import torch.utils.checkpoint
22
-
23
- from diffusers.configuration_utils import ConfigMixin, register_to_config
24
- from diffusers.loaders import PeftAdapterMixin, UNet2DConditionLoadersMixin
25
- from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, logging, scale_lora_layers, unscale_lora_layers
26
- from diffusers.models.activations import get_activation
27
- from diffusers.models.attention_processor import (
28
- ADDED_KV_ATTENTION_PROCESSORS,
29
- CROSS_ATTENTION_PROCESSORS,
30
- Attention,
31
- AttentionProcessor,
32
- AttnAddedKVProcessor,
33
- AttnProcessor,
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 .unet_2d_extractKV_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 ExtractKVUNet2DConditionOutput(BaseOutput):
60
- """
61
- The output of [`UNet2DConditionModel`].
62
-
63
- Args:
64
- sample (`torch.FloatTensor` 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.FloatTensor = None
69
- cached_kvs: Dict[str, Any] = None
70
-
71
-
72
- class ExtractKVUNet2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin, PeftAdapterMixin):
73
- r"""
74
- A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample
75
- shaped output.
76
-
77
- This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
78
- for all models (such as downloading or saving).
79
-
80
- Parameters:
81
- sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
82
- Height and width of input/output sample.
83
- in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample.
84
- out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.
85
- center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
86
- flip_sin_to_cos (`bool`, *optional*, defaults to `True`):
87
- Whether to flip the sin to cos in the time embedding.
88
- freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
89
- down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
90
- The tuple of downsample blocks to use.
91
- mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
92
- Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or
93
- `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped.
94
- up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`):
95
- The tuple of upsample blocks to use.
96
- only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):
97
- Whether to include self-attention in the basic transformer blocks, see
98
- [`~models.attention.BasicTransformerBlock`].
99
- block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
100
- The tuple of output channels for each block.
101
- layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
102
- downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
103
- mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
104
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
105
- act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
106
- norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
107
- If `None`, normalization and activation layers is skipped in post-processing.
108
- norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
109
- cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):
110
- The dimension of the cross attention features.
111
- transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):
112
- The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
113
- [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
114
- [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
115
- reverse_transformer_layers_per_block : (`Tuple[Tuple]`, *optional*, defaults to None):
116
- The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`], in the upsampling
117
- blocks of the U-Net. Only relevant if `transformer_layers_per_block` is of type `Tuple[Tuple]` and for
118
- [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
119
- [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
120
- encoder_hid_dim (`int`, *optional*, defaults to None):
121
- If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
122
- dimension to `cross_attention_dim`.
123
- encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
124
- If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
125
- embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
126
- attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
127
- num_attention_heads (`int`, *optional*):
128
- The number of attention heads. If not defined, defaults to `attention_head_dim`
129
- resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
130
- for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
131
- class_embed_type (`str`, *optional*, defaults to `None`):
132
- The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
133
- `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
134
- addition_embed_type (`str`, *optional*, defaults to `None`):
135
- Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
136
- "text". "text" will use the `TextTimeEmbedding` layer.
137
- addition_time_embed_dim: (`int`, *optional*, defaults to `None`):
138
- Dimension for the timestep embeddings.
139
- num_class_embeds (`int`, *optional*, defaults to `None`):
140
- Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
141
- class conditioning with `class_embed_type` equal to `None`.
142
- time_embedding_type (`str`, *optional*, defaults to `positional`):
143
- The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.
144
- time_embedding_dim (`int`, *optional*, defaults to `None`):
145
- An optional override for the dimension of the projected time embedding.
146
- time_embedding_act_fn (`str`, *optional*, defaults to `None`):
147
- Optional activation function to use only once on the time embeddings before they are passed to the rest of
148
- the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`.
149
- timestep_post_act (`str`, *optional*, defaults to `None`):
150
- The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.
151
- time_cond_proj_dim (`int`, *optional*, defaults to `None`):
152
- The dimension of `cond_proj` layer in the timestep embedding.
153
- conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer.
154
- conv_out_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_out` layer.
155
- projection_class_embeddings_input_dim (`int`, *optional*): The dimension of the `class_labels` input when
156
- `class_embed_type="projection"`. Required when `class_embed_type="projection"`.
157
- class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time
158
- embeddings with the class embeddings.
159
- mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`):
160
- Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If
161
- `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the
162
- `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False`
163
- otherwise.
164
- """
165
-
166
- _supports_gradient_checkpointing = True
167
- _no_split_modules = ["BasicTransformerBlock", "ResnetBlock2D", "CrossAttnUpBlock2D"]
168
-
169
- @register_to_config
170
- def __init__(
171
- self,
172
- sample_size: Optional[int] = None,
173
- in_channels: int = 4,
174
- out_channels: int = 4,
175
- center_input_sample: bool = False,
176
- flip_sin_to_cos: bool = True,
177
- freq_shift: int = 0,
178
- down_block_types: Tuple[str] = (
179
- "CrossAttnDownBlock2D",
180
- "CrossAttnDownBlock2D",
181
- "CrossAttnDownBlock2D",
182
- "DownBlock2D",
183
- ),
184
- mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
185
- up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
186
- only_cross_attention: Union[bool, Tuple[bool]] = False,
187
- block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
188
- layers_per_block: Union[int, Tuple[int]] = 2,
189
- downsample_padding: int = 1,
190
- mid_block_scale_factor: float = 1,
191
- dropout: float = 0.0,
192
- act_fn: str = "silu",
193
- norm_num_groups: Optional[int] = 32,
194
- norm_eps: float = 1e-5,
195
- cross_attention_dim: Union[int, Tuple[int]] = 1280,
196
- transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
197
- reverse_transformer_layers_per_block: Optional[Tuple[Tuple[int]]] = None,
198
- encoder_hid_dim: Optional[int] = None,
199
- encoder_hid_dim_type: Optional[str] = None,
200
- attention_head_dim: Union[int, Tuple[int]] = 8,
201
- num_attention_heads: Optional[Union[int, Tuple[int]]] = None,
202
- dual_cross_attention: bool = False,
203
- use_linear_projection: bool = False,
204
- class_embed_type: Optional[str] = None,
205
- addition_embed_type: Optional[str] = None,
206
- addition_time_embed_dim: Optional[int] = None,
207
- num_class_embeds: Optional[int] = None,
208
- upcast_attention: bool = False,
209
- resnet_time_scale_shift: str = "default",
210
- resnet_skip_time_act: bool = False,
211
- resnet_out_scale_factor: float = 1.0,
212
- time_embedding_type: str = "positional",
213
- time_embedding_dim: Optional[int] = None,
214
- time_embedding_act_fn: Optional[str] = None,
215
- timestep_post_act: Optional[str] = None,
216
- time_cond_proj_dim: Optional[int] = None,
217
- conv_in_kernel: int = 3,
218
- conv_out_kernel: int = 3,
219
- projection_class_embeddings_input_dim: Optional[int] = None,
220
- attention_type: str = "default",
221
- class_embeddings_concat: bool = False,
222
- mid_block_only_cross_attention: Optional[bool] = None,
223
- cross_attention_norm: Optional[str] = None,
224
- addition_embed_type_num_heads: int = 64,
225
- extract_self_attention_kv: bool = False,
226
- extract_cross_attention_kv: bool = False,
227
- ):
228
- super().__init__()
229
-
230
- self.sample_size = sample_size
231
-
232
- if num_attention_heads is not None:
233
- raise ValueError(
234
- "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."
235
- )
236
-
237
- # If `num_attention_heads` is not defined (which is the case for most models)
238
- # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
239
- # The reason for this behavior is to correct for incorrectly named variables that were introduced
240
- # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
241
- # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
242
- # which is why we correct for the naming here.
243
- num_attention_heads = num_attention_heads or attention_head_dim
244
-
245
- # Check inputs
246
- self._check_config(
247
- down_block_types=down_block_types,
248
- up_block_types=up_block_types,
249
- only_cross_attention=only_cross_attention,
250
- block_out_channels=block_out_channels,
251
- layers_per_block=layers_per_block,
252
- cross_attention_dim=cross_attention_dim,
253
- transformer_layers_per_block=transformer_layers_per_block,
254
- reverse_transformer_layers_per_block=reverse_transformer_layers_per_block,
255
- attention_head_dim=attention_head_dim,
256
- num_attention_heads=num_attention_heads,
257
- )
258
-
259
- # input
260
- conv_in_padding = (conv_in_kernel - 1) // 2
261
- self.conv_in = nn.Conv2d(
262
- in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
263
- )
264
-
265
- # time
266
- time_embed_dim, timestep_input_dim = self._set_time_proj(
267
- time_embedding_type,
268
- block_out_channels=block_out_channels,
269
- flip_sin_to_cos=flip_sin_to_cos,
270
- freq_shift=freq_shift,
271
- time_embedding_dim=time_embedding_dim,
272
- )
273
-
274
- self.time_embedding = TimestepEmbedding(
275
- timestep_input_dim,
276
- time_embed_dim,
277
- act_fn=act_fn,
278
- post_act_fn=timestep_post_act,
279
- cond_proj_dim=time_cond_proj_dim,
280
- )
281
-
282
- self._set_encoder_hid_proj(
283
- encoder_hid_dim_type,
284
- cross_attention_dim=cross_attention_dim,
285
- encoder_hid_dim=encoder_hid_dim,
286
- )
287
-
288
- # class embedding
289
- self._set_class_embedding(
290
- class_embed_type,
291
- act_fn=act_fn,
292
- num_class_embeds=num_class_embeds,
293
- projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,
294
- time_embed_dim=time_embed_dim,
295
- timestep_input_dim=timestep_input_dim,
296
- )
297
-
298
- self._set_add_embedding(
299
- addition_embed_type,
300
- addition_embed_type_num_heads=addition_embed_type_num_heads,
301
- addition_time_embed_dim=addition_time_embed_dim,
302
- cross_attention_dim=cross_attention_dim,
303
- encoder_hid_dim=encoder_hid_dim,
304
- flip_sin_to_cos=flip_sin_to_cos,
305
- freq_shift=freq_shift,
306
- projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,
307
- time_embed_dim=time_embed_dim,
308
- )
309
-
310
- if time_embedding_act_fn is None:
311
- self.time_embed_act = None
312
- else:
313
- self.time_embed_act = get_activation(time_embedding_act_fn)
314
-
315
- self.down_blocks = nn.ModuleList([])
316
- self.up_blocks = nn.ModuleList([])
317
-
318
- if isinstance(only_cross_attention, bool):
319
- if mid_block_only_cross_attention is None:
320
- mid_block_only_cross_attention = only_cross_attention
321
-
322
- only_cross_attention = [only_cross_attention] * len(down_block_types)
323
-
324
- if mid_block_only_cross_attention is None:
325
- mid_block_only_cross_attention = False
326
-
327
- if isinstance(num_attention_heads, int):
328
- num_attention_heads = (num_attention_heads,) * len(down_block_types)
329
-
330
- if isinstance(attention_head_dim, int):
331
- attention_head_dim = (attention_head_dim,) * len(down_block_types)
332
-
333
- if isinstance(cross_attention_dim, int):
334
- cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
335
-
336
- if isinstance(layers_per_block, int):
337
- layers_per_block = [layers_per_block] * len(down_block_types)
338
-
339
- if isinstance(transformer_layers_per_block, int):
340
- transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
341
-
342
- if class_embeddings_concat:
343
- # The time embeddings are concatenated with the class embeddings. The dimension of the
344
- # time embeddings passed to the down, middle, and up blocks is twice the dimension of the
345
- # regular time embeddings
346
- blocks_time_embed_dim = time_embed_dim * 2
347
- else:
348
- blocks_time_embed_dim = time_embed_dim
349
-
350
- # down
351
- output_channel = block_out_channels[0]
352
- for i, down_block_type in enumerate(down_block_types):
353
- input_channel = output_channel
354
- output_channel = block_out_channels[i]
355
- is_final_block = i == len(block_out_channels) - 1
356
-
357
- down_block = get_down_block(
358
- down_block_type,
359
- num_layers=layers_per_block[i],
360
- transformer_layers_per_block=transformer_layers_per_block[i],
361
- in_channels=input_channel,
362
- out_channels=output_channel,
363
- temb_channels=blocks_time_embed_dim,
364
- add_downsample=not is_final_block,
365
- resnet_eps=norm_eps,
366
- resnet_act_fn=act_fn,
367
- resnet_groups=norm_num_groups,
368
- cross_attention_dim=cross_attention_dim[i],
369
- num_attention_heads=num_attention_heads[i],
370
- downsample_padding=downsample_padding,
371
- dual_cross_attention=dual_cross_attention,
372
- use_linear_projection=use_linear_projection,
373
- only_cross_attention=only_cross_attention[i],
374
- upcast_attention=upcast_attention,
375
- resnet_time_scale_shift=resnet_time_scale_shift,
376
- attention_type=attention_type,
377
- resnet_skip_time_act=resnet_skip_time_act,
378
- resnet_out_scale_factor=resnet_out_scale_factor,
379
- cross_attention_norm=cross_attention_norm,
380
- attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
381
- dropout=dropout,
382
- extract_self_attention_kv=extract_self_attention_kv,
383
- extract_cross_attention_kv=extract_cross_attention_kv,
384
- )
385
- self.down_blocks.append(down_block)
386
-
387
- # mid
388
- self.mid_block = get_mid_block(
389
- mid_block_type,
390
- temb_channels=blocks_time_embed_dim,
391
- in_channels=block_out_channels[-1],
392
- resnet_eps=norm_eps,
393
- resnet_act_fn=act_fn,
394
- resnet_groups=norm_num_groups,
395
- output_scale_factor=mid_block_scale_factor,
396
- transformer_layers_per_block=transformer_layers_per_block[-1],
397
- num_attention_heads=num_attention_heads[-1],
398
- cross_attention_dim=cross_attention_dim[-1],
399
- dual_cross_attention=dual_cross_attention,
400
- use_linear_projection=use_linear_projection,
401
- mid_block_only_cross_attention=mid_block_only_cross_attention,
402
- upcast_attention=upcast_attention,
403
- resnet_time_scale_shift=resnet_time_scale_shift,
404
- attention_type=attention_type,
405
- resnet_skip_time_act=resnet_skip_time_act,
406
- cross_attention_norm=cross_attention_norm,
407
- attention_head_dim=attention_head_dim[-1],
408
- dropout=dropout,
409
- extract_self_attention_kv=extract_self_attention_kv,
410
- extract_cross_attention_kv=extract_cross_attention_kv,
411
- )
412
-
413
- # count how many layers upsample the images
414
- self.num_upsamplers = 0
415
-
416
- # up
417
- reversed_block_out_channels = list(reversed(block_out_channels))
418
- reversed_num_attention_heads = list(reversed(num_attention_heads))
419
- reversed_layers_per_block = list(reversed(layers_per_block))
420
- reversed_cross_attention_dim = list(reversed(cross_attention_dim))
421
- reversed_transformer_layers_per_block = (
422
- list(reversed(transformer_layers_per_block))
423
- if reverse_transformer_layers_per_block is None
424
- else reverse_transformer_layers_per_block
425
- )
426
- only_cross_attention = list(reversed(only_cross_attention))
427
-
428
- output_channel = reversed_block_out_channels[0]
429
- for i, up_block_type in enumerate(up_block_types):
430
- is_final_block = i == len(block_out_channels) - 1
431
-
432
- prev_output_channel = output_channel
433
- output_channel = reversed_block_out_channels[i]
434
- input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
435
-
436
- # add upsample block for all BUT final layer
437
- if not is_final_block:
438
- add_upsample = True
439
- self.num_upsamplers += 1
440
- else:
441
- add_upsample = False
442
-
443
- up_block = get_up_block(
444
- up_block_type,
445
- num_layers=reversed_layers_per_block[i] + 1,
446
- transformer_layers_per_block=reversed_transformer_layers_per_block[i],
447
- in_channels=input_channel,
448
- out_channels=output_channel,
449
- prev_output_channel=prev_output_channel,
450
- temb_channels=blocks_time_embed_dim,
451
- add_upsample=add_upsample,
452
- resnet_eps=norm_eps,
453
- resnet_act_fn=act_fn,
454
- resolution_idx=i,
455
- resnet_groups=norm_num_groups,
456
- cross_attention_dim=reversed_cross_attention_dim[i],
457
- num_attention_heads=reversed_num_attention_heads[i],
458
- dual_cross_attention=dual_cross_attention,
459
- use_linear_projection=use_linear_projection,
460
- only_cross_attention=only_cross_attention[i],
461
- upcast_attention=upcast_attention,
462
- resnet_time_scale_shift=resnet_time_scale_shift,
463
- attention_type=attention_type,
464
- resnet_skip_time_act=resnet_skip_time_act,
465
- resnet_out_scale_factor=resnet_out_scale_factor,
466
- cross_attention_norm=cross_attention_norm,
467
- attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
468
- dropout=dropout,
469
- extract_self_attention_kv=extract_self_attention_kv,
470
- extract_cross_attention_kv=extract_cross_attention_kv,
471
- )
472
- self.up_blocks.append(up_block)
473
- prev_output_channel = output_channel
474
-
475
- # out
476
- if norm_num_groups is not None:
477
- self.conv_norm_out = nn.GroupNorm(
478
- num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
479
- )
480
-
481
- self.conv_act = get_activation(act_fn)
482
-
483
- else:
484
- self.conv_norm_out = None
485
- self.conv_act = None
486
-
487
- conv_out_padding = (conv_out_kernel - 1) // 2
488
- self.conv_out = nn.Conv2d(
489
- block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding
490
- )
491
-
492
- self._set_pos_net_if_use_gligen(attention_type=attention_type, cross_attention_dim=cross_attention_dim)
493
-
494
- def _check_config(
495
- self,
496
- down_block_types: Tuple[str],
497
- up_block_types: Tuple[str],
498
- only_cross_attention: Union[bool, Tuple[bool]],
499
- block_out_channels: Tuple[int],
500
- layers_per_block: Union[int, Tuple[int]],
501
- cross_attention_dim: Union[int, Tuple[int]],
502
- transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple[int]]],
503
- reverse_transformer_layers_per_block: bool,
504
- attention_head_dim: int,
505
- num_attention_heads: Optional[Union[int, Tuple[int]]],
506
- ):
507
- assert "ExtractKVCrossAttnDownBlock2D" in down_block_types, "ExtractKVUNet must have ExtractKVCrossAttnDownBlock2D."
508
- assert "ExtractKVCrossAttnUpBlock2D" in up_block_types, "ExtractKVUNet must have ExtractKVCrossAttnUpBlock2D."
509
-
510
- if len(down_block_types) != len(up_block_types):
511
- raise ValueError(
512
- 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}."
513
- )
514
-
515
- if len(block_out_channels) != len(down_block_types):
516
- raise ValueError(
517
- 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}."
518
- )
519
-
520
- if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
521
- raise ValueError(
522
- 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}."
523
- )
524
-
525
- if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
526
- raise ValueError(
527
- 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}."
528
- )
529
-
530
- if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
531
- raise ValueError(
532
- 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}."
533
- )
534
-
535
- if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types):
536
- raise ValueError(
537
- 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}."
538
- )
539
-
540
- if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types):
541
- raise ValueError(
542
- 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}."
543
- )
544
- if isinstance(transformer_layers_per_block, list) and reverse_transformer_layers_per_block is None:
545
- for layer_number_per_block in transformer_layers_per_block:
546
- if isinstance(layer_number_per_block, list):
547
- raise ValueError("Must provide 'reverse_transformer_layers_per_block` if using asymmetrical UNet.")
548
-
549
- def _set_time_proj(
550
- self,
551
- time_embedding_type: str,
552
- block_out_channels: int,
553
- flip_sin_to_cos: bool,
554
- freq_shift: float,
555
- time_embedding_dim: int,
556
- ) -> Tuple[int, int]:
557
- if time_embedding_type == "fourier":
558
- time_embed_dim = time_embedding_dim or block_out_channels[0] * 2
559
- if time_embed_dim % 2 != 0:
560
- raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.")
561
- self.time_proj = GaussianFourierProjection(
562
- time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos
563
- )
564
- timestep_input_dim = time_embed_dim
565
- elif time_embedding_type == "positional":
566
- time_embed_dim = time_embedding_dim or block_out_channels[0] * 4
567
-
568
- self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
569
- timestep_input_dim = block_out_channels[0]
570
- else:
571
- raise ValueError(
572
- f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`."
573
- )
574
-
575
- return time_embed_dim, timestep_input_dim
576
-
577
- def _set_encoder_hid_proj(
578
- self,
579
- encoder_hid_dim_type: Optional[str],
580
- cross_attention_dim: Union[int, Tuple[int]],
581
- encoder_hid_dim: Optional[int],
582
- ):
583
- if encoder_hid_dim_type is None and encoder_hid_dim is not None:
584
- encoder_hid_dim_type = "text_proj"
585
- self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
586
- logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.")
587
-
588
- if encoder_hid_dim is None and encoder_hid_dim_type is not None:
589
- raise ValueError(
590
- f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
591
- )
592
-
593
- if encoder_hid_dim_type == "text_proj":
594
- self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
595
- elif encoder_hid_dim_type == "text_image_proj":
596
- # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
597
- # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
598
- # case when `addition_embed_type == "text_image_proj"` (Kandinsky 2.1)`
599
- self.encoder_hid_proj = TextImageProjection(
600
- text_embed_dim=encoder_hid_dim,
601
- image_embed_dim=cross_attention_dim,
602
- cross_attention_dim=cross_attention_dim,
603
- )
604
- elif encoder_hid_dim_type == "image_proj":
605
- # Kandinsky 2.2
606
- self.encoder_hid_proj = ImageProjection(
607
- image_embed_dim=encoder_hid_dim,
608
- cross_attention_dim=cross_attention_dim,
609
- )
610
- elif encoder_hid_dim_type is not None:
611
- raise ValueError(
612
- f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'."
613
- )
614
- else:
615
- self.encoder_hid_proj = None
616
-
617
- def _set_class_embedding(
618
- self,
619
- class_embed_type: Optional[str],
620
- act_fn: str,
621
- num_class_embeds: Optional[int],
622
- projection_class_embeddings_input_dim: Optional[int],
623
- time_embed_dim: int,
624
- timestep_input_dim: int,
625
- ):
626
- if class_embed_type is None and num_class_embeds is not None:
627
- self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
628
- elif class_embed_type == "timestep":
629
- self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn)
630
- elif class_embed_type == "identity":
631
- self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
632
- elif class_embed_type == "projection":
633
- if projection_class_embeddings_input_dim is None:
634
- raise ValueError(
635
- "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
636
- )
637
- # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
638
- # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
639
- # 2. it projects from an arbitrary input dimension.
640
- #
641
- # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
642
- # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
643
- # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
644
- self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
645
- elif class_embed_type == "simple_projection":
646
- if projection_class_embeddings_input_dim is None:
647
- raise ValueError(
648
- "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set"
649
- )
650
- self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim)
651
- else:
652
- self.class_embedding = None
653
-
654
- def _set_add_embedding(
655
- self,
656
- addition_embed_type: str,
657
- addition_embed_type_num_heads: int,
658
- addition_time_embed_dim: Optional[int],
659
- flip_sin_to_cos: bool,
660
- freq_shift: float,
661
- cross_attention_dim: Optional[int],
662
- encoder_hid_dim: Optional[int],
663
- projection_class_embeddings_input_dim: Optional[int],
664
- time_embed_dim: int,
665
- ):
666
- if addition_embed_type == "text":
667
- if encoder_hid_dim is not None:
668
- text_time_embedding_from_dim = encoder_hid_dim
669
- else:
670
- text_time_embedding_from_dim = cross_attention_dim
671
-
672
- self.add_embedding = TextTimeEmbedding(
673
- text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads
674
- )
675
- elif addition_embed_type == "text_image":
676
- # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
677
- # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
678
- # case when `addition_embed_type == "text_image"` (Kandinsky 2.1)`
679
- self.add_embedding = TextImageTimeEmbedding(
680
- text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim
681
- )
682
- elif addition_embed_type == "text_time":
683
- self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)
684
- self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
685
- elif addition_embed_type == "image":
686
- # Kandinsky 2.2
687
- self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
688
- elif addition_embed_type == "image_hint":
689
- # Kandinsky 2.2 ControlNet
690
- self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
691
- elif addition_embed_type is not None:
692
- raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.")
693
-
694
- def _set_pos_net_if_use_gligen(self, attention_type: str, cross_attention_dim: int):
695
- if attention_type in ["gated", "gated-text-image"]:
696
- positive_len = 768
697
- if isinstance(cross_attention_dim, int):
698
- positive_len = cross_attention_dim
699
- elif isinstance(cross_attention_dim, tuple) or isinstance(cross_attention_dim, list):
700
- positive_len = cross_attention_dim[0]
701
-
702
- feature_type = "text-only" if attention_type == "gated" else "text-image"
703
- self.position_net = GLIGENTextBoundingboxProjection(
704
- positive_len=positive_len, out_dim=cross_attention_dim, feature_type=feature_type
705
- )
706
-
707
- @property
708
- def attn_processors(self) -> Dict[str, AttentionProcessor]:
709
- r"""
710
- Returns:
711
- `dict` of attention processors: A dictionary containing all attention processors used in the model with
712
- indexed by its weight name.
713
- """
714
- # set recursively
715
- processors = {}
716
-
717
- def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
718
- if hasattr(module, "get_processor"):
719
- processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
720
-
721
- for sub_name, child in module.named_children():
722
- fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
723
-
724
- return processors
725
-
726
- for name, module in self.named_children():
727
- fn_recursive_add_processors(name, module, processors)
728
-
729
- return processors
730
-
731
- def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
732
- r"""
733
- Sets the attention processor to use to compute attention.
734
-
735
- Parameters:
736
- processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
737
- The instantiated processor class or a dictionary of processor classes that will be set as the processor
738
- for **all** `Attention` layers.
739
-
740
- If `processor` is a dict, the key needs to define the path to the corresponding cross attention
741
- processor. This is strongly recommended when setting trainable attention processors.
742
-
743
- """
744
- count = len(self.attn_processors.keys())
745
-
746
- if isinstance(processor, dict) and len(processor) != count:
747
- raise ValueError(
748
- f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
749
- f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
750
- )
751
-
752
- def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
753
- if hasattr(module, "set_processor"):
754
- if not isinstance(processor, dict):
755
- module.set_processor(processor)
756
- else:
757
- module.set_processor(processor.pop(f"{name}.processor"))
758
-
759
- for sub_name, child in module.named_children():
760
- fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
761
-
762
- for name, module in self.named_children():
763
- fn_recursive_attn_processor(name, module, processor)
764
-
765
- def set_default_attn_processor(self):
766
- """
767
- Disables custom attention processors and sets the default attention implementation.
768
- """
769
- if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
770
- processor = AttnAddedKVProcessor()
771
- elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
772
- processor = AttnProcessor()
773
- else:
774
- raise ValueError(
775
- f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
776
- )
777
-
778
- self.set_attn_processor(processor)
779
-
780
- def set_attention_slice(self, slice_size: Union[str, int, List[int]] = "auto"):
781
- r"""
782
- Enable sliced attention computation.
783
-
784
- When this option is enabled, the attention module splits the input tensor in slices to compute attention in
785
- several steps. This is useful for saving some memory in exchange for a small decrease in speed.
786
-
787
- Args:
788
- slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
789
- When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
790
- `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
791
- provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
792
- must be a multiple of `slice_size`.
793
- """
794
- sliceable_head_dims = []
795
-
796
- def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
797
- if hasattr(module, "set_attention_slice"):
798
- sliceable_head_dims.append(module.sliceable_head_dim)
799
-
800
- for child in module.children():
801
- fn_recursive_retrieve_sliceable_dims(child)
802
-
803
- # retrieve number of attention layers
804
- for module in self.children():
805
- fn_recursive_retrieve_sliceable_dims(module)
806
-
807
- num_sliceable_layers = len(sliceable_head_dims)
808
-
809
- if slice_size == "auto":
810
- # half the attention head size is usually a good trade-off between
811
- # speed and memory
812
- slice_size = [dim // 2 for dim in sliceable_head_dims]
813
- elif slice_size == "max":
814
- # make smallest slice possible
815
- slice_size = num_sliceable_layers * [1]
816
-
817
- slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
818
-
819
- if len(slice_size) != len(sliceable_head_dims):
820
- raise ValueError(
821
- f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
822
- f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
823
- )
824
-
825
- for i in range(len(slice_size)):
826
- size = slice_size[i]
827
- dim = sliceable_head_dims[i]
828
- if size is not None and size > dim:
829
- raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
830
-
831
- # Recursively walk through all the children.
832
- # Any children which exposes the set_attention_slice method
833
- # gets the message
834
- def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
835
- if hasattr(module, "set_attention_slice"):
836
- module.set_attention_slice(slice_size.pop())
837
-
838
- for child in module.children():
839
- fn_recursive_set_attention_slice(child, slice_size)
840
-
841
- reversed_slice_size = list(reversed(slice_size))
842
- for module in self.children():
843
- fn_recursive_set_attention_slice(module, reversed_slice_size)
844
-
845
- def _set_gradient_checkpointing(self, module, value=False):
846
- if hasattr(module, "gradient_checkpointing"):
847
- module.gradient_checkpointing = value
848
-
849
- def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
850
- r"""Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497.
851
-
852
- The suffixes after the scaling factors represent the stage blocks where they are being applied.
853
-
854
- Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that
855
- are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
856
-
857
- Args:
858
- s1 (`float`):
859
- Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
860
- mitigate the "oversmoothing effect" in the enhanced denoising process.
861
- s2 (`float`):
862
- Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
863
- mitigate the "oversmoothing effect" in the enhanced denoising process.
864
- b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
865
- b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
866
- """
867
- for i, upsample_block in enumerate(self.up_blocks):
868
- setattr(upsample_block, "s1", s1)
869
- setattr(upsample_block, "s2", s2)
870
- setattr(upsample_block, "b1", b1)
871
- setattr(upsample_block, "b2", b2)
872
-
873
- def disable_freeu(self):
874
- """Disables the FreeU mechanism."""
875
- freeu_keys = {"s1", "s2", "b1", "b2"}
876
- for i, upsample_block in enumerate(self.up_blocks):
877
- for k in freeu_keys:
878
- if hasattr(upsample_block, k) or getattr(upsample_block, k, None) is not None:
879
- setattr(upsample_block, k, None)
880
-
881
- def fuse_qkv_projections(self):
882
- """
883
- Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
884
- are fused. For cross-attention modules, key and value projection matrices are fused.
885
-
886
- <Tip warning={true}>
887
-
888
- This API is 🧪 experimental.
889
-
890
- </Tip>
891
- """
892
- self.original_attn_processors = None
893
-
894
- for _, attn_processor in self.attn_processors.items():
895
- if "Added" in str(attn_processor.__class__.__name__):
896
- raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
897
-
898
- self.original_attn_processors = self.attn_processors
899
-
900
- for module in self.modules():
901
- if isinstance(module, Attention):
902
- module.fuse_projections(fuse=True)
903
-
904
- def unfuse_qkv_projections(self):
905
- """Disables the fused QKV projection if enabled.
906
-
907
- <Tip warning={true}>
908
-
909
- This API is 🧪 experimental.
910
-
911
- </Tip>
912
-
913
- """
914
- if self.original_attn_processors is not None:
915
- self.set_attn_processor(self.original_attn_processors)
916
-
917
- def unload_lora(self):
918
- """Unloads LoRA weights."""
919
- deprecate(
920
- "unload_lora",
921
- "0.28.0",
922
- "Calling `unload_lora()` is deprecated and will be removed in a future version. Please install `peft` and then call `disable_adapters().",
923
- )
924
- for module in self.modules():
925
- if hasattr(module, "set_lora_layer"):
926
- module.set_lora_layer(None)
927
-
928
- def get_time_embed(
929
- self, sample: torch.Tensor, timestep: Union[torch.Tensor, float, int]
930
- ) -> Optional[torch.Tensor]:
931
- timesteps = timestep
932
- if not torch.is_tensor(timesteps):
933
- # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
934
- # This would be a good case for the `match` statement (Python 3.10+)
935
- is_mps = sample.device.type == "mps"
936
- if isinstance(timestep, float):
937
- dtype = torch.float32 if is_mps else torch.float64
938
- else:
939
- dtype = torch.int32 if is_mps else torch.int64
940
- timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
941
- elif len(timesteps.shape) == 0:
942
- timesteps = timesteps[None].to(sample.device)
943
-
944
- # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
945
- timesteps = timesteps.expand(sample.shape[0])
946
-
947
- t_emb = self.time_proj(timesteps)
948
- # `Timesteps` does not contain any weights and will always return f32 tensors
949
- # but time_embedding might actually be running in fp16. so we need to cast here.
950
- # there might be better ways to encapsulate this.
951
- t_emb = t_emb.to(dtype=sample.dtype)
952
- return t_emb
953
-
954
- def get_class_embed(self, sample: torch.Tensor, class_labels: Optional[torch.Tensor]) -> Optional[torch.Tensor]:
955
- class_emb = None
956
- if self.class_embedding is not None:
957
- if class_labels is None:
958
- raise ValueError("class_labels should be provided when num_class_embeds > 0")
959
-
960
- if self.config.class_embed_type == "timestep":
961
- class_labels = self.time_proj(class_labels)
962
-
963
- # `Timesteps` does not contain any weights and will always return f32 tensors
964
- # there might be better ways to encapsulate this.
965
- class_labels = class_labels.to(dtype=sample.dtype)
966
-
967
- class_emb = self.class_embedding(class_labels).to(dtype=sample.dtype)
968
- return class_emb
969
-
970
- def get_aug_embed(
971
- self, emb: torch.Tensor, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
972
- ) -> Optional[torch.Tensor]:
973
- aug_emb = None
974
- if self.config.addition_embed_type == "text":
975
- aug_emb = self.add_embedding(encoder_hidden_states)
976
- elif self.config.addition_embed_type == "text_image":
977
- # Kandinsky 2.1 - style
978
- if "image_embeds" not in added_cond_kwargs:
979
- raise ValueError(
980
- 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`"
981
- )
982
-
983
- image_embs = added_cond_kwargs.get("image_embeds")
984
- text_embs = added_cond_kwargs.get("text_embeds", encoder_hidden_states)
985
- aug_emb = self.add_embedding(text_embs, image_embs)
986
- elif self.config.addition_embed_type == "text_time":
987
- # SDXL - style
988
- if "text_embeds" not in added_cond_kwargs:
989
- raise ValueError(
990
- 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`"
991
- )
992
- text_embeds = added_cond_kwargs.get("text_embeds")
993
- if "time_ids" not in added_cond_kwargs:
994
- raise ValueError(
995
- 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`"
996
- )
997
- time_ids = added_cond_kwargs.get("time_ids")
998
- time_embeds = self.add_time_proj(time_ids.flatten())
999
- time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
1000
- add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
1001
- add_embeds = add_embeds.to(emb.dtype)
1002
- aug_emb = self.add_embedding(add_embeds)
1003
- elif self.config.addition_embed_type == "image":
1004
- # Kandinsky 2.2 - style
1005
- if "image_embeds" not in added_cond_kwargs:
1006
- raise ValueError(
1007
- 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`"
1008
- )
1009
- image_embs = added_cond_kwargs.get("image_embeds")
1010
- aug_emb = self.add_embedding(image_embs)
1011
- elif self.config.addition_embed_type == "image_hint":
1012
- # Kandinsky 2.2 - style
1013
- if "image_embeds" not in added_cond_kwargs or "hint" not in added_cond_kwargs:
1014
- raise ValueError(
1015
- 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`"
1016
- )
1017
- image_embs = added_cond_kwargs.get("image_embeds")
1018
- hint = added_cond_kwargs.get("hint")
1019
- aug_emb = self.add_embedding(image_embs, hint)
1020
- return aug_emb
1021
-
1022
- def process_encoder_hidden_states(
1023
- self, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
1024
- ) -> torch.Tensor:
1025
- if self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_proj":
1026
- encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states)
1027
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_image_proj":
1028
- # Kandinsky 2.1 - style
1029
- if "image_embeds" not in added_cond_kwargs:
1030
- raise ValueError(
1031
- 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`"
1032
- )
1033
-
1034
- image_embeds = added_cond_kwargs.get("image_embeds")
1035
- encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states, image_embeds)
1036
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "image_proj":
1037
- # Kandinsky 2.2 - style
1038
- if "image_embeds" not in added_cond_kwargs:
1039
- raise ValueError(
1040
- 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`"
1041
- )
1042
- image_embeds = added_cond_kwargs.get("image_embeds")
1043
- encoder_hidden_states = self.encoder_hid_proj(image_embeds)
1044
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "ip_image_proj":
1045
- if "image_embeds" not in added_cond_kwargs:
1046
- raise ValueError(
1047
- 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`"
1048
- )
1049
- image_embeds = added_cond_kwargs.get("image_embeds")
1050
- image_embeds = self.encoder_hid_proj(image_embeds)
1051
- encoder_hidden_states = (encoder_hidden_states, image_embeds)
1052
- return encoder_hidden_states
1053
-
1054
- def init_kv_extraction(self):
1055
- for block in self.down_blocks:
1056
- if hasattr(block, "has_cross_attention") and block.has_cross_attention:
1057
- block.init_kv_extraction()
1058
-
1059
- for block in self.up_blocks:
1060
- if hasattr(block, "has_cross_attention") and block.has_cross_attention:
1061
- block.init_kv_extraction()
1062
-
1063
- if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
1064
- self.mid_block.init_kv_extraction()
1065
-
1066
- def forward(
1067
- self,
1068
- sample: torch.FloatTensor,
1069
- timestep: Union[torch.Tensor, float, int],
1070
- encoder_hidden_states: torch.Tensor,
1071
- class_labels: Optional[torch.Tensor] = None,
1072
- timestep_cond: Optional[torch.Tensor] = None,
1073
- attention_mask: Optional[torch.Tensor] = None,
1074
- cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1075
- added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
1076
- down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
1077
- mid_block_additional_residual: Optional[torch.Tensor] = None,
1078
- down_intrablock_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
1079
- encoder_attention_mask: Optional[torch.Tensor] = None,
1080
- return_dict: bool = True,
1081
- ) -> Union[ExtractKVUNet2DConditionOutput, Tuple]:
1082
- r"""
1083
- The [`UNet2DConditionModel`] forward method.
1084
-
1085
- Args:
1086
- sample (`torch.FloatTensor`):
1087
- The noisy input tensor with the following shape `(batch, channel, height, width)`.
1088
- timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
1089
- encoder_hidden_states (`torch.FloatTensor`):
1090
- The encoder hidden states with shape `(batch, sequence_length, feature_dim)`.
1091
- class_labels (`torch.Tensor`, *optional*, defaults to `None`):
1092
- Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
1093
- timestep_cond: (`torch.Tensor`, *optional*, defaults to `None`):
1094
- Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed
1095
- through the `self.time_embedding` layer to obtain the timestep embeddings.
1096
- attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
1097
- An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
1098
- is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
1099
- negative values to the attention scores corresponding to "discard" tokens.
1100
- cross_attention_kwargs (`dict`, *optional*):
1101
- A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1102
- `self.processor` in
1103
- [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1104
- added_cond_kwargs: (`dict`, *optional*):
1105
- A kwargs dictionary containing additional embeddings that if specified are added to the embeddings that
1106
- are passed along to the UNet blocks.
1107
- down_block_additional_residuals: (`tuple` of `torch.Tensor`, *optional*):
1108
- A tuple of tensors that if specified are added to the residuals of down unet blocks.
1109
- mid_block_additional_residual: (`torch.Tensor`, *optional*):
1110
- A tensor that if specified is added to the residual of the middle unet block.
1111
- down_intrablock_additional_residuals (`tuple` of `torch.Tensor`, *optional*):
1112
- additional residuals to be added within UNet down blocks, for example from T2I-Adapter side model(s)
1113
- encoder_attention_mask (`torch.Tensor`):
1114
- A cross-attention mask of shape `(batch, sequence_length)` is applied to `encoder_hidden_states`. If
1115
- `True` the mask is kept, otherwise if `False` it is discarded. Mask will be converted into a bias,
1116
- which adds large negative values to the attention scores corresponding to "discard" tokens.
1117
- return_dict (`bool`, *optional*, defaults to `True`):
1118
- Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
1119
- tuple.
1120
-
1121
- Returns:
1122
- [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
1123
- If `return_dict` is True, an [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] is returned,
1124
- otherwise a `tuple` is returned where the first element is the sample tensor.
1125
- """
1126
- # By default samples have to be AT least a multiple of the overall upsampling factor.
1127
- # The overall upsampling factor is equal to 2 ** (# num of upsampling layers).
1128
- # However, the upsampling interpolation output size can be forced to fit any upsampling size
1129
- # on the fly if necessary.
1130
- default_overall_up_factor = 2**self.num_upsamplers
1131
-
1132
- # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
1133
- forward_upsample_size = False
1134
- upsample_size = None
1135
-
1136
- for dim in sample.shape[-2:]:
1137
- if dim % default_overall_up_factor != 0:
1138
- # Forward upsample size to force interpolation output size.
1139
- forward_upsample_size = True
1140
- break
1141
-
1142
- # ensure attention_mask is a bias, and give it a singleton query_tokens dimension
1143
- # expects mask of shape:
1144
- # [batch, key_tokens]
1145
- # adds singleton query_tokens dimension:
1146
- # [batch, 1, key_tokens]
1147
- # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
1148
- # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
1149
- # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
1150
- if attention_mask is not None:
1151
- # assume that mask is expressed as:
1152
- # (1 = keep, 0 = discard)
1153
- # convert mask into a bias that can be added to attention scores:
1154
- # (keep = +0, discard = -10000.0)
1155
- attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
1156
- attention_mask = attention_mask.unsqueeze(1)
1157
-
1158
- # convert encoder_attention_mask to a bias the same way we do for attention_mask
1159
- if encoder_attention_mask is not None:
1160
- encoder_attention_mask = (1 - encoder_attention_mask.to(sample.dtype)) * -10000.0
1161
- encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
1162
-
1163
- # 0. center input if necessary
1164
- if self.config.center_input_sample:
1165
- sample = 2 * sample - 1.0
1166
-
1167
- # 1. time
1168
- t_emb = self.get_time_embed(sample=sample, timestep=timestep)
1169
- emb = self.time_embedding(t_emb, timestep_cond)
1170
- aug_emb = None
1171
-
1172
- class_emb = self.get_class_embed(sample=sample, class_labels=class_labels)
1173
- if class_emb is not None:
1174
- if self.config.class_embeddings_concat:
1175
- emb = torch.cat([emb, class_emb], dim=-1)
1176
- else:
1177
- emb = emb + class_emb
1178
-
1179
- aug_emb = self.get_aug_embed(
1180
- emb=emb, encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
1181
- )
1182
- if self.config.addition_embed_type == "image_hint":
1183
- aug_emb, hint = aug_emb
1184
- sample = torch.cat([sample, hint], dim=1)
1185
-
1186
- emb = emb + aug_emb if aug_emb is not None else emb
1187
-
1188
- if self.time_embed_act is not None:
1189
- emb = self.time_embed_act(emb)
1190
-
1191
- encoder_hidden_states = self.process_encoder_hidden_states(
1192
- encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
1193
- )
1194
-
1195
- # 2. pre-process
1196
- sample = self.conv_in(sample)
1197
-
1198
- # 2.5 GLIGEN position net
1199
- if cross_attention_kwargs is not None and cross_attention_kwargs.get("gligen", None) is not None:
1200
- cross_attention_kwargs = cross_attention_kwargs.copy()
1201
- gligen_args = cross_attention_kwargs.pop("gligen")
1202
- cross_attention_kwargs["gligen"] = {"objs": self.position_net(**gligen_args)}
1203
-
1204
- if cross_attention_kwargs is not None and cross_attention_kwargs.get("kv_drop_idx", None) is not None:
1205
- threshold = cross_attention_kwargs.pop("kv_drop_idx")
1206
- cross_attention_kwargs["kv_drop_idx"] = timestep<threshold
1207
-
1208
- # 3. down
1209
- # we're popping the `scale` instead of getting it because otherwise `scale` will be propagated
1210
- # to the internal blocks and will raise deprecation warnings. this will be confusing for our users.
1211
- if cross_attention_kwargs is not None:
1212
- cross_attention_kwargs = cross_attention_kwargs.copy()
1213
- lora_scale = cross_attention_kwargs.pop("scale", 1.0)
1214
- else:
1215
- lora_scale = 1.0
1216
-
1217
- if USE_PEFT_BACKEND:
1218
- # weight the lora layers by setting `lora_scale` for each PEFT layer
1219
- scale_lora_layers(self, lora_scale)
1220
-
1221
- is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None
1222
- # using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets
1223
- is_adapter = down_intrablock_additional_residuals is not None
1224
- # maintain backward compatibility for legacy usage, where
1225
- # T2I-Adapter and ControlNet both use down_block_additional_residuals arg
1226
- # but can only use one or the other
1227
- if not is_adapter and mid_block_additional_residual is None and down_block_additional_residuals is not None:
1228
- deprecate(
1229
- "T2I should not use down_block_additional_residuals",
1230
- "1.3.0",
1231
- "Passing intrablock residual connections with `down_block_additional_residuals` is deprecated \
1232
- and will be removed in diffusers 1.3.0. `down_block_additional_residuals` should only be used \
1233
- for ControlNet. Please make sure use `down_intrablock_additional_residuals` instead. ",
1234
- standard_warn=False,
1235
- )
1236
- down_intrablock_additional_residuals = down_block_additional_residuals
1237
- is_adapter = True
1238
-
1239
- down_block_res_samples = (sample,)
1240
- extracted_kvs = {}
1241
- for downsample_block in self.down_blocks:
1242
- if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
1243
- # For t2i-adapter CrossAttnDownBlock2D
1244
- additional_residuals = {}
1245
- if is_adapter and len(down_intrablock_additional_residuals) > 0:
1246
- additional_residuals["additional_residuals"] = down_intrablock_additional_residuals.pop(0)
1247
-
1248
- sample, res_samples, extracted_kv = downsample_block(
1249
- hidden_states=sample,
1250
- temb=emb,
1251
- encoder_hidden_states=encoder_hidden_states,
1252
- attention_mask=attention_mask,
1253
- cross_attention_kwargs=cross_attention_kwargs,
1254
- encoder_attention_mask=encoder_attention_mask,
1255
- **additional_residuals,
1256
- )
1257
- extracted_kvs.update(extracted_kv)
1258
- else:
1259
- sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
1260
- if is_adapter and len(down_intrablock_additional_residuals) > 0:
1261
- sample += down_intrablock_additional_residuals.pop(0)
1262
-
1263
- down_block_res_samples += res_samples
1264
-
1265
- if is_controlnet:
1266
- new_down_block_res_samples = ()
1267
-
1268
- for down_block_res_sample, down_block_additional_residual in zip(
1269
- down_block_res_samples, down_block_additional_residuals
1270
- ):
1271
- down_block_res_sample = down_block_res_sample + down_block_additional_residual
1272
- new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)
1273
-
1274
- down_block_res_samples = new_down_block_res_samples
1275
-
1276
- # 4. mid
1277
- if self.mid_block is not None:
1278
- if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
1279
- sample, extracted_kv = self.mid_block(
1280
- sample,
1281
- emb,
1282
- encoder_hidden_states=encoder_hidden_states,
1283
- attention_mask=attention_mask,
1284
- cross_attention_kwargs=cross_attention_kwargs,
1285
- encoder_attention_mask=encoder_attention_mask,
1286
- )
1287
- extracted_kvs.update(extracted_kv)
1288
- else:
1289
- sample = self.mid_block(sample, emb)
1290
-
1291
- # To support T2I-Adapter-XL
1292
- if (
1293
- is_adapter
1294
- and len(down_intrablock_additional_residuals) > 0
1295
- and sample.shape == down_intrablock_additional_residuals[0].shape
1296
- ):
1297
- sample += down_intrablock_additional_residuals.pop(0)
1298
-
1299
- if is_controlnet:
1300
- sample = sample + mid_block_additional_residual
1301
-
1302
- # 5. up
1303
- for i, upsample_block in enumerate(self.up_blocks):
1304
- is_final_block = i == len(self.up_blocks) - 1
1305
-
1306
- res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
1307
- down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
1308
-
1309
- # if we have not reached the final block and need to forward the
1310
- # upsample size, we do it here
1311
- if not is_final_block and forward_upsample_size:
1312
- upsample_size = down_block_res_samples[-1].shape[2:]
1313
-
1314
- if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
1315
- sample, extract_kv = upsample_block(
1316
- hidden_states=sample,
1317
- temb=emb,
1318
- res_hidden_states_tuple=res_samples,
1319
- encoder_hidden_states=encoder_hidden_states,
1320
- cross_attention_kwargs=cross_attention_kwargs,
1321
- upsample_size=upsample_size,
1322
- attention_mask=attention_mask,
1323
- encoder_attention_mask=encoder_attention_mask,
1324
- )
1325
- extracted_kvs.update(extract_kv)
1326
- else:
1327
- sample = upsample_block(
1328
- hidden_states=sample,
1329
- temb=emb,
1330
- res_hidden_states_tuple=res_samples,
1331
- upsample_size=upsample_size,
1332
- )
1333
-
1334
- # 6. post-process
1335
- if self.conv_norm_out:
1336
- sample = self.conv_norm_out(sample)
1337
- sample = self.conv_act(sample)
1338
- sample = self.conv_out(sample)
1339
-
1340
- if USE_PEFT_BACKEND:
1341
- # remove `lora_scale` from each PEFT layer
1342
- unscale_lora_layers(self, lora_scale)
1343
-
1344
- if not return_dict:
1345
- return (sample, extracted_kvs)
1346
-
1347
- return ExtractKVUNet2DConditionOutput(sample=sample, cached_kvs=extracted_kvs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
module/unet/unet_2d_extractKV_blocks.py DELETED
@@ -1,1417 +0,0 @@
1
- # Copy from diffusers.models.unet.unet_2d_blocks.py
2
-
3
- # Copyright 2024 The HuggingFace Team. All rights reserved.
4
- #
5
- # Licensed under the Apache License, Version 2.0 (the "License");
6
- # you may not use this file except in compliance with the License.
7
- # You may obtain a copy of the License at
8
- #
9
- # http://www.apache.org/licenses/LICENSE-2.0
10
- #
11
- # Unless required by applicable law or agreed to in writing, software
12
- # distributed under the License is distributed on an "AS IS" BASIS,
13
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- # See the License for the specific language governing permissions and
15
- # limitations under the License.
16
- from typing import Any, Dict, Optional, Tuple, Union
17
-
18
- import numpy as np
19
- import torch
20
- import torch.nn.functional as F
21
- from torch import nn
22
-
23
- from diffusers.utils import deprecate, is_torch_version, logging
24
- from diffusers.utils.torch_utils import apply_freeu
25
- from diffusers.models.activations import get_activation
26
- from diffusers.models.attention_processor import Attention, AttnAddedKVProcessor, AttnAddedKVProcessor2_0
27
- from diffusers.models.normalization import AdaGroupNorm
28
- from diffusers.models.resnet import (
29
- Downsample2D,
30
- FirDownsample2D,
31
- FirUpsample2D,
32
- KDownsample2D,
33
- KUpsample2D,
34
- ResnetBlock2D,
35
- ResnetBlockCondNorm2D,
36
- Upsample2D,
37
- )
38
- from diffusers.models.transformers.dual_transformer_2d import DualTransformer2DModel
39
- from diffusers.models.transformers.transformer_2d import Transformer2DModel
40
-
41
- from module.transformers.transformer_2d_ExtractKV import ExtractKVTransformer2DModel
42
-
43
-
44
- logger = logging.get_logger(__name__) # pylint: disable=invalid-name
45
-
46
-
47
- def get_down_block(
48
- down_block_type: str,
49
- num_layers: int,
50
- in_channels: int,
51
- out_channels: int,
52
- temb_channels: int,
53
- add_downsample: bool,
54
- resnet_eps: float,
55
- resnet_act_fn: str,
56
- transformer_layers_per_block: int = 1,
57
- num_attention_heads: Optional[int] = None,
58
- resnet_groups: Optional[int] = None,
59
- cross_attention_dim: Optional[int] = None,
60
- downsample_padding: Optional[int] = None,
61
- dual_cross_attention: bool = False,
62
- use_linear_projection: bool = False,
63
- only_cross_attention: bool = False,
64
- upcast_attention: bool = False,
65
- resnet_time_scale_shift: str = "default",
66
- attention_type: str = "default",
67
- resnet_skip_time_act: bool = False,
68
- resnet_out_scale_factor: float = 1.0,
69
- cross_attention_norm: Optional[str] = None,
70
- attention_head_dim: Optional[int] = None,
71
- downsample_type: Optional[str] = None,
72
- dropout: float = 0.0,
73
- extract_self_attention_kv: bool = False,
74
- extract_cross_attention_kv: bool = False,
75
- ):
76
- # If attn head dim is not defined, we default it to the number of heads
77
- if attention_head_dim is None:
78
- logger.warning(
79
- f"It is recommended to provide `attention_head_dim` when calling `get_down_block`. Defaulting `attention_head_dim` to {num_attention_heads}."
80
- )
81
- attention_head_dim = num_attention_heads
82
-
83
- down_block_type = down_block_type[7:] if down_block_type.startswith("UNetRes") else down_block_type
84
- if down_block_type == "DownBlock2D":
85
- return DownBlock2D(
86
- num_layers=num_layers,
87
- in_channels=in_channels,
88
- out_channels=out_channels,
89
- temb_channels=temb_channels,
90
- dropout=dropout,
91
- add_downsample=add_downsample,
92
- resnet_eps=resnet_eps,
93
- resnet_act_fn=resnet_act_fn,
94
- resnet_groups=resnet_groups,
95
- downsample_padding=downsample_padding,
96
- resnet_time_scale_shift=resnet_time_scale_shift,
97
- )
98
- elif down_block_type == "ResnetDownsampleBlock2D":
99
- from diffusers.models.unets.unet_2d_blocks import ResnetDownsampleBlock2D
100
- return ResnetDownsampleBlock2D(
101
- num_layers=num_layers,
102
- in_channels=in_channels,
103
- out_channels=out_channels,
104
- temb_channels=temb_channels,
105
- dropout=dropout,
106
- add_downsample=add_downsample,
107
- resnet_eps=resnet_eps,
108
- resnet_act_fn=resnet_act_fn,
109
- resnet_groups=resnet_groups,
110
- resnet_time_scale_shift=resnet_time_scale_shift,
111
- skip_time_act=resnet_skip_time_act,
112
- output_scale_factor=resnet_out_scale_factor,
113
- )
114
- elif down_block_type == "AttnDownBlock2D":
115
- from diffusers.models.unets.unet_2d_blocks import AttnDownBlock2D
116
- if add_downsample is False:
117
- downsample_type = None
118
- else:
119
- downsample_type = downsample_type or "conv" # default to 'conv'
120
- return AttnDownBlock2D(
121
- num_layers=num_layers,
122
- in_channels=in_channels,
123
- out_channels=out_channels,
124
- temb_channels=temb_channels,
125
- dropout=dropout,
126
- resnet_eps=resnet_eps,
127
- resnet_act_fn=resnet_act_fn,
128
- resnet_groups=resnet_groups,
129
- downsample_padding=downsample_padding,
130
- attention_head_dim=attention_head_dim,
131
- resnet_time_scale_shift=resnet_time_scale_shift,
132
- downsample_type=downsample_type,
133
- )
134
- elif down_block_type == "ExtractKVCrossAttnDownBlock2D":
135
- if cross_attention_dim is None:
136
- raise ValueError("cross_attention_dim must be specified for ExtractKVCrossAttnDownBlock2D")
137
- return ExtractKVCrossAttnDownBlock2D(
138
- num_layers=num_layers,
139
- transformer_layers_per_block=transformer_layers_per_block,
140
- in_channels=in_channels,
141
- out_channels=out_channels,
142
- temb_channels=temb_channels,
143
- dropout=dropout,
144
- add_downsample=add_downsample,
145
- resnet_eps=resnet_eps,
146
- resnet_act_fn=resnet_act_fn,
147
- resnet_groups=resnet_groups,
148
- downsample_padding=downsample_padding,
149
- cross_attention_dim=cross_attention_dim,
150
- num_attention_heads=num_attention_heads,
151
- dual_cross_attention=dual_cross_attention,
152
- use_linear_projection=use_linear_projection,
153
- only_cross_attention=only_cross_attention,
154
- upcast_attention=upcast_attention,
155
- resnet_time_scale_shift=resnet_time_scale_shift,
156
- attention_type=attention_type,
157
- extract_self_attention_kv=extract_self_attention_kv,
158
- extract_cross_attention_kv=extract_cross_attention_kv,
159
- )
160
- elif down_block_type == "CrossAttnDownBlock2D":
161
- from diffusers.models.unets.unet_2d_blocks import CrossAttnDownBlock2D
162
- if cross_attention_dim is None:
163
- raise ValueError("cross_attention_dim must be specified for CrossAttnDownBlock2D")
164
- return CrossAttnDownBlock2D(
165
- num_layers=num_layers,
166
- transformer_layers_per_block=transformer_layers_per_block,
167
- in_channels=in_channels,
168
- out_channels=out_channels,
169
- temb_channels=temb_channels,
170
- dropout=dropout,
171
- add_downsample=add_downsample,
172
- resnet_eps=resnet_eps,
173
- resnet_act_fn=resnet_act_fn,
174
- resnet_groups=resnet_groups,
175
- downsample_padding=downsample_padding,
176
- cross_attention_dim=cross_attention_dim,
177
- num_attention_heads=num_attention_heads,
178
- dual_cross_attention=dual_cross_attention,
179
- use_linear_projection=use_linear_projection,
180
- only_cross_attention=only_cross_attention,
181
- upcast_attention=upcast_attention,
182
- resnet_time_scale_shift=resnet_time_scale_shift,
183
- attention_type=attention_type,
184
- )
185
- elif down_block_type == "SimpleCrossAttnDownBlock2D":
186
- if cross_attention_dim is None:
187
- raise ValueError("cross_attention_dim must be specified for SimpleCrossAttnDownBlock2D")
188
- from diffusers.models.unets.unet_2d_blocks import SimpleCrossAttnDownBlock2D
189
- return SimpleCrossAttnDownBlock2D(
190
- num_layers=num_layers,
191
- in_channels=in_channels,
192
- out_channels=out_channels,
193
- temb_channels=temb_channels,
194
- dropout=dropout,
195
- add_downsample=add_downsample,
196
- resnet_eps=resnet_eps,
197
- resnet_act_fn=resnet_act_fn,
198
- resnet_groups=resnet_groups,
199
- cross_attention_dim=cross_attention_dim,
200
- attention_head_dim=attention_head_dim,
201
- resnet_time_scale_shift=resnet_time_scale_shift,
202
- skip_time_act=resnet_skip_time_act,
203
- output_scale_factor=resnet_out_scale_factor,
204
- only_cross_attention=only_cross_attention,
205
- cross_attention_norm=cross_attention_norm,
206
- )
207
- elif down_block_type == "SkipDownBlock2D":
208
- from diffusers.models.unets.unet_2d_blocks import SkipDownBlock2D
209
- return SkipDownBlock2D(
210
- num_layers=num_layers,
211
- in_channels=in_channels,
212
- out_channels=out_channels,
213
- temb_channels=temb_channels,
214
- dropout=dropout,
215
- add_downsample=add_downsample,
216
- resnet_eps=resnet_eps,
217
- resnet_act_fn=resnet_act_fn,
218
- downsample_padding=downsample_padding,
219
- resnet_time_scale_shift=resnet_time_scale_shift,
220
- )
221
- elif down_block_type == "AttnSkipDownBlock2D":
222
- from diffusers.models.unets.unet_2d_blocks import AttnSkipDownBlock2D
223
- return AttnSkipDownBlock2D(
224
- num_layers=num_layers,
225
- in_channels=in_channels,
226
- out_channels=out_channels,
227
- temb_channels=temb_channels,
228
- dropout=dropout,
229
- add_downsample=add_downsample,
230
- resnet_eps=resnet_eps,
231
- resnet_act_fn=resnet_act_fn,
232
- attention_head_dim=attention_head_dim,
233
- resnet_time_scale_shift=resnet_time_scale_shift,
234
- )
235
- elif down_block_type == "DownEncoderBlock2D":
236
- from diffusers.models.unets.unet_2d_blocks import DownEncoderBlock2D
237
- return DownEncoderBlock2D(
238
- num_layers=num_layers,
239
- in_channels=in_channels,
240
- out_channels=out_channels,
241
- dropout=dropout,
242
- add_downsample=add_downsample,
243
- resnet_eps=resnet_eps,
244
- resnet_act_fn=resnet_act_fn,
245
- resnet_groups=resnet_groups,
246
- downsample_padding=downsample_padding,
247
- resnet_time_scale_shift=resnet_time_scale_shift,
248
- )
249
- elif down_block_type == "AttnDownEncoderBlock2D":
250
- from diffusers.models.unets.unet_2d_blocks import AttnDownEncoderBlock2D
251
- return AttnDownEncoderBlock2D(
252
- num_layers=num_layers,
253
- in_channels=in_channels,
254
- out_channels=out_channels,
255
- dropout=dropout,
256
- add_downsample=add_downsample,
257
- resnet_eps=resnet_eps,
258
- resnet_act_fn=resnet_act_fn,
259
- resnet_groups=resnet_groups,
260
- downsample_padding=downsample_padding,
261
- attention_head_dim=attention_head_dim,
262
- resnet_time_scale_shift=resnet_time_scale_shift,
263
- )
264
- elif down_block_type == "KDownBlock2D":
265
- from diffusers.models.unets.unet_2d_blocks import KDownBlock2D
266
- return KDownBlock2D(
267
- num_layers=num_layers,
268
- in_channels=in_channels,
269
- out_channels=out_channels,
270
- temb_channels=temb_channels,
271
- dropout=dropout,
272
- add_downsample=add_downsample,
273
- resnet_eps=resnet_eps,
274
- resnet_act_fn=resnet_act_fn,
275
- )
276
- elif down_block_type == "KCrossAttnDownBlock2D":
277
- from diffusers.models.unets.unet_2d_blocks import KCrossAttnDownBlock2D
278
- return KCrossAttnDownBlock2D(
279
- num_layers=num_layers,
280
- in_channels=in_channels,
281
- out_channels=out_channels,
282
- temb_channels=temb_channels,
283
- dropout=dropout,
284
- add_downsample=add_downsample,
285
- resnet_eps=resnet_eps,
286
- resnet_act_fn=resnet_act_fn,
287
- cross_attention_dim=cross_attention_dim,
288
- attention_head_dim=attention_head_dim,
289
- add_self_attention=True if not add_downsample else False,
290
- )
291
- raise ValueError(f"{down_block_type} does not exist.")
292
-
293
-
294
- def get_mid_block(
295
- mid_block_type: str,
296
- temb_channels: int,
297
- in_channels: int,
298
- resnet_eps: float,
299
- resnet_act_fn: str,
300
- resnet_groups: int,
301
- output_scale_factor: float = 1.0,
302
- transformer_layers_per_block: int = 1,
303
- num_attention_heads: Optional[int] = None,
304
- cross_attention_dim: Optional[int] = None,
305
- dual_cross_attention: bool = False,
306
- use_linear_projection: bool = False,
307
- mid_block_only_cross_attention: bool = False,
308
- upcast_attention: bool = False,
309
- resnet_time_scale_shift: str = "default",
310
- attention_type: str = "default",
311
- resnet_skip_time_act: bool = False,
312
- cross_attention_norm: Optional[str] = None,
313
- attention_head_dim: Optional[int] = 1,
314
- dropout: float = 0.0,
315
- extract_self_attention_kv: bool = False,
316
- extract_cross_attention_kv: bool = False,
317
- ):
318
- if mid_block_type == "ExtractKVUNetMidBlock2DCrossAttn":
319
- return ExtractKVUNetMidBlock2DCrossAttn(
320
- transformer_layers_per_block=transformer_layers_per_block,
321
- in_channels=in_channels,
322
- temb_channels=temb_channels,
323
- dropout=dropout,
324
- resnet_eps=resnet_eps,
325
- resnet_act_fn=resnet_act_fn,
326
- output_scale_factor=output_scale_factor,
327
- resnet_time_scale_shift=resnet_time_scale_shift,
328
- cross_attention_dim=cross_attention_dim,
329
- num_attention_heads=num_attention_heads,
330
- resnet_groups=resnet_groups,
331
- dual_cross_attention=dual_cross_attention,
332
- use_linear_projection=use_linear_projection,
333
- upcast_attention=upcast_attention,
334
- attention_type=attention_type,
335
- extract_self_attention_kv=extract_self_attention_kv,
336
- extract_cross_attention_kv=extract_cross_attention_kv,
337
- )
338
- elif mid_block_type == "UNetMidBlock2DCrossAttn":
339
- from diffusers.models.unets.unet_2d_blocks import UNetMidBlock2DCrossAttn
340
- return UNetMidBlock2DCrossAttn(
341
- transformer_layers_per_block=transformer_layers_per_block,
342
- in_channels=in_channels,
343
- temb_channels=temb_channels,
344
- dropout=dropout,
345
- resnet_eps=resnet_eps,
346
- resnet_act_fn=resnet_act_fn,
347
- output_scale_factor=output_scale_factor,
348
- resnet_time_scale_shift=resnet_time_scale_shift,
349
- cross_attention_dim=cross_attention_dim,
350
- num_attention_heads=num_attention_heads,
351
- resnet_groups=resnet_groups,
352
- dual_cross_attention=dual_cross_attention,
353
- use_linear_projection=use_linear_projection,
354
- upcast_attention=upcast_attention,
355
- attention_type=attention_type,
356
- )
357
- elif mid_block_type == "UNetMidBlock2DSimpleCrossAttn":
358
- from diffusers.models.unets.unet_2d_blocks import UNetMidBlock2DSimpleCrossAttn
359
- return UNetMidBlock2DSimpleCrossAttn(
360
- in_channels=in_channels,
361
- temb_channels=temb_channels,
362
- dropout=dropout,
363
- resnet_eps=resnet_eps,
364
- resnet_act_fn=resnet_act_fn,
365
- output_scale_factor=output_scale_factor,
366
- cross_attention_dim=cross_attention_dim,
367
- attention_head_dim=attention_head_dim,
368
- resnet_groups=resnet_groups,
369
- resnet_time_scale_shift=resnet_time_scale_shift,
370
- skip_time_act=resnet_skip_time_act,
371
- only_cross_attention=mid_block_only_cross_attention,
372
- cross_attention_norm=cross_attention_norm,
373
- )
374
- elif mid_block_type == "UNetMidBlock2D":
375
- from diffusers.models.unets.unet_2d_blocks import UNetMidBlock2D
376
- return UNetMidBlock2D(
377
- in_channels=in_channels,
378
- temb_channels=temb_channels,
379
- dropout=dropout,
380
- num_layers=0,
381
- resnet_eps=resnet_eps,
382
- resnet_act_fn=resnet_act_fn,
383
- output_scale_factor=output_scale_factor,
384
- resnet_groups=resnet_groups,
385
- resnet_time_scale_shift=resnet_time_scale_shift,
386
- add_attention=False,
387
- )
388
- elif mid_block_type is None:
389
- return None
390
- else:
391
- raise ValueError(f"unknown mid_block_type : {mid_block_type}")
392
-
393
-
394
- def get_up_block(
395
- up_block_type: str,
396
- num_layers: int,
397
- in_channels: int,
398
- out_channels: int,
399
- prev_output_channel: int,
400
- temb_channels: int,
401
- add_upsample: bool,
402
- resnet_eps: float,
403
- resnet_act_fn: str,
404
- resolution_idx: Optional[int] = None,
405
- transformer_layers_per_block: int = 1,
406
- num_attention_heads: Optional[int] = None,
407
- resnet_groups: Optional[int] = None,
408
- cross_attention_dim: Optional[int] = None,
409
- dual_cross_attention: bool = False,
410
- use_linear_projection: bool = False,
411
- only_cross_attention: bool = False,
412
- upcast_attention: bool = False,
413
- resnet_time_scale_shift: str = "default",
414
- attention_type: str = "default",
415
- resnet_skip_time_act: bool = False,
416
- resnet_out_scale_factor: float = 1.0,
417
- cross_attention_norm: Optional[str] = None,
418
- attention_head_dim: Optional[int] = None,
419
- upsample_type: Optional[str] = None,
420
- dropout: float = 0.0,
421
- extract_self_attention_kv: bool = False,
422
- extract_cross_attention_kv: bool = False,
423
- ) -> nn.Module:
424
- # If attn head dim is not defined, we default it to the number of heads
425
- if attention_head_dim is None:
426
- logger.warning(
427
- f"It is recommended to provide `attention_head_dim` when calling `get_up_block`. Defaulting `attention_head_dim` to {num_attention_heads}."
428
- )
429
- attention_head_dim = num_attention_heads
430
-
431
- up_block_type = up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type
432
- if up_block_type == "UpBlock2D":
433
- return UpBlock2D(
434
- num_layers=num_layers,
435
- in_channels=in_channels,
436
- out_channels=out_channels,
437
- prev_output_channel=prev_output_channel,
438
- temb_channels=temb_channels,
439
- resolution_idx=resolution_idx,
440
- dropout=dropout,
441
- add_upsample=add_upsample,
442
- resnet_eps=resnet_eps,
443
- resnet_act_fn=resnet_act_fn,
444
- resnet_groups=resnet_groups,
445
- resnet_time_scale_shift=resnet_time_scale_shift,
446
- )
447
- elif up_block_type == "ResnetUpsampleBlock2D":
448
- from diffusers.models.unets.unet_2d_blocks import ResnetUpsampleBlock2D
449
- return ResnetUpsampleBlock2D(
450
- num_layers=num_layers,
451
- in_channels=in_channels,
452
- out_channels=out_channels,
453
- prev_output_channel=prev_output_channel,
454
- temb_channels=temb_channels,
455
- resolution_idx=resolution_idx,
456
- dropout=dropout,
457
- add_upsample=add_upsample,
458
- resnet_eps=resnet_eps,
459
- resnet_act_fn=resnet_act_fn,
460
- resnet_groups=resnet_groups,
461
- resnet_time_scale_shift=resnet_time_scale_shift,
462
- skip_time_act=resnet_skip_time_act,
463
- output_scale_factor=resnet_out_scale_factor,
464
- )
465
- elif up_block_type == "ExtractKVCrossAttnUpBlock2D":
466
- if cross_attention_dim is None:
467
- raise ValueError("cross_attention_dim must be specified for CrossAttnUpBlock2D")
468
- return ExtractKVCrossAttnUpBlock2D(
469
- num_layers=num_layers,
470
- transformer_layers_per_block=transformer_layers_per_block,
471
- in_channels=in_channels,
472
- out_channels=out_channels,
473
- prev_output_channel=prev_output_channel,
474
- temb_channels=temb_channels,
475
- resolution_idx=resolution_idx,
476
- dropout=dropout,
477
- add_upsample=add_upsample,
478
- resnet_eps=resnet_eps,
479
- resnet_act_fn=resnet_act_fn,
480
- resnet_groups=resnet_groups,
481
- cross_attention_dim=cross_attention_dim,
482
- num_attention_heads=num_attention_heads,
483
- dual_cross_attention=dual_cross_attention,
484
- use_linear_projection=use_linear_projection,
485
- only_cross_attention=only_cross_attention,
486
- upcast_attention=upcast_attention,
487
- resnet_time_scale_shift=resnet_time_scale_shift,
488
- attention_type=attention_type,
489
- extract_self_attention_kv=extract_self_attention_kv,
490
- extract_cross_attention_kv=extract_cross_attention_kv,
491
- )
492
- elif up_block_type == "CrossAttnUpBlock2D":
493
- if cross_attention_dim is None:
494
- raise ValueError("cross_attention_dim must be specified for CrossAttnUpBlock2D")
495
- from diffusers.models.unets.unet_2d_blocks import CrossAttnUpBlock2D
496
- return CrossAttnUpBlock2D(
497
- num_layers=num_layers,
498
- transformer_layers_per_block=transformer_layers_per_block,
499
- in_channels=in_channels,
500
- out_channels=out_channels,
501
- prev_output_channel=prev_output_channel,
502
- temb_channels=temb_channels,
503
- resolution_idx=resolution_idx,
504
- dropout=dropout,
505
- add_upsample=add_upsample,
506
- resnet_eps=resnet_eps,
507
- resnet_act_fn=resnet_act_fn,
508
- resnet_groups=resnet_groups,
509
- cross_attention_dim=cross_attention_dim,
510
- num_attention_heads=num_attention_heads,
511
- dual_cross_attention=dual_cross_attention,
512
- use_linear_projection=use_linear_projection,
513
- only_cross_attention=only_cross_attention,
514
- upcast_attention=upcast_attention,
515
- resnet_time_scale_shift=resnet_time_scale_shift,
516
- attention_type=attention_type,
517
- )
518
- elif up_block_type == "SimpleCrossAttnUpBlock2D":
519
- if cross_attention_dim is None:
520
- raise ValueError("cross_attention_dim must be specified for SimpleCrossAttnUpBlock2D")
521
- from diffusers.models.unets.unet_2d_blocks import SimpleCrossAttnUpBlock2D
522
- return SimpleCrossAttnUpBlock2D(
523
- num_layers=num_layers,
524
- in_channels=in_channels,
525
- out_channels=out_channels,
526
- prev_output_channel=prev_output_channel,
527
- temb_channels=temb_channels,
528
- resolution_idx=resolution_idx,
529
- dropout=dropout,
530
- add_upsample=add_upsample,
531
- resnet_eps=resnet_eps,
532
- resnet_act_fn=resnet_act_fn,
533
- resnet_groups=resnet_groups,
534
- cross_attention_dim=cross_attention_dim,
535
- attention_head_dim=attention_head_dim,
536
- resnet_time_scale_shift=resnet_time_scale_shift,
537
- skip_time_act=resnet_skip_time_act,
538
- output_scale_factor=resnet_out_scale_factor,
539
- only_cross_attention=only_cross_attention,
540
- cross_attention_norm=cross_attention_norm,
541
- )
542
- elif up_block_type == "AttnUpBlock2D":
543
- from diffusers.models.unets.unet_2d_blocks import AttnUpBlock2D
544
- if add_upsample is False:
545
- upsample_type = None
546
- else:
547
- upsample_type = upsample_type or "conv" # default to 'conv'
548
-
549
- return AttnUpBlock2D(
550
- num_layers=num_layers,
551
- in_channels=in_channels,
552
- out_channels=out_channels,
553
- prev_output_channel=prev_output_channel,
554
- temb_channels=temb_channels,
555
- resolution_idx=resolution_idx,
556
- dropout=dropout,
557
- resnet_eps=resnet_eps,
558
- resnet_act_fn=resnet_act_fn,
559
- resnet_groups=resnet_groups,
560
- attention_head_dim=attention_head_dim,
561
- resnet_time_scale_shift=resnet_time_scale_shift,
562
- upsample_type=upsample_type,
563
- )
564
- elif up_block_type == "SkipUpBlock2D":
565
- from diffusers.models.unets.unet_2d_blocks import SkipUpBlock2D
566
- return SkipUpBlock2D(
567
- num_layers=num_layers,
568
- in_channels=in_channels,
569
- out_channels=out_channels,
570
- prev_output_channel=prev_output_channel,
571
- temb_channels=temb_channels,
572
- resolution_idx=resolution_idx,
573
- dropout=dropout,
574
- add_upsample=add_upsample,
575
- resnet_eps=resnet_eps,
576
- resnet_act_fn=resnet_act_fn,
577
- resnet_time_scale_shift=resnet_time_scale_shift,
578
- )
579
- elif up_block_type == "AttnSkipUpBlock2D":
580
- from diffusers.models.unets.unet_2d_blocks import AttnSkipUpBlock2D
581
- return AttnSkipUpBlock2D(
582
- num_layers=num_layers,
583
- in_channels=in_channels,
584
- out_channels=out_channels,
585
- prev_output_channel=prev_output_channel,
586
- temb_channels=temb_channels,
587
- resolution_idx=resolution_idx,
588
- dropout=dropout,
589
- add_upsample=add_upsample,
590
- resnet_eps=resnet_eps,
591
- resnet_act_fn=resnet_act_fn,
592
- attention_head_dim=attention_head_dim,
593
- resnet_time_scale_shift=resnet_time_scale_shift,
594
- )
595
- elif up_block_type == "UpDecoderBlock2D":
596
- from diffusers.models.unets.unet_2d_blocks import UpDecoderBlock2D
597
- return UpDecoderBlock2D(
598
- num_layers=num_layers,
599
- in_channels=in_channels,
600
- out_channels=out_channels,
601
- resolution_idx=resolution_idx,
602
- dropout=dropout,
603
- add_upsample=add_upsample,
604
- resnet_eps=resnet_eps,
605
- resnet_act_fn=resnet_act_fn,
606
- resnet_groups=resnet_groups,
607
- resnet_time_scale_shift=resnet_time_scale_shift,
608
- temb_channels=temb_channels,
609
- )
610
- elif up_block_type == "AttnUpDecoderBlock2D":
611
- from diffusers.models.unets.unet_2d_blocks import AttnUpDecoderBlock2D
612
- return AttnUpDecoderBlock2D(
613
- num_layers=num_layers,
614
- in_channels=in_channels,
615
- out_channels=out_channels,
616
- resolution_idx=resolution_idx,
617
- dropout=dropout,
618
- add_upsample=add_upsample,
619
- resnet_eps=resnet_eps,
620
- resnet_act_fn=resnet_act_fn,
621
- resnet_groups=resnet_groups,
622
- attention_head_dim=attention_head_dim,
623
- resnet_time_scale_shift=resnet_time_scale_shift,
624
- temb_channels=temb_channels,
625
- )
626
- elif up_block_type == "KUpBlock2D":
627
- from diffusers.models.unets.unet_2d_blocks import KUpBlock2D
628
- return KUpBlock2D(
629
- num_layers=num_layers,
630
- in_channels=in_channels,
631
- out_channels=out_channels,
632
- temb_channels=temb_channels,
633
- resolution_idx=resolution_idx,
634
- dropout=dropout,
635
- add_upsample=add_upsample,
636
- resnet_eps=resnet_eps,
637
- resnet_act_fn=resnet_act_fn,
638
- )
639
- elif up_block_type == "KCrossAttnUpBlock2D":
640
- from diffusers.models.unets.unet_2d_blocks import KCrossAttnUpBlock2D
641
- return KCrossAttnUpBlock2D(
642
- num_layers=num_layers,
643
- in_channels=in_channels,
644
- out_channels=out_channels,
645
- temb_channels=temb_channels,
646
- resolution_idx=resolution_idx,
647
- dropout=dropout,
648
- add_upsample=add_upsample,
649
- resnet_eps=resnet_eps,
650
- resnet_act_fn=resnet_act_fn,
651
- cross_attention_dim=cross_attention_dim,
652
- attention_head_dim=attention_head_dim,
653
- )
654
-
655
- raise ValueError(f"{up_block_type} does not exist.")
656
-
657
-
658
- class AutoencoderTinyBlock(nn.Module):
659
- """
660
- Tiny Autoencoder block used in [`AutoencoderTiny`]. It is a mini residual module consisting of plain conv + ReLU
661
- blocks.
662
-
663
- Args:
664
- in_channels (`int`): The number of input channels.
665
- out_channels (`int`): The number of output channels.
666
- act_fn (`str`):
667
- ` The activation function to use. Supported values are `"swish"`, `"mish"`, `"gelu"`, and `"relu"`.
668
-
669
- Returns:
670
- `torch.FloatTensor`: A tensor with the same shape as the input tensor, but with the number of channels equal to
671
- `out_channels`.
672
- """
673
-
674
- def __init__(self, in_channels: int, out_channels: int, act_fn: str):
675
- super().__init__()
676
- act_fn = get_activation(act_fn)
677
- self.conv = nn.Sequential(
678
- nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
679
- act_fn,
680
- nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),
681
- act_fn,
682
- nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),
683
- )
684
- self.skip = (
685
- nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False)
686
- if in_channels != out_channels
687
- else nn.Identity()
688
- )
689
- self.fuse = nn.ReLU()
690
-
691
- def forward(self, x: torch.FloatTensor) -> torch.FloatTensor:
692
- return self.fuse(self.conv(x) + self.skip(x))
693
-
694
-
695
- class ExtractKVUNetMidBlock2DCrossAttn(nn.Module):
696
- def __init__(
697
- self,
698
- in_channels: int,
699
- temb_channels: int,
700
- out_channels: Optional[int] = None,
701
- dropout: float = 0.0,
702
- num_layers: int = 1,
703
- transformer_layers_per_block: Union[int, Tuple[int]] = 1,
704
- resnet_eps: float = 1e-6,
705
- resnet_time_scale_shift: str = "default",
706
- resnet_act_fn: str = "swish",
707
- resnet_groups: int = 32,
708
- resnet_groups_out: Optional[int] = None,
709
- resnet_pre_norm: bool = True,
710
- num_attention_heads: int = 1,
711
- output_scale_factor: float = 1.0,
712
- cross_attention_dim: int = 1280,
713
- dual_cross_attention: bool = False,
714
- use_linear_projection: bool = False,
715
- upcast_attention: bool = False,
716
- attention_type: str = "default",
717
- extract_self_attention_kv: bool = False,
718
- extract_cross_attention_kv: bool = False,
719
- ):
720
- super().__init__()
721
-
722
- out_channels = out_channels or in_channels
723
- self.in_channels = in_channels
724
- self.out_channels = out_channels
725
-
726
- self.has_cross_attention = True
727
- self.num_attention_heads = num_attention_heads
728
- resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
729
-
730
- # support for variable transformer layers per block
731
- if isinstance(transformer_layers_per_block, int):
732
- transformer_layers_per_block = [transformer_layers_per_block] * num_layers
733
-
734
- resnet_groups_out = resnet_groups_out or resnet_groups
735
-
736
- # there is always at least one resnet
737
- resnets = [
738
- ResnetBlock2D(
739
- in_channels=in_channels,
740
- out_channels=out_channels,
741
- temb_channels=temb_channels,
742
- eps=resnet_eps,
743
- groups=resnet_groups,
744
- groups_out=resnet_groups_out,
745
- dropout=dropout,
746
- time_embedding_norm=resnet_time_scale_shift,
747
- non_linearity=resnet_act_fn,
748
- output_scale_factor=output_scale_factor,
749
- pre_norm=resnet_pre_norm,
750
- )
751
- ]
752
- attentions = []
753
-
754
- for i in range(num_layers):
755
- if not dual_cross_attention:
756
- attentions.append(
757
- ExtractKVTransformer2DModel(
758
- num_attention_heads,
759
- out_channels // num_attention_heads,
760
- in_channels=out_channels,
761
- num_layers=transformer_layers_per_block[i],
762
- cross_attention_dim=cross_attention_dim,
763
- norm_num_groups=resnet_groups_out,
764
- use_linear_projection=use_linear_projection,
765
- upcast_attention=upcast_attention,
766
- attention_type=attention_type,
767
- extract_self_attention_kv=extract_self_attention_kv,
768
- extract_cross_attention_kv=extract_cross_attention_kv,
769
- )
770
- )
771
- else:
772
- attentions.append(
773
- DualTransformer2DModel(
774
- num_attention_heads,
775
- out_channels // num_attention_heads,
776
- in_channels=out_channels,
777
- num_layers=1,
778
- cross_attention_dim=cross_attention_dim,
779
- norm_num_groups=resnet_groups,
780
- )
781
- )
782
- resnets.append(
783
- ResnetBlock2D(
784
- in_channels=out_channels,
785
- out_channels=out_channels,
786
- temb_channels=temb_channels,
787
- eps=resnet_eps,
788
- groups=resnet_groups_out,
789
- dropout=dropout,
790
- time_embedding_norm=resnet_time_scale_shift,
791
- non_linearity=resnet_act_fn,
792
- output_scale_factor=output_scale_factor,
793
- pre_norm=resnet_pre_norm,
794
- )
795
- )
796
-
797
- self.attentions = nn.ModuleList(attentions)
798
- self.resnets = nn.ModuleList(resnets)
799
-
800
- self.gradient_checkpointing = False
801
-
802
- def forward(
803
- self,
804
- hidden_states: torch.FloatTensor,
805
- temb: Optional[torch.FloatTensor] = None,
806
- encoder_hidden_states: Optional[torch.FloatTensor] = None,
807
- attention_mask: Optional[torch.FloatTensor] = None,
808
- cross_attention_kwargs: Optional[Dict[str, Any]] = None,
809
- encoder_attention_mask: Optional[torch.FloatTensor] = None,
810
- ) -> torch.FloatTensor:
811
- if cross_attention_kwargs is not None:
812
- if cross_attention_kwargs.get("scale", None) is not None:
813
- logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
814
-
815
- hidden_states = self.resnets[0](hidden_states, temb)
816
- extracted_kvs = {}
817
- for attn, resnet in zip(self.attentions, self.resnets[1:]):
818
- if self.training and self.gradient_checkpointing:
819
-
820
- def create_custom_forward(module, return_dict=None):
821
- def custom_forward(*inputs):
822
- if return_dict is not None:
823
- return module(*inputs, return_dict=return_dict)
824
- else:
825
- return module(*inputs)
826
-
827
- return custom_forward
828
-
829
- ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
830
- hidden_states, extracted_kv = attn(
831
- hidden_states,
832
- timestep=temb,
833
- encoder_hidden_states=encoder_hidden_states,
834
- cross_attention_kwargs=cross_attention_kwargs,
835
- attention_mask=attention_mask,
836
- encoder_attention_mask=encoder_attention_mask,
837
- return_dict=False,
838
- )
839
- hidden_states = torch.utils.checkpoint.checkpoint(
840
- create_custom_forward(resnet),
841
- hidden_states,
842
- temb,
843
- **ckpt_kwargs,
844
- )
845
- else:
846
- hidden_states, extracted_kv = attn(
847
- hidden_states,
848
- timestep=temb,
849
- encoder_hidden_states=encoder_hidden_states,
850
- cross_attention_kwargs=cross_attention_kwargs,
851
- attention_mask=attention_mask,
852
- encoder_attention_mask=encoder_attention_mask,
853
- return_dict=False,
854
- )
855
- hidden_states = resnet(hidden_states, temb)
856
-
857
- extracted_kvs.update(extracted_kv)
858
-
859
- return hidden_states, extracted_kvs
860
-
861
- def init_kv_extraction(self):
862
- for block in self.attentions:
863
- block.init_kv_extraction()
864
-
865
-
866
- class ExtractKVCrossAttnDownBlock2D(nn.Module):
867
- def __init__(
868
- self,
869
- in_channels: int,
870
- out_channels: int,
871
- temb_channels: int,
872
- dropout: float = 0.0,
873
- num_layers: int = 1, # Originally n_layers
874
- transformer_layers_per_block: Union[int, Tuple[int]] = 1,
875
- resnet_eps: float = 1e-6,
876
- resnet_time_scale_shift: str = "default",
877
- resnet_act_fn: str = "swish",
878
- resnet_groups: int = 32,
879
- resnet_pre_norm: bool = True,
880
- num_attention_heads: int = 1,
881
- cross_attention_dim: int = 1280,
882
- output_scale_factor: float = 1.0,
883
- downsample_padding: int = 1,
884
- add_downsample: bool = True,
885
- dual_cross_attention: bool = False,
886
- use_linear_projection: bool = False,
887
- only_cross_attention: bool = False,
888
- upcast_attention: bool = False,
889
- attention_type: str = "default",
890
- extract_self_attention_kv: bool = False,
891
- extract_cross_attention_kv: bool = False,
892
- ):
893
- super().__init__()
894
- resnets = []
895
- attentions = []
896
-
897
- self.has_cross_attention = True
898
- self.num_attention_heads = num_attention_heads
899
- if isinstance(transformer_layers_per_block, int):
900
- transformer_layers_per_block = [transformer_layers_per_block] * num_layers
901
-
902
- for i in range(num_layers):
903
- in_channels = in_channels if i == 0 else out_channels
904
- resnets.append(
905
- ResnetBlock2D(
906
- in_channels=in_channels,
907
- out_channels=out_channels,
908
- temb_channels=temb_channels,
909
- eps=resnet_eps,
910
- groups=resnet_groups,
911
- dropout=dropout,
912
- time_embedding_norm=resnet_time_scale_shift,
913
- non_linearity=resnet_act_fn,
914
- output_scale_factor=output_scale_factor,
915
- pre_norm=resnet_pre_norm,
916
- )
917
- )
918
- if not dual_cross_attention:
919
- attentions.append(
920
- ExtractKVTransformer2DModel(
921
- num_attention_heads,
922
- out_channels // num_attention_heads,
923
- in_channels=out_channels,
924
- num_layers=transformer_layers_per_block[i],
925
- cross_attention_dim=cross_attention_dim,
926
- norm_num_groups=resnet_groups,
927
- use_linear_projection=use_linear_projection,
928
- only_cross_attention=only_cross_attention,
929
- upcast_attention=upcast_attention,
930
- attention_type=attention_type,
931
- extract_self_attention_kv=extract_self_attention_kv,
932
- extract_cross_attention_kv=extract_cross_attention_kv,
933
- )
934
- )
935
- else:
936
- raise ValueError("Dual cross attention is not supported in ExtractKVCrossAttnDownBlock2D")
937
-
938
- self.attentions = nn.ModuleList(attentions)
939
- self.resnets = nn.ModuleList(resnets)
940
-
941
- if add_downsample:
942
- self.downsamplers = nn.ModuleList(
943
- [
944
- Downsample2D(
945
- out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
946
- )
947
- ]
948
- )
949
- else:
950
- self.downsamplers = None
951
-
952
- self.gradient_checkpointing = False
953
-
954
- def forward(
955
- self,
956
- hidden_states: torch.FloatTensor,
957
- temb: Optional[torch.FloatTensor] = None,
958
- encoder_hidden_states: Optional[torch.FloatTensor] = None,
959
- attention_mask: Optional[torch.FloatTensor] = None,
960
- cross_attention_kwargs: Optional[Dict[str, Any]] = None,
961
- encoder_attention_mask: Optional[torch.FloatTensor] = None,
962
- additional_residuals: Optional[torch.FloatTensor] = None,
963
- ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]:
964
- if cross_attention_kwargs is not None:
965
- if cross_attention_kwargs.get("scale", None) is not None:
966
- logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
967
-
968
- output_states = ()
969
- extracted_kvs = {}
970
-
971
- blocks = list(zip(self.resnets, self.attentions))
972
-
973
- for i, (resnet, attn) in enumerate(blocks):
974
- if self.training and self.gradient_checkpointing:
975
-
976
- def create_custom_forward(module, return_dict=None):
977
- def custom_forward(*inputs):
978
- if return_dict is not None:
979
- return module(*inputs, return_dict=return_dict)
980
- else:
981
- return module(*inputs)
982
-
983
- return custom_forward
984
-
985
- ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
986
- hidden_states = torch.utils.checkpoint.checkpoint(
987
- create_custom_forward(resnet),
988
- hidden_states,
989
- temb,
990
- **ckpt_kwargs,
991
- )
992
- hidden_states, extracted_kv = attn(
993
- hidden_states,
994
- timestep=temb,
995
- encoder_hidden_states=encoder_hidden_states,
996
- cross_attention_kwargs=cross_attention_kwargs,
997
- attention_mask=attention_mask,
998
- encoder_attention_mask=encoder_attention_mask,
999
- return_dict=False,
1000
- )
1001
- else:
1002
- hidden_states = resnet(hidden_states, temb)
1003
- hidden_states, extracted_kv = attn(
1004
- hidden_states,
1005
- timestep=temb,
1006
- encoder_hidden_states=encoder_hidden_states,
1007
- cross_attention_kwargs=cross_attention_kwargs,
1008
- attention_mask=attention_mask,
1009
- encoder_attention_mask=encoder_attention_mask,
1010
- return_dict=False,
1011
- )
1012
-
1013
- # apply additional residuals to the output of the last pair of resnet and attention blocks
1014
- if i == len(blocks) - 1 and additional_residuals is not None:
1015
- hidden_states = hidden_states + additional_residuals
1016
-
1017
- output_states = output_states + (hidden_states,)
1018
- extracted_kvs.update(extracted_kv)
1019
-
1020
- if self.downsamplers is not None:
1021
- for downsampler in self.downsamplers:
1022
- hidden_states = downsampler(hidden_states)
1023
-
1024
- output_states = output_states + (hidden_states,)
1025
-
1026
- return hidden_states, output_states, extracted_kvs
1027
-
1028
- def init_kv_extraction(self):
1029
- for block in self.attentions:
1030
- block.init_kv_extraction()
1031
-
1032
-
1033
- class ExtractKVCrossAttnUpBlock2D(nn.Module):
1034
- def __init__(
1035
- self,
1036
- in_channels: int,
1037
- out_channels: int,
1038
- prev_output_channel: int,
1039
- temb_channels: int,
1040
- resolution_idx: Optional[int] = None,
1041
- dropout: float = 0.0,
1042
- num_layers: int = 1,
1043
- transformer_layers_per_block: Union[int, Tuple[int]] = 1,
1044
- resnet_eps: float = 1e-6,
1045
- resnet_time_scale_shift: str = "default",
1046
- resnet_act_fn: str = "swish",
1047
- resnet_groups: int = 32,
1048
- resnet_pre_norm: bool = True,
1049
- num_attention_heads: int = 1,
1050
- cross_attention_dim: int = 1280,
1051
- output_scale_factor: float = 1.0,
1052
- add_upsample: bool = True,
1053
- dual_cross_attention: bool = False,
1054
- use_linear_projection: bool = False,
1055
- only_cross_attention: bool = False,
1056
- upcast_attention: bool = False,
1057
- attention_type: str = "default",
1058
- extract_self_attention_kv: bool = False,
1059
- extract_cross_attention_kv: bool = False,
1060
- ):
1061
- super().__init__()
1062
- resnets = []
1063
- attentions = []
1064
-
1065
- self.has_cross_attention = True
1066
- self.num_attention_heads = num_attention_heads
1067
-
1068
- if isinstance(transformer_layers_per_block, int):
1069
- transformer_layers_per_block = [transformer_layers_per_block] * num_layers
1070
-
1071
- for i in range(num_layers):
1072
- res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
1073
- resnet_in_channels = prev_output_channel if i == 0 else out_channels
1074
-
1075
- resnets.append(
1076
- ResnetBlock2D(
1077
- in_channels=resnet_in_channels + res_skip_channels,
1078
- out_channels=out_channels,
1079
- temb_channels=temb_channels,
1080
- eps=resnet_eps,
1081
- groups=resnet_groups,
1082
- dropout=dropout,
1083
- time_embedding_norm=resnet_time_scale_shift,
1084
- non_linearity=resnet_act_fn,
1085
- output_scale_factor=output_scale_factor,
1086
- pre_norm=resnet_pre_norm,
1087
- )
1088
- )
1089
- if not dual_cross_attention:
1090
- attentions.append(
1091
- ExtractKVTransformer2DModel(
1092
- num_attention_heads,
1093
- out_channels // num_attention_heads,
1094
- in_channels=out_channels,
1095
- num_layers=transformer_layers_per_block[i],
1096
- cross_attention_dim=cross_attention_dim,
1097
- norm_num_groups=resnet_groups,
1098
- use_linear_projection=use_linear_projection,
1099
- only_cross_attention=only_cross_attention,
1100
- upcast_attention=upcast_attention,
1101
- attention_type=attention_type,
1102
- extract_self_attention_kv=extract_self_attention_kv,
1103
- extract_cross_attention_kv=extract_cross_attention_kv,
1104
- )
1105
- )
1106
- else:
1107
- raise ValueError("Dual cross attention is not supported in ExtractKVCrossAttnUpBlock2D")
1108
- self.attentions = nn.ModuleList(attentions)
1109
- self.resnets = nn.ModuleList(resnets)
1110
-
1111
- if add_upsample:
1112
- self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)])
1113
- else:
1114
- self.upsamplers = None
1115
-
1116
- self.gradient_checkpointing = False
1117
- self.resolution_idx = resolution_idx
1118
-
1119
- def forward(
1120
- self,
1121
- hidden_states: torch.FloatTensor,
1122
- res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
1123
- temb: Optional[torch.FloatTensor] = None,
1124
- encoder_hidden_states: Optional[torch.FloatTensor] = None,
1125
- cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1126
- upsample_size: Optional[int] = None,
1127
- attention_mask: Optional[torch.FloatTensor] = None,
1128
- encoder_attention_mask: Optional[torch.FloatTensor] = None,
1129
- ) -> torch.FloatTensor:
1130
- if cross_attention_kwargs is not None:
1131
- if cross_attention_kwargs.get("scale", None) is not None:
1132
- logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
1133
-
1134
- is_freeu_enabled = (
1135
- getattr(self, "s1", None)
1136
- and getattr(self, "s2", None)
1137
- and getattr(self, "b1", None)
1138
- and getattr(self, "b2", None)
1139
- )
1140
-
1141
- extracted_kvs = {}
1142
- for resnet, attn in zip(self.resnets, self.attentions):
1143
- # pop res hidden states
1144
- res_hidden_states = res_hidden_states_tuple[-1]
1145
- res_hidden_states_tuple = res_hidden_states_tuple[:-1]
1146
-
1147
- # FreeU: Only operate on the first two stages
1148
- if is_freeu_enabled:
1149
- hidden_states, res_hidden_states = apply_freeu(
1150
- self.resolution_idx,
1151
- hidden_states,
1152
- res_hidden_states,
1153
- s1=self.s1,
1154
- s2=self.s2,
1155
- b1=self.b1,
1156
- b2=self.b2,
1157
- )
1158
-
1159
- hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
1160
-
1161
- if self.training and self.gradient_checkpointing:
1162
-
1163
- def create_custom_forward(module, return_dict=None):
1164
- def custom_forward(*inputs):
1165
- if return_dict is not None:
1166
- return module(*inputs, return_dict=return_dict)
1167
- else:
1168
- return module(*inputs)
1169
-
1170
- return custom_forward
1171
-
1172
- ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
1173
- hidden_states = torch.utils.checkpoint.checkpoint(
1174
- create_custom_forward(resnet),
1175
- hidden_states,
1176
- temb,
1177
- **ckpt_kwargs,
1178
- )
1179
- hidden_states, extracted_kv = attn(
1180
- hidden_states,
1181
- timestep=temb,
1182
- encoder_hidden_states=encoder_hidden_states,
1183
- cross_attention_kwargs=cross_attention_kwargs,
1184
- attention_mask=attention_mask,
1185
- encoder_attention_mask=encoder_attention_mask,
1186
- return_dict=False,
1187
- )
1188
- else:
1189
- hidden_states = resnet(hidden_states, temb)
1190
- hidden_states, extracted_kv = attn(
1191
- hidden_states,
1192
- timestep=temb,
1193
- encoder_hidden_states=encoder_hidden_states,
1194
- cross_attention_kwargs=cross_attention_kwargs,
1195
- attention_mask=attention_mask,
1196
- encoder_attention_mask=encoder_attention_mask,
1197
- return_dict=False,
1198
- )
1199
-
1200
- extracted_kvs.update(extracted_kv)
1201
-
1202
- if self.upsamplers is not None:
1203
- for upsampler in self.upsamplers:
1204
- hidden_states = upsampler(hidden_states, upsample_size)
1205
-
1206
- return hidden_states, extracted_kvs
1207
-
1208
- def init_kv_extraction(self):
1209
- for block in self.attentions:
1210
- block.init_kv_extraction()
1211
-
1212
-
1213
- class DownBlock2D(nn.Module):
1214
- def __init__(
1215
- self,
1216
- in_channels: int,
1217
- out_channels: int,
1218
- temb_channels: int,
1219
- dropout: float = 0.0,
1220
- num_layers: int = 1,
1221
- resnet_eps: float = 1e-6,
1222
- resnet_time_scale_shift: str = "default",
1223
- resnet_act_fn: str = "swish",
1224
- resnet_groups: int = 32,
1225
- resnet_pre_norm: bool = True,
1226
- output_scale_factor: float = 1.0,
1227
- add_downsample: bool = True,
1228
- downsample_padding: int = 1,
1229
- ):
1230
- super().__init__()
1231
- resnets = []
1232
-
1233
- for i in range(num_layers):
1234
- in_channels = in_channels if i == 0 else out_channels
1235
- resnets.append(
1236
- ResnetBlock2D(
1237
- in_channels=in_channels,
1238
- out_channels=out_channels,
1239
- temb_channels=temb_channels,
1240
- eps=resnet_eps,
1241
- groups=resnet_groups,
1242
- dropout=dropout,
1243
- time_embedding_norm=resnet_time_scale_shift,
1244
- non_linearity=resnet_act_fn,
1245
- output_scale_factor=output_scale_factor,
1246
- pre_norm=resnet_pre_norm,
1247
- )
1248
- )
1249
-
1250
- self.resnets = nn.ModuleList(resnets)
1251
-
1252
- if add_downsample:
1253
- self.downsamplers = nn.ModuleList(
1254
- [
1255
- Downsample2D(
1256
- out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
1257
- )
1258
- ]
1259
- )
1260
- else:
1261
- self.downsamplers = None
1262
-
1263
- self.gradient_checkpointing = False
1264
-
1265
- def forward(
1266
- self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, *args, **kwargs
1267
- ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]:
1268
- if len(args) > 0 or kwargs.get("scale", None) is not None:
1269
- deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
1270
- deprecate("scale", "1.0.0", deprecation_message)
1271
-
1272
- output_states = ()
1273
-
1274
- for resnet in self.resnets:
1275
- if self.training and self.gradient_checkpointing:
1276
-
1277
- def create_custom_forward(module):
1278
- def custom_forward(*inputs):
1279
- return module(*inputs)
1280
-
1281
- return custom_forward
1282
-
1283
- if is_torch_version(">=", "1.11.0"):
1284
- hidden_states = torch.utils.checkpoint.checkpoint(
1285
- create_custom_forward(resnet), hidden_states, temb, use_reentrant=False
1286
- )
1287
- else:
1288
- hidden_states = torch.utils.checkpoint.checkpoint(
1289
- create_custom_forward(resnet), hidden_states, temb
1290
- )
1291
- else:
1292
- hidden_states = resnet(hidden_states, temb)
1293
-
1294
- output_states = output_states + (hidden_states,)
1295
-
1296
- if self.downsamplers is not None:
1297
- for downsampler in self.downsamplers:
1298
- hidden_states = downsampler(hidden_states)
1299
-
1300
- output_states = output_states + (hidden_states,)
1301
-
1302
- return hidden_states, output_states
1303
-
1304
-
1305
- class UpBlock2D(nn.Module):
1306
- def __init__(
1307
- self,
1308
- in_channels: int,
1309
- prev_output_channel: int,
1310
- out_channels: int,
1311
- temb_channels: int,
1312
- resolution_idx: Optional[int] = None,
1313
- dropout: float = 0.0,
1314
- num_layers: int = 1,
1315
- resnet_eps: float = 1e-6,
1316
- resnet_time_scale_shift: str = "default",
1317
- resnet_act_fn: str = "swish",
1318
- resnet_groups: int = 32,
1319
- resnet_pre_norm: bool = True,
1320
- output_scale_factor: float = 1.0,
1321
- add_upsample: bool = True,
1322
- ):
1323
- super().__init__()
1324
- resnets = []
1325
-
1326
- for i in range(num_layers):
1327
- res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
1328
- resnet_in_channels = prev_output_channel if i == 0 else out_channels
1329
-
1330
- resnets.append(
1331
- ResnetBlock2D(
1332
- in_channels=resnet_in_channels + res_skip_channels,
1333
- out_channels=out_channels,
1334
- temb_channels=temb_channels,
1335
- eps=resnet_eps,
1336
- groups=resnet_groups,
1337
- dropout=dropout,
1338
- time_embedding_norm=resnet_time_scale_shift,
1339
- non_linearity=resnet_act_fn,
1340
- output_scale_factor=output_scale_factor,
1341
- pre_norm=resnet_pre_norm,
1342
- )
1343
- )
1344
-
1345
- self.resnets = nn.ModuleList(resnets)
1346
-
1347
- if add_upsample:
1348
- self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)])
1349
- else:
1350
- self.upsamplers = None
1351
-
1352
- self.gradient_checkpointing = False
1353
- self.resolution_idx = resolution_idx
1354
-
1355
- def forward(
1356
- self,
1357
- hidden_states: torch.FloatTensor,
1358
- res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
1359
- temb: Optional[torch.FloatTensor] = None,
1360
- upsample_size: Optional[int] = None,
1361
- *args,
1362
- **kwargs,
1363
- ) -> torch.FloatTensor:
1364
- if len(args) > 0 or kwargs.get("scale", None) is not None:
1365
- deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
1366
- deprecate("scale", "1.0.0", deprecation_message)
1367
-
1368
- is_freeu_enabled = (
1369
- getattr(self, "s1", None)
1370
- and getattr(self, "s2", None)
1371
- and getattr(self, "b1", None)
1372
- and getattr(self, "b2", None)
1373
- )
1374
-
1375
- for resnet in self.resnets:
1376
- # pop res hidden states
1377
- res_hidden_states = res_hidden_states_tuple[-1]
1378
- res_hidden_states_tuple = res_hidden_states_tuple[:-1]
1379
-
1380
- # FreeU: Only operate on the first two stages
1381
- if is_freeu_enabled:
1382
- hidden_states, res_hidden_states = apply_freeu(
1383
- self.resolution_idx,
1384
- hidden_states,
1385
- res_hidden_states,
1386
- s1=self.s1,
1387
- s2=self.s2,
1388
- b1=self.b1,
1389
- b2=self.b2,
1390
- )
1391
-
1392
- hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
1393
-
1394
- if self.training and self.gradient_checkpointing:
1395
-
1396
- def create_custom_forward(module):
1397
- def custom_forward(*inputs):
1398
- return module(*inputs)
1399
-
1400
- return custom_forward
1401
-
1402
- if is_torch_version(">=", "1.11.0"):
1403
- hidden_states = torch.utils.checkpoint.checkpoint(
1404
- create_custom_forward(resnet), hidden_states, temb, use_reentrant=False
1405
- )
1406
- else:
1407
- hidden_states = torch.utils.checkpoint.checkpoint(
1408
- create_custom_forward(resnet), hidden_states, temb
1409
- )
1410
- else:
1411
- hidden_states = resnet(hidden_states, temb)
1412
-
1413
- if self.upsamplers is not None:
1414
- for upsampler in self.upsamplers:
1415
- hidden_states = upsampler(hidden_states, upsample_size)
1416
-
1417
- return hidden_states
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
module/unet/unet_2d_extractKV_res.py DELETED
@@ -1,1589 +0,0 @@
1
- # Copy from diffusers.models.unets.unet_2d_condition.py
2
-
3
- # Copyright 2024 The HuggingFace Team. All rights reserved.
4
- #
5
- # Licensed under the Apache License, Version 2.0 (the "License");
6
- # you may not use this file except in compliance with the License.
7
- # You may obtain a copy of the License at
8
- #
9
- # http://www.apache.org/licenses/LICENSE-2.0
10
- #
11
- # Unless required by applicable law or agreed to in writing, software
12
- # distributed under the License is distributed on an "AS IS" BASIS,
13
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- # See the License for the specific language governing permissions and
15
- # limitations under the License.
16
- from dataclasses import dataclass
17
- from typing import Any, Dict, List, Optional, Tuple, Union
18
-
19
- import torch
20
- import torch.nn as nn
21
- import torch.utils.checkpoint
22
-
23
- from diffusers.configuration_utils import ConfigMixin, register_to_config
24
- from diffusers.loaders import PeftAdapterMixin, UNet2DConditionLoadersMixin
25
- from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, logging, scale_lora_layers, unscale_lora_layers
26
- from diffusers.models.activations import get_activation
27
- from diffusers.models.attention_processor import (
28
- ADDED_KV_ATTENTION_PROCESSORS,
29
- CROSS_ATTENTION_PROCESSORS,
30
- Attention,
31
- AttentionProcessor,
32
- AttnAddedKVProcessor,
33
- AttnProcessor,
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_condition import UNet2DConditionModel
49
- from .unet_2d_extractKV_blocks import (
50
- get_down_block,
51
- get_mid_block,
52
- get_up_block,
53
- )
54
-
55
-
56
- logger = logging.get_logger(__name__) # pylint: disable=invalid-name
57
-
58
-
59
- @dataclass
60
- class ExtractKVUNet2DConditionOutput(BaseOutput):
61
- """
62
- The output of [`UNet2DConditionModel`].
63
-
64
- Args:
65
- sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
66
- The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.
67
- """
68
-
69
- sample: torch.FloatTensor = None
70
- cached_kvs: Dict[str, Any] = None
71
- down_block_res_samples: Tuple[torch.Tensor] = None
72
- mid_block_res_sample: torch.Tensor = None
73
-
74
-
75
- def zero_module(module):
76
- for p in module.parameters():
77
- nn.init.zeros_(p)
78
- return module
79
-
80
-
81
- class ControlNetConditioningEmbedding(nn.Module):
82
- """
83
- Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN
84
- [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized
85
- training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the
86
- convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides
87
- (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
88
- model) to encode image-space conditions ... into feature maps ..."
89
- """
90
-
91
- def __init__(
92
- self,
93
- conditioning_embedding_channels: int,
94
- conditioning_channels: int = 3,
95
- block_out_channels: Tuple[int, ...] = (16, 32, 96, 256),
96
- ):
97
- super().__init__()
98
-
99
- self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
100
-
101
- self.blocks = nn.ModuleList([])
102
-
103
- for i in range(len(block_out_channels) - 1):
104
- channel_in = block_out_channels[i]
105
- channel_out = block_out_channels[i + 1]
106
- self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
107
- self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2))
108
-
109
- self.conv_out = zero_module(
110
- nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
111
- )
112
-
113
- def forward(self, conditioning):
114
- embedding = self.conv_in(conditioning)
115
- embedding = F.silu(embedding)
116
-
117
- for block in self.blocks:
118
- embedding = block(embedding)
119
- embedding = F.silu(embedding)
120
-
121
- embedding = self.conv_out(embedding)
122
-
123
- return embedding
124
-
125
-
126
- class ExtractKVUNet2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin, PeftAdapterMixin):
127
- r"""
128
- A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample
129
- shaped output.
130
-
131
- This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
132
- for all models (such as downloading or saving).
133
-
134
- Parameters:
135
- sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
136
- Height and width of input/output sample.
137
- in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample.
138
- out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.
139
- center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
140
- flip_sin_to_cos (`bool`, *optional*, defaults to `True`):
141
- Whether to flip the sin to cos in the time embedding.
142
- freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
143
- down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
144
- The tuple of downsample blocks to use.
145
- mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
146
- Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or
147
- `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped.
148
- up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`):
149
- The tuple of upsample blocks to use.
150
- only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):
151
- Whether to include self-attention in the basic transformer blocks, see
152
- [`~models.attention.BasicTransformerBlock`].
153
- block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
154
- The tuple of output channels for each block.
155
- layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
156
- downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
157
- mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
158
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
159
- act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
160
- norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
161
- If `None`, normalization and activation layers is skipped in post-processing.
162
- norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
163
- cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):
164
- The dimension of the cross attention features.
165
- transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):
166
- The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
167
- [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
168
- [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
169
- reverse_transformer_layers_per_block : (`Tuple[Tuple]`, *optional*, defaults to None):
170
- The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`], in the upsampling
171
- blocks of the U-Net. Only relevant if `transformer_layers_per_block` is of type `Tuple[Tuple]` and for
172
- [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
173
- [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
174
- encoder_hid_dim (`int`, *optional*, defaults to None):
175
- If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
176
- dimension to `cross_attention_dim`.
177
- encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
178
- If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
179
- embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
180
- attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
181
- num_attention_heads (`int`, *optional*):
182
- The number of attention heads. If not defined, defaults to `attention_head_dim`
183
- resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
184
- for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
185
- class_embed_type (`str`, *optional*, defaults to `None`):
186
- The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
187
- `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
188
- addition_embed_type (`str`, *optional*, defaults to `None`):
189
- Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
190
- "text". "text" will use the `TextTimeEmbedding` layer.
191
- addition_time_embed_dim: (`int`, *optional*, defaults to `None`):
192
- Dimension for the timestep embeddings.
193
- num_class_embeds (`int`, *optional*, defaults to `None`):
194
- Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
195
- class conditioning with `class_embed_type` equal to `None`.
196
- time_embedding_type (`str`, *optional*, defaults to `positional`):
197
- The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.
198
- time_embedding_dim (`int`, *optional*, defaults to `None`):
199
- An optional override for the dimension of the projected time embedding.
200
- time_embedding_act_fn (`str`, *optional*, defaults to `None`):
201
- Optional activation function to use only once on the time embeddings before they are passed to the rest of
202
- the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`.
203
- timestep_post_act (`str`, *optional*, defaults to `None`):
204
- The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.
205
- time_cond_proj_dim (`int`, *optional*, defaults to `None`):
206
- The dimension of `cond_proj` layer in the timestep embedding.
207
- conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer.
208
- conv_out_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_out` layer.
209
- projection_class_embeddings_input_dim (`int`, *optional*): The dimension of the `class_labels` input when
210
- `class_embed_type="projection"`. Required when `class_embed_type="projection"`.
211
- class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time
212
- embeddings with the class embeddings.
213
- mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`):
214
- Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If
215
- `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the
216
- `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False`
217
- otherwise.
218
- """
219
-
220
- _supports_gradient_checkpointing = True
221
- _no_split_modules = ["BasicTransformerBlock", "ResnetBlock2D", "CrossAttnUpBlock2D"]
222
-
223
- @register_to_config
224
- def __init__(
225
- self,
226
- sample_size: Optional[int] = None,
227
- in_channels: int = 4,
228
- out_channels: int = 4,
229
- conditioning_channels: int = 3,
230
- center_input_sample: bool = False,
231
- flip_sin_to_cos: bool = True,
232
- freq_shift: int = 0,
233
- down_block_types: Tuple[str] = (
234
- "CrossAttnDownBlock2D",
235
- "CrossAttnDownBlock2D",
236
- "CrossAttnDownBlock2D",
237
- "DownBlock2D",
238
- ),
239
- mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
240
- up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
241
- only_cross_attention: Union[bool, Tuple[bool]] = False,
242
- block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
243
- layers_per_block: Union[int, Tuple[int]] = 2,
244
- downsample_padding: int = 1,
245
- mid_block_scale_factor: float = 1,
246
- dropout: float = 0.0,
247
- act_fn: str = "silu",
248
- norm_num_groups: Optional[int] = 32,
249
- norm_eps: float = 1e-5,
250
- cross_attention_dim: Union[int, Tuple[int]] = 1280,
251
- transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
252
- reverse_transformer_layers_per_block: Optional[Tuple[Tuple[int]]] = None,
253
- encoder_hid_dim: Optional[int] = None,
254
- encoder_hid_dim_type: Optional[str] = None,
255
- attention_head_dim: Union[int, Tuple[int]] = 8,
256
- num_attention_heads: Optional[Union[int, Tuple[int]]] = None,
257
- dual_cross_attention: bool = False,
258
- use_linear_projection: bool = False,
259
- class_embed_type: Optional[str] = None,
260
- addition_embed_type: Optional[str] = None,
261
- addition_time_embed_dim: Optional[int] = None,
262
- num_class_embeds: Optional[int] = None,
263
- upcast_attention: bool = False,
264
- resnet_time_scale_shift: str = "default",
265
- resnet_skip_time_act: bool = False,
266
- resnet_out_scale_factor: float = 1.0,
267
- time_embedding_type: str = "positional",
268
- time_embedding_dim: Optional[int] = None,
269
- time_embedding_act_fn: Optional[str] = None,
270
- timestep_post_act: Optional[str] = None,
271
- time_cond_proj_dim: Optional[int] = None,
272
- conv_in_kernel: int = 3,
273
- conv_out_kernel: int = 3,
274
- projection_class_embeddings_input_dim: Optional[int] = None,
275
- controlnet_conditioning_channel_order: str = "rgb",
276
- conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
277
- attention_type: str = "default",
278
- class_embeddings_concat: bool = False,
279
- mid_block_only_cross_attention: Optional[bool] = None,
280
- cross_attention_norm: Optional[str] = None,
281
- addition_embed_type_num_heads: int = 64,
282
- extract_self_attention_kv: bool = True,
283
- extract_cross_attention_kv: bool = True,
284
- ):
285
- super().__init__()
286
-
287
- self.sample_size = sample_size
288
-
289
- if num_attention_heads is not None:
290
- raise ValueError(
291
- "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."
292
- )
293
-
294
- # If `num_attention_heads` is not defined (which is the case for most models)
295
- # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
296
- # The reason for this behavior is to correct for incorrectly named variables that were introduced
297
- # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
298
- # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
299
- # which is why we correct for the naming here.
300
- num_attention_heads = num_attention_heads or attention_head_dim
301
-
302
- # Check inputs
303
- self._check_config(
304
- down_block_types=down_block_types,
305
- up_block_types=up_block_types,
306
- only_cross_attention=only_cross_attention,
307
- block_out_channels=block_out_channels,
308
- layers_per_block=layers_per_block,
309
- cross_attention_dim=cross_attention_dim,
310
- transformer_layers_per_block=transformer_layers_per_block,
311
- reverse_transformer_layers_per_block=reverse_transformer_layers_per_block,
312
- attention_head_dim=attention_head_dim,
313
- num_attention_heads=num_attention_heads,
314
- )
315
-
316
- # input
317
- conv_in_padding = (conv_in_kernel - 1) // 2
318
- self.conv_in = nn.Conv2d(
319
- in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
320
- )
321
-
322
- # time
323
- time_embed_dim, timestep_input_dim = self._set_time_proj(
324
- time_embedding_type,
325
- block_out_channels=block_out_channels,
326
- flip_sin_to_cos=flip_sin_to_cos,
327
- freq_shift=freq_shift,
328
- time_embedding_dim=time_embedding_dim,
329
- )
330
-
331
- self.time_embedding = TimestepEmbedding(
332
- timestep_input_dim,
333
- time_embed_dim,
334
- act_fn=act_fn,
335
- post_act_fn=timestep_post_act,
336
- cond_proj_dim=time_cond_proj_dim,
337
- )
338
-
339
- self._set_encoder_hid_proj(
340
- encoder_hid_dim_type,
341
- cross_attention_dim=cross_attention_dim,
342
- encoder_hid_dim=encoder_hid_dim,
343
- )
344
-
345
- # class embedding
346
- self._set_class_embedding(
347
- class_embed_type,
348
- act_fn=act_fn,
349
- num_class_embeds=num_class_embeds,
350
- projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,
351
- time_embed_dim=time_embed_dim,
352
- timestep_input_dim=timestep_input_dim,
353
- )
354
-
355
- self._set_add_embedding(
356
- addition_embed_type,
357
- addition_embed_type_num_heads=addition_embed_type_num_heads,
358
- addition_time_embed_dim=addition_time_embed_dim,
359
- cross_attention_dim=cross_attention_dim,
360
- encoder_hid_dim=encoder_hid_dim,
361
- flip_sin_to_cos=flip_sin_to_cos,
362
- freq_shift=freq_shift,
363
- projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,
364
- time_embed_dim=time_embed_dim,
365
- )
366
-
367
- if time_embedding_act_fn is None:
368
- self.time_embed_act = None
369
- else:
370
- self.time_embed_act = get_activation(time_embedding_act_fn)
371
-
372
- # control net conditioning embedding
373
- self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
374
- conditioning_embedding_channels=block_out_channels[0],
375
- block_out_channels=conditioning_embedding_out_channels,
376
- conditioning_channels=conditioning_channels,
377
- )
378
-
379
- self.down_blocks = nn.ModuleList([])
380
- self.controlnet_down_blocks = nn.ModuleList([])
381
- self.up_blocks = nn.ModuleList([])
382
- # self.controlnet_up_blocks = nn.ModuleList([])
383
-
384
- if isinstance(only_cross_attention, bool):
385
- if mid_block_only_cross_attention is None:
386
- mid_block_only_cross_attention = only_cross_attention
387
-
388
- only_cross_attention = [only_cross_attention] * len(down_block_types)
389
-
390
- if mid_block_only_cross_attention is None:
391
- mid_block_only_cross_attention = False
392
-
393
- if isinstance(num_attention_heads, int):
394
- num_attention_heads = (num_attention_heads,) * len(down_block_types)
395
-
396
- if isinstance(attention_head_dim, int):
397
- attention_head_dim = (attention_head_dim,) * len(down_block_types)
398
-
399
- if isinstance(cross_attention_dim, int):
400
- cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
401
-
402
- if isinstance(layers_per_block, int):
403
- layers_per_block = [layers_per_block] * len(down_block_types)
404
-
405
- if isinstance(transformer_layers_per_block, int):
406
- transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
407
-
408
- if class_embeddings_concat:
409
- # The time embeddings are concatenated with the class embeddings. The dimension of the
410
- # time embeddings passed to the down, middle, and up blocks is twice the dimension of the
411
- # regular time embeddings
412
- blocks_time_embed_dim = time_embed_dim * 2
413
- else:
414
- blocks_time_embed_dim = time_embed_dim
415
-
416
- # down
417
- output_channel = block_out_channels[0]
418
-
419
- controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
420
- controlnet_block = zero_module(controlnet_block)
421
- self.controlnet_down_blocks.append(controlnet_block)
422
-
423
- for i, down_block_type in enumerate(down_block_types):
424
- input_channel = output_channel
425
- output_channel = block_out_channels[i]
426
- is_final_block = i == len(block_out_channels) - 1
427
-
428
- down_block = get_down_block(
429
- down_block_type,
430
- num_layers=layers_per_block[i],
431
- transformer_layers_per_block=transformer_layers_per_block[i],
432
- in_channels=input_channel,
433
- out_channels=output_channel,
434
- temb_channels=blocks_time_embed_dim,
435
- add_downsample=not is_final_block,
436
- resnet_eps=norm_eps,
437
- resnet_act_fn=act_fn,
438
- resnet_groups=norm_num_groups,
439
- cross_attention_dim=cross_attention_dim[i],
440
- num_attention_heads=num_attention_heads[i],
441
- downsample_padding=downsample_padding,
442
- dual_cross_attention=dual_cross_attention,
443
- use_linear_projection=use_linear_projection,
444
- only_cross_attention=only_cross_attention[i],
445
- upcast_attention=upcast_attention,
446
- resnet_time_scale_shift=resnet_time_scale_shift,
447
- attention_type=attention_type,
448
- resnet_skip_time_act=resnet_skip_time_act,
449
- resnet_out_scale_factor=resnet_out_scale_factor,
450
- cross_attention_norm=cross_attention_norm,
451
- attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
452
- dropout=dropout,
453
- extract_self_attention_kv=extract_self_attention_kv,
454
- extract_cross_attention_kv=extract_cross_attention_kv,
455
- )
456
- self.down_blocks.append(down_block)
457
-
458
- for _ in range(layers_per_block):
459
- controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
460
- controlnet_block = zero_module(controlnet_block)
461
- self.controlnet_down_blocks.append(controlnet_block)
462
-
463
- if not is_final_block:
464
- controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
465
- controlnet_block = zero_module(controlnet_block)
466
- self.controlnet_down_blocks.append(controlnet_block)
467
-
468
- # mid
469
- mid_block_channel = block_out_channels[-1]
470
-
471
- controlnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)
472
- controlnet_block = zero_module(controlnet_block)
473
- self.controlnet_mid_block = controlnet_block
474
-
475
- self.mid_block = get_mid_block(
476
- mid_block_type,
477
- temb_channels=blocks_time_embed_dim,
478
- in_channels=block_out_channels[-1],
479
- resnet_eps=norm_eps,
480
- resnet_act_fn=act_fn,
481
- resnet_groups=norm_num_groups,
482
- output_scale_factor=mid_block_scale_factor,
483
- transformer_layers_per_block=transformer_layers_per_block[-1],
484
- num_attention_heads=num_attention_heads[-1],
485
- cross_attention_dim=cross_attention_dim[-1],
486
- dual_cross_attention=dual_cross_attention,
487
- use_linear_projection=use_linear_projection,
488
- mid_block_only_cross_attention=mid_block_only_cross_attention,
489
- upcast_attention=upcast_attention,
490
- resnet_time_scale_shift=resnet_time_scale_shift,
491
- attention_type=attention_type,
492
- resnet_skip_time_act=resnet_skip_time_act,
493
- cross_attention_norm=cross_attention_norm,
494
- attention_head_dim=attention_head_dim[-1],
495
- dropout=dropout,
496
- extract_self_attention_kv=extract_self_attention_kv,
497
- extract_cross_attention_kv=extract_cross_attention_kv,
498
- )
499
-
500
- # count how many layers upsample the images
501
- self.num_upsamplers = 0
502
-
503
- # up
504
- reversed_block_out_channels = list(reversed(block_out_channels))
505
- reversed_num_attention_heads = list(reversed(num_attention_heads))
506
- reversed_layers_per_block = list(reversed(layers_per_block))
507
- reversed_cross_attention_dim = list(reversed(cross_attention_dim))
508
- reversed_transformer_layers_per_block = (
509
- list(reversed(transformer_layers_per_block))
510
- if reverse_transformer_layers_per_block is None
511
- else reverse_transformer_layers_per_block
512
- )
513
- only_cross_attention = list(reversed(only_cross_attention))
514
-
515
- output_channel = reversed_block_out_channels[0]
516
- for i, up_block_type in enumerate(up_block_types):
517
- is_final_block = i == len(block_out_channels) - 1
518
-
519
- prev_output_channel = output_channel
520
- output_channel = reversed_block_out_channels[i]
521
- input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
522
-
523
- # add upsample block for all BUT final layer
524
- if not is_final_block:
525
- add_upsample = True
526
- self.num_upsamplers += 1
527
- else:
528
- add_upsample = False
529
-
530
- up_block = get_up_block(
531
- up_block_type,
532
- num_layers=reversed_layers_per_block[i] + 1,
533
- transformer_layers_per_block=reversed_transformer_layers_per_block[i],
534
- in_channels=input_channel,
535
- out_channels=output_channel,
536
- prev_output_channel=prev_output_channel,
537
- temb_channels=blocks_time_embed_dim,
538
- add_upsample=add_upsample,
539
- resnet_eps=norm_eps,
540
- resnet_act_fn=act_fn,
541
- resolution_idx=i,
542
- resnet_groups=norm_num_groups,
543
- cross_attention_dim=reversed_cross_attention_dim[i],
544
- num_attention_heads=reversed_num_attention_heads[i],
545
- dual_cross_attention=dual_cross_attention,
546
- use_linear_projection=use_linear_projection,
547
- only_cross_attention=only_cross_attention[i],
548
- upcast_attention=upcast_attention,
549
- resnet_time_scale_shift=resnet_time_scale_shift,
550
- attention_type=attention_type,
551
- resnet_skip_time_act=resnet_skip_time_act,
552
- resnet_out_scale_factor=resnet_out_scale_factor,
553
- cross_attention_norm=cross_attention_norm,
554
- attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
555
- dropout=dropout,
556
- extract_self_attention_kv=extract_self_attention_kv,
557
- extract_cross_attention_kv=extract_cross_attention_kv,
558
- )
559
- self.up_blocks.append(up_block)
560
- prev_output_channel = output_channel
561
-
562
- # for _ in range(layers_per_block):
563
- # controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
564
- # controlnet_block = zero_module(controlnet_block)
565
- # self.controlnet_up_blocks.append(controlnet_block)
566
-
567
- # if not is_final_block:
568
- # controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
569
- # controlnet_block = zero_module(controlnet_block)
570
- # self.controlnet_up_blocks.append(controlnet_block)
571
-
572
- # out
573
- if norm_num_groups is not None:
574
- self.conv_norm_out = nn.GroupNorm(
575
- num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
576
- )
577
-
578
- self.conv_act = get_activation(act_fn)
579
-
580
- else:
581
- self.conv_norm_out = None
582
- self.conv_act = None
583
-
584
- conv_out_padding = (conv_out_kernel - 1) // 2
585
- self.conv_out = nn.Conv2d(
586
- block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding
587
- )
588
-
589
- self._set_pos_net_if_use_gligen(attention_type=attention_type, cross_attention_dim=cross_attention_dim)
590
-
591
- @classmethod
592
- def from_unet(
593
- cls,
594
- unet: UNet2DConditionModel,
595
- controlnet_conditioning_channel_order: str = "rgb",
596
- conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
597
- load_weights_from_unet: bool = True,
598
- conditioning_channels: int = 3,
599
- extract_self_attention_kv: bool = True,
600
- extract_cross_attention_kv: bool = True,
601
- ):
602
- r"""
603
- Instantiate a [`ExtractKVUNet2DConditionModel`] from [`UNet2DConditionModel`].
604
-
605
- Parameters:
606
- unet (`UNet2DConditionModel`):
607
- The UNet model weights to copy to the [`ControlNetModel`]. All configuration options are also copied
608
- where applicable.
609
- """
610
- transformer_layers_per_block = (
611
- unet.config.transformer_layers_per_block if "transformer_layers_per_block" in unet.config else 1
612
- )
613
- encoder_hid_dim = unet.config.encoder_hid_dim if "encoder_hid_dim" in unet.config else None
614
- encoder_hid_dim_type = unet.config.encoder_hid_dim_type if "encoder_hid_dim_type" in unet.config else None
615
- addition_embed_type = unet.config.addition_embed_type if "addition_embed_type" in unet.config else None
616
- addition_time_embed_dim = (
617
- unet.config.addition_time_embed_dim if "addition_time_embed_dim" in unet.config else None
618
- )
619
- down_block_types = (
620
- 'DownBlock2D', 'ExtractKVCrossAttnDownBlock2D', 'ExtractKVCrossAttnDownBlock2D'
621
- )
622
- mid_block_type = 'ExtractKVUNetMidBlock2DCrossAttn'
623
- up_block_types = (
624
- 'ExtractKVCrossAttnUpBlock2D', 'ExtractKVCrossAttnUpBlock2D', 'UpBlock2D'
625
- )
626
-
627
- refnet = cls(
628
- down_block_types=down_block_types,
629
- up_block_types=up_block_types,
630
- mid_block_type=mid_block_type,
631
- encoder_hid_dim=encoder_hid_dim,
632
- encoder_hid_dim_type=encoder_hid_dim_type,
633
- addition_embed_type=addition_embed_type,
634
- addition_time_embed_dim=addition_time_embed_dim,
635
- transformer_layers_per_block=transformer_layers_per_block,
636
- in_channels=unet.config.in_channels,
637
- flip_sin_to_cos=unet.config.flip_sin_to_cos,
638
- freq_shift=unet.config.freq_shift,
639
- only_cross_attention=unet.config.only_cross_attention,
640
- block_out_channels=unet.config.block_out_channels,
641
- layers_per_block=unet.config.layers_per_block,
642
- downsample_padding=unet.config.downsample_padding,
643
- mid_block_scale_factor=unet.config.mid_block_scale_factor,
644
- act_fn=unet.config.act_fn,
645
- norm_num_groups=unet.config.norm_num_groups,
646
- norm_eps=unet.config.norm_eps,
647
- cross_attention_dim=unet.config.cross_attention_dim,
648
- attention_head_dim=unet.config.attention_head_dim,
649
- num_attention_heads=unet.config.num_attention_heads,
650
- use_linear_projection=unet.config.use_linear_projection,
651
- class_embed_type=unet.config.class_embed_type,
652
- num_class_embeds=unet.config.num_class_embeds,
653
- upcast_attention=unet.config.upcast_attention,
654
- resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
655
- projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
656
- mid_block_type=unet.config.mid_block_type,
657
- controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
658
- conditioning_embedding_out_channels=conditioning_embedding_out_channels,
659
- conditioning_channels=conditioning_channels,
660
- extract_self_attention_kv=extract_self_attention_kv,
661
- extract_cross_attention_kv=extract_cross_attention_kv,
662
- )
663
-
664
- if load_weights_from_unet:
665
- def verify_load(missing_keys, unexpected_keys):
666
- if len(unexpected_keys) > 0:
667
- raise RuntimeError(f"Found unexpected keys in state dict while loading the encoder:\n{unexpected_keys}")
668
-
669
- filtered_missing = [key for key in missing_keys if not "extract_kv" in key]
670
- if len(filtered_missing) > 0:
671
- raise RuntimeError(f"Missing keys in state dict while loading the encoder:\n{filtered_missing}")
672
- refnet.conv_in.load_state_dict(unet.conv_in.state_dict())
673
- refnet.time_proj.load_state_dict(unet.time_proj.state_dict())
674
- refnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())
675
-
676
- if refnet.class_embedding:
677
- refnet.class_embedding.load_state_dict(unet.class_embedding.state_dict())
678
-
679
- if hasattr(refnet, "add_embedding"):
680
- refnet.add_embedding.load_state_dict(unet.add_embedding.state_dict())
681
-
682
- missing_keys, unexpected_keys = refnet.down_blocks.load_state_dict(unet.down_blocks.state_dict(), strict=False)
683
- verify_load(missing_keys, unexpected_keys)
684
- missing_keys, unexpected_keys = refnet.mid_block.load_state_dict(unet.mid_block.state_dict(), strict=False)
685
- verify_load(missing_keys, unexpected_keys)
686
- missing_keys, unexpected_keys = refnet.up_blocks.load_state_dict(unet.up_blocks.state_dict(), strict=False)
687
- verify_load(missing_keys, unexpected_keys)
688
-
689
- return refnet
690
-
691
- def _check_config(
692
- self,
693
- down_block_types: Tuple[str],
694
- up_block_types: Tuple[str],
695
- only_cross_attention: Union[bool, Tuple[bool]],
696
- block_out_channels: Tuple[int],
697
- layers_per_block: Union[int, Tuple[int]],
698
- cross_attention_dim: Union[int, Tuple[int]],
699
- transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple[int]]],
700
- reverse_transformer_layers_per_block: bool,
701
- attention_head_dim: int,
702
- num_attention_heads: Optional[Union[int, Tuple[int]]],
703
- ):
704
- assert "ExtractKVCrossAttnDownBlock2D" in down_block_types, "ExtractKVUNet must have ExtractKVCrossAttnDownBlock2D."
705
- assert "ExtractKVCrossAttnUpBlock2D" in up_block_types, "ExtractKVUNet must have ExtractKVCrossAttnUpBlock2D."
706
-
707
- if len(down_block_types) != len(up_block_types):
708
- raise ValueError(
709
- 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}."
710
- )
711
-
712
- if len(block_out_channels) != len(down_block_types):
713
- raise ValueError(
714
- 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}."
715
- )
716
-
717
- if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
718
- raise ValueError(
719
- 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}."
720
- )
721
-
722
- if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
723
- raise ValueError(
724
- 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}."
725
- )
726
-
727
- if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
728
- raise ValueError(
729
- 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}."
730
- )
731
-
732
- if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types):
733
- raise ValueError(
734
- 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}."
735
- )
736
-
737
- if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types):
738
- raise ValueError(
739
- 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}."
740
- )
741
- if isinstance(transformer_layers_per_block, list) and reverse_transformer_layers_per_block is None:
742
- for layer_number_per_block in transformer_layers_per_block:
743
- if isinstance(layer_number_per_block, list):
744
- raise ValueError("Must provide 'reverse_transformer_layers_per_block` if using asymmetrical UNet.")
745
-
746
- def _set_time_proj(
747
- self,
748
- time_embedding_type: str,
749
- block_out_channels: int,
750
- flip_sin_to_cos: bool,
751
- freq_shift: float,
752
- time_embedding_dim: int,
753
- ) -> Tuple[int, int]:
754
- if time_embedding_type == "fourier":
755
- time_embed_dim = time_embedding_dim or block_out_channels[0] * 2
756
- if time_embed_dim % 2 != 0:
757
- raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.")
758
- self.time_proj = GaussianFourierProjection(
759
- time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos
760
- )
761
- timestep_input_dim = time_embed_dim
762
- elif time_embedding_type == "positional":
763
- time_embed_dim = time_embedding_dim or block_out_channels[0] * 4
764
-
765
- self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
766
- timestep_input_dim = block_out_channels[0]
767
- else:
768
- raise ValueError(
769
- f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`."
770
- )
771
-
772
- return time_embed_dim, timestep_input_dim
773
-
774
- def _set_encoder_hid_proj(
775
- self,
776
- encoder_hid_dim_type: Optional[str],
777
- cross_attention_dim: Union[int, Tuple[int]],
778
- encoder_hid_dim: Optional[int],
779
- ):
780
- if encoder_hid_dim_type is None and encoder_hid_dim is not None:
781
- encoder_hid_dim_type = "text_proj"
782
- self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
783
- logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.")
784
-
785
- if encoder_hid_dim is None and encoder_hid_dim_type is not None:
786
- raise ValueError(
787
- f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
788
- )
789
-
790
- if encoder_hid_dim_type == "text_proj":
791
- self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
792
- elif encoder_hid_dim_type == "text_image_proj":
793
- # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
794
- # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
795
- # case when `addition_embed_type == "text_image_proj"` (Kandinsky 2.1)`
796
- self.encoder_hid_proj = TextImageProjection(
797
- text_embed_dim=encoder_hid_dim,
798
- image_embed_dim=cross_attention_dim,
799
- cross_attention_dim=cross_attention_dim,
800
- )
801
- elif encoder_hid_dim_type == "image_proj":
802
- # Kandinsky 2.2
803
- self.encoder_hid_proj = ImageProjection(
804
- image_embed_dim=encoder_hid_dim,
805
- cross_attention_dim=cross_attention_dim,
806
- )
807
- elif encoder_hid_dim_type is not None:
808
- raise ValueError(
809
- f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'."
810
- )
811
- else:
812
- self.encoder_hid_proj = None
813
-
814
- def _set_class_embedding(
815
- self,
816
- class_embed_type: Optional[str],
817
- act_fn: str,
818
- num_class_embeds: Optional[int],
819
- projection_class_embeddings_input_dim: Optional[int],
820
- time_embed_dim: int,
821
- timestep_input_dim: int,
822
- ):
823
- if class_embed_type is None and num_class_embeds is not None:
824
- self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
825
- elif class_embed_type == "timestep":
826
- self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn)
827
- elif class_embed_type == "identity":
828
- self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
829
- elif class_embed_type == "projection":
830
- if projection_class_embeddings_input_dim is None:
831
- raise ValueError(
832
- "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
833
- )
834
- # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
835
- # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
836
- # 2. it projects from an arbitrary input dimension.
837
- #
838
- # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
839
- # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
840
- # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
841
- self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
842
- elif class_embed_type == "simple_projection":
843
- if projection_class_embeddings_input_dim is None:
844
- raise ValueError(
845
- "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set"
846
- )
847
- self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim)
848
- else:
849
- self.class_embedding = None
850
-
851
- def _set_add_embedding(
852
- self,
853
- addition_embed_type: str,
854
- addition_embed_type_num_heads: int,
855
- addition_time_embed_dim: Optional[int],
856
- flip_sin_to_cos: bool,
857
- freq_shift: float,
858
- cross_attention_dim: Optional[int],
859
- encoder_hid_dim: Optional[int],
860
- projection_class_embeddings_input_dim: Optional[int],
861
- time_embed_dim: int,
862
- ):
863
- if addition_embed_type == "text":
864
- if encoder_hid_dim is not None:
865
- text_time_embedding_from_dim = encoder_hid_dim
866
- else:
867
- text_time_embedding_from_dim = cross_attention_dim
868
-
869
- self.add_embedding = TextTimeEmbedding(
870
- text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads
871
- )
872
- elif addition_embed_type == "text_image":
873
- # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
874
- # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
875
- # case when `addition_embed_type == "text_image"` (Kandinsky 2.1)`
876
- self.add_embedding = TextImageTimeEmbedding(
877
- text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim
878
- )
879
- elif addition_embed_type == "text_time":
880
- self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)
881
- self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
882
- elif addition_embed_type == "image":
883
- # Kandinsky 2.2
884
- self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
885
- elif addition_embed_type == "image_hint":
886
- # Kandinsky 2.2 ControlNet
887
- self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
888
- elif addition_embed_type is not None:
889
- raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.")
890
-
891
- def _set_pos_net_if_use_gligen(self, attention_type: str, cross_attention_dim: int):
892
- if attention_type in ["gated", "gated-text-image"]:
893
- positive_len = 768
894
- if isinstance(cross_attention_dim, int):
895
- positive_len = cross_attention_dim
896
- elif isinstance(cross_attention_dim, tuple) or isinstance(cross_attention_dim, list):
897
- positive_len = cross_attention_dim[0]
898
-
899
- feature_type = "text-only" if attention_type == "gated" else "text-image"
900
- self.position_net = GLIGENTextBoundingboxProjection(
901
- positive_len=positive_len, out_dim=cross_attention_dim, feature_type=feature_type
902
- )
903
-
904
- @property
905
- def attn_processors(self) -> Dict[str, AttentionProcessor]:
906
- r"""
907
- Returns:
908
- `dict` of attention processors: A dictionary containing all attention processors used in the model with
909
- indexed by its weight name.
910
- """
911
- # set recursively
912
- processors = {}
913
-
914
- def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
915
- if hasattr(module, "get_processor"):
916
- processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
917
-
918
- for sub_name, child in module.named_children():
919
- fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
920
-
921
- return processors
922
-
923
- for name, module in self.named_children():
924
- fn_recursive_add_processors(name, module, processors)
925
-
926
- return processors
927
-
928
- def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
929
- r"""
930
- Sets the attention processor to use to compute attention.
931
-
932
- Parameters:
933
- processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
934
- The instantiated processor class or a dictionary of processor classes that will be set as the processor
935
- for **all** `Attention` layers.
936
-
937
- If `processor` is a dict, the key needs to define the path to the corresponding cross attention
938
- processor. This is strongly recommended when setting trainable attention processors.
939
-
940
- """
941
- count = len(self.attn_processors.keys())
942
-
943
- if isinstance(processor, dict) and len(processor) != count:
944
- raise ValueError(
945
- f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
946
- f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
947
- )
948
-
949
- def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
950
- if hasattr(module, "set_processor"):
951
- if not isinstance(processor, dict):
952
- module.set_processor(processor)
953
- else:
954
- module.set_processor(processor.pop(f"{name}.processor"))
955
-
956
- for sub_name, child in module.named_children():
957
- fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
958
-
959
- for name, module in self.named_children():
960
- fn_recursive_attn_processor(name, module, processor)
961
-
962
- def set_default_attn_processor(self):
963
- """
964
- Disables custom attention processors and sets the default attention implementation.
965
- """
966
- if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
967
- processor = AttnAddedKVProcessor()
968
- elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
969
- processor = AttnProcessor()
970
- else:
971
- raise ValueError(
972
- f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
973
- )
974
-
975
- self.set_attn_processor(processor)
976
-
977
- def set_attention_slice(self, slice_size: Union[str, int, List[int]] = "auto"):
978
- r"""
979
- Enable sliced attention computation.
980
-
981
- When this option is enabled, the attention module splits the input tensor in slices to compute attention in
982
- several steps. This is useful for saving some memory in exchange for a small decrease in speed.
983
-
984
- Args:
985
- slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
986
- When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
987
- `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
988
- provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
989
- must be a multiple of `slice_size`.
990
- """
991
- sliceable_head_dims = []
992
-
993
- def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
994
- if hasattr(module, "set_attention_slice"):
995
- sliceable_head_dims.append(module.sliceable_head_dim)
996
-
997
- for child in module.children():
998
- fn_recursive_retrieve_sliceable_dims(child)
999
-
1000
- # retrieve number of attention layers
1001
- for module in self.children():
1002
- fn_recursive_retrieve_sliceable_dims(module)
1003
-
1004
- num_sliceable_layers = len(sliceable_head_dims)
1005
-
1006
- if slice_size == "auto":
1007
- # half the attention head size is usually a good trade-off between
1008
- # speed and memory
1009
- slice_size = [dim // 2 for dim in sliceable_head_dims]
1010
- elif slice_size == "max":
1011
- # make smallest slice possible
1012
- slice_size = num_sliceable_layers * [1]
1013
-
1014
- slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
1015
-
1016
- if len(slice_size) != len(sliceable_head_dims):
1017
- raise ValueError(
1018
- f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
1019
- f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
1020
- )
1021
-
1022
- for i in range(len(slice_size)):
1023
- size = slice_size[i]
1024
- dim = sliceable_head_dims[i]
1025
- if size is not None and size > dim:
1026
- raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
1027
-
1028
- # Recursively walk through all the children.
1029
- # Any children which exposes the set_attention_slice method
1030
- # gets the message
1031
- def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
1032
- if hasattr(module, "set_attention_slice"):
1033
- module.set_attention_slice(slice_size.pop())
1034
-
1035
- for child in module.children():
1036
- fn_recursive_set_attention_slice(child, slice_size)
1037
-
1038
- reversed_slice_size = list(reversed(slice_size))
1039
- for module in self.children():
1040
- fn_recursive_set_attention_slice(module, reversed_slice_size)
1041
-
1042
- def _set_gradient_checkpointing(self, module, value=False):
1043
- if hasattr(module, "gradient_checkpointing"):
1044
- module.gradient_checkpointing = value
1045
-
1046
- def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
1047
- r"""Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497.
1048
-
1049
- The suffixes after the scaling factors represent the stage blocks where they are being applied.
1050
-
1051
- Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that
1052
- are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
1053
-
1054
- Args:
1055
- s1 (`float`):
1056
- Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
1057
- mitigate the "oversmoothing effect" in the enhanced denoising process.
1058
- s2 (`float`):
1059
- Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
1060
- mitigate the "oversmoothing effect" in the enhanced denoising process.
1061
- b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
1062
- b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
1063
- """
1064
- for i, upsample_block in enumerate(self.up_blocks):
1065
- setattr(upsample_block, "s1", s1)
1066
- setattr(upsample_block, "s2", s2)
1067
- setattr(upsample_block, "b1", b1)
1068
- setattr(upsample_block, "b2", b2)
1069
-
1070
- def disable_freeu(self):
1071
- """Disables the FreeU mechanism."""
1072
- freeu_keys = {"s1", "s2", "b1", "b2"}
1073
- for i, upsample_block in enumerate(self.up_blocks):
1074
- for k in freeu_keys:
1075
- if hasattr(upsample_block, k) or getattr(upsample_block, k, None) is not None:
1076
- setattr(upsample_block, k, None)
1077
-
1078
- def fuse_qkv_projections(self):
1079
- """
1080
- Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
1081
- are fused. For cross-attention modules, key and value projection matrices are fused.
1082
-
1083
- <Tip warning={true}>
1084
-
1085
- This API is 🧪 experimental.
1086
-
1087
- </Tip>
1088
- """
1089
- self.original_attn_processors = None
1090
-
1091
- for _, attn_processor in self.attn_processors.items():
1092
- if "Added" in str(attn_processor.__class__.__name__):
1093
- raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
1094
-
1095
- self.original_attn_processors = self.attn_processors
1096
-
1097
- for module in self.modules():
1098
- if isinstance(module, Attention):
1099
- module.fuse_projections(fuse=True)
1100
-
1101
- def unfuse_qkv_projections(self):
1102
- """Disables the fused QKV projection if enabled.
1103
-
1104
- <Tip warning={true}>
1105
-
1106
- This API is 🧪 experimental.
1107
-
1108
- </Tip>
1109
-
1110
- """
1111
- if self.original_attn_processors is not None:
1112
- self.set_attn_processor(self.original_attn_processors)
1113
-
1114
- def unload_lora(self):
1115
- """Unloads LoRA weights."""
1116
- deprecate(
1117
- "unload_lora",
1118
- "0.28.0",
1119
- "Calling `unload_lora()` is deprecated and will be removed in a future version. Please install `peft` and then call `disable_adapters().",
1120
- )
1121
- for module in self.modules():
1122
- if hasattr(module, "set_lora_layer"):
1123
- module.set_lora_layer(None)
1124
-
1125
- def get_time_embed(
1126
- self, sample: torch.Tensor, timestep: Union[torch.Tensor, float, int]
1127
- ) -> Optional[torch.Tensor]:
1128
- timesteps = timestep
1129
- if not torch.is_tensor(timesteps):
1130
- # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
1131
- # This would be a good case for the `match` statement (Python 3.10+)
1132
- is_mps = sample.device.type == "mps"
1133
- if isinstance(timestep, float):
1134
- dtype = torch.float32 if is_mps else torch.float64
1135
- else:
1136
- dtype = torch.int32 if is_mps else torch.int64
1137
- timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
1138
- elif len(timesteps.shape) == 0:
1139
- timesteps = timesteps[None].to(sample.device)
1140
-
1141
- # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
1142
- timesteps = timesteps.expand(sample.shape[0])
1143
-
1144
- t_emb = self.time_proj(timesteps)
1145
- # `Timesteps` does not contain any weights and will always return f32 tensors
1146
- # but time_embedding might actually be running in fp16. so we need to cast here.
1147
- # there might be better ways to encapsulate this.
1148
- t_emb = t_emb.to(dtype=sample.dtype)
1149
- return t_emb
1150
-
1151
- def get_class_embed(self, sample: torch.Tensor, class_labels: Optional[torch.Tensor]) -> Optional[torch.Tensor]:
1152
- class_emb = None
1153
- if self.class_embedding is not None:
1154
- if class_labels is None:
1155
- raise ValueError("class_labels should be provided when num_class_embeds > 0")
1156
-
1157
- if self.config.class_embed_type == "timestep":
1158
- class_labels = self.time_proj(class_labels)
1159
-
1160
- # `Timesteps` does not contain any weights and will always return f32 tensors
1161
- # there might be better ways to encapsulate this.
1162
- class_labels = class_labels.to(dtype=sample.dtype)
1163
-
1164
- class_emb = self.class_embedding(class_labels).to(dtype=sample.dtype)
1165
- return class_emb
1166
-
1167
- def get_aug_embed(
1168
- self, emb: torch.Tensor, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
1169
- ) -> Optional[torch.Tensor]:
1170
- aug_emb = None
1171
- if self.config.addition_embed_type == "text":
1172
- aug_emb = self.add_embedding(encoder_hidden_states)
1173
- elif self.config.addition_embed_type == "text_image":
1174
- # Kandinsky 2.1 - style
1175
- if "image_embeds" not in added_cond_kwargs:
1176
- raise ValueError(
1177
- 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`"
1178
- )
1179
-
1180
- image_embs = added_cond_kwargs.get("image_embeds")
1181
- text_embs = added_cond_kwargs.get("text_embeds", encoder_hidden_states)
1182
- aug_emb = self.add_embedding(text_embs, image_embs)
1183
- elif self.config.addition_embed_type == "text_time":
1184
- # SDXL - style
1185
- if "text_embeds" not in added_cond_kwargs:
1186
- raise ValueError(
1187
- 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`"
1188
- )
1189
- text_embeds = added_cond_kwargs.get("text_embeds")
1190
- if "time_ids" not in added_cond_kwargs:
1191
- raise ValueError(
1192
- 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`"
1193
- )
1194
- time_ids = added_cond_kwargs.get("time_ids")
1195
- time_embeds = self.add_time_proj(time_ids.flatten())
1196
- time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
1197
- add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
1198
- add_embeds = add_embeds.to(emb.dtype)
1199
- aug_emb = self.add_embedding(add_embeds)
1200
- elif self.config.addition_embed_type == "image":
1201
- # Kandinsky 2.2 - style
1202
- if "image_embeds" not in added_cond_kwargs:
1203
- raise ValueError(
1204
- 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`"
1205
- )
1206
- image_embs = added_cond_kwargs.get("image_embeds")
1207
- aug_emb = self.add_embedding(image_embs)
1208
- elif self.config.addition_embed_type == "image_hint":
1209
- # Kandinsky 2.2 - style
1210
- if "image_embeds" not in added_cond_kwargs or "hint" not in added_cond_kwargs:
1211
- raise ValueError(
1212
- 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`"
1213
- )
1214
- image_embs = added_cond_kwargs.get("image_embeds")
1215
- hint = added_cond_kwargs.get("hint")
1216
- aug_emb = self.add_embedding(image_embs, hint)
1217
- return aug_emb
1218
-
1219
- def process_encoder_hidden_states(
1220
- self, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
1221
- ) -> torch.Tensor:
1222
- if self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_proj":
1223
- encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states)
1224
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_image_proj":
1225
- # Kandinsky 2.1 - style
1226
- if "image_embeds" not in added_cond_kwargs:
1227
- raise ValueError(
1228
- 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`"
1229
- )
1230
-
1231
- image_embeds = added_cond_kwargs.get("image_embeds")
1232
- encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states, image_embeds)
1233
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "image_proj":
1234
- # Kandinsky 2.2 - style
1235
- if "image_embeds" not in added_cond_kwargs:
1236
- raise ValueError(
1237
- 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`"
1238
- )
1239
- image_embeds = added_cond_kwargs.get("image_embeds")
1240
- encoder_hidden_states = self.encoder_hid_proj(image_embeds)
1241
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "ip_image_proj":
1242
- if "image_embeds" not in added_cond_kwargs:
1243
- raise ValueError(
1244
- 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`"
1245
- )
1246
- image_embeds = added_cond_kwargs.get("image_embeds")
1247
- image_embeds = self.encoder_hid_proj(image_embeds)
1248
- encoder_hidden_states = (encoder_hidden_states, image_embeds)
1249
- return encoder_hidden_states
1250
-
1251
- def init_kv_extraction(self):
1252
- for block in self.down_blocks:
1253
- if hasattr(block, "has_cross_attention") and block.has_cross_attention:
1254
- block.init_kv_extraction()
1255
-
1256
- for block in self.up_blocks:
1257
- if hasattr(block, "has_cross_attention") and block.has_cross_attention:
1258
- block.init_kv_extraction()
1259
-
1260
- if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
1261
- self.mid_block.init_kv_extraction()
1262
-
1263
- def forward(
1264
- self,
1265
- sample: torch.FloatTensor,
1266
- timestep: Union[torch.Tensor, float, int],
1267
- encoder_hidden_states: torch.Tensor,
1268
- controlnet_cond: torch.FloatTensor,
1269
- conditioning_scale: float = 1.0,
1270
- class_labels: Optional[torch.Tensor] = None,
1271
- timestep_cond: Optional[torch.Tensor] = None,
1272
- attention_mask: Optional[torch.Tensor] = None,
1273
- cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1274
- added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
1275
- down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
1276
- mid_block_additional_residual: Optional[torch.Tensor] = None,
1277
- down_intrablock_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
1278
- encoder_attention_mask: Optional[torch.Tensor] = None,
1279
- guess_mode: bool = False,
1280
- return_dict: bool = True,
1281
- ) -> Union[ExtractKVUNet2DConditionOutput, Tuple]:
1282
- r"""
1283
- The [`ExtractKVUNet2DConditionModel`] forward method.
1284
-
1285
- Args:
1286
- sample (`torch.FloatTensor`):
1287
- The noisy input tensor with the following shape `(batch, channel, height, width)`.
1288
- timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
1289
- encoder_hidden_states (`torch.FloatTensor`):
1290
- The encoder hidden states with shape `(batch, sequence_length, feature_dim)`.
1291
- class_labels (`torch.Tensor`, *optional*, defaults to `None`):
1292
- Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
1293
- timestep_cond: (`torch.Tensor`, *optional*, defaults to `None`):
1294
- Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed
1295
- through the `self.time_embedding` layer to obtain the timestep embeddings.
1296
- attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
1297
- An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
1298
- is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
1299
- negative values to the attention scores corresponding to "discard" tokens.
1300
- cross_attention_kwargs (`dict`, *optional*):
1301
- A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1302
- `self.processor` in
1303
- [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1304
- added_cond_kwargs: (`dict`, *optional*):
1305
- A kwargs dictionary containing additional embeddings that if specified are added to the embeddings that
1306
- are passed along to the UNet blocks.
1307
- down_block_additional_residuals: (`tuple` of `torch.Tensor`, *optional*):
1308
- A tuple of tensors that if specified are added to the residuals of down unet blocks.
1309
- mid_block_additional_residual: (`torch.Tensor`, *optional*):
1310
- A tensor that if specified is added to the residual of the middle unet block.
1311
- down_intrablock_additional_residuals (`tuple` of `torch.Tensor`, *optional*):
1312
- additional residuals to be added within UNet down blocks, for example from T2I-Adapter side model(s)
1313
- encoder_attention_mask (`torch.Tensor`):
1314
- A cross-attention mask of shape `(batch, sequence_length)` is applied to `encoder_hidden_states`. If
1315
- `True` the mask is kept, otherwise if `False` it is discarded. Mask will be converted into a bias,
1316
- which adds large negative values to the attention scores corresponding to "discard" tokens.
1317
- return_dict (`bool`, *optional*, defaults to `True`):
1318
- Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
1319
- tuple.
1320
-
1321
- Returns:
1322
- [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
1323
- If `return_dict` is True, an [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] is returned,
1324
- otherwise a `tuple` is returned where the first element is the sample tensor.
1325
- """
1326
- # check channel order
1327
- channel_order = self.config.controlnet_conditioning_channel_order
1328
-
1329
- if channel_order == "rgb":
1330
- # in rgb order by default
1331
- ...
1332
- elif channel_order == "bgr":
1333
- controlnet_cond = torch.flip(controlnet_cond, dims=[1])
1334
- else:
1335
- raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}")
1336
-
1337
- # By default samples have to be AT least a multiple of the overall upsampling factor.
1338
- # The overall upsampling factor is equal to 2 ** (# num of upsampling layers).
1339
- # However, the upsampling interpolation output size can be forced to fit any upsampling size
1340
- # on the fly if necessary.
1341
- default_overall_up_factor = 2**self.num_upsamplers
1342
-
1343
- # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
1344
- forward_upsample_size = False
1345
- upsample_size = None
1346
-
1347
- for dim in sample.shape[-2:]:
1348
- if dim % default_overall_up_factor != 0:
1349
- # Forward upsample size to force interpolation output size.
1350
- forward_upsample_size = True
1351
- break
1352
-
1353
- # ensure attention_mask is a bias, and give it a singleton query_tokens dimension
1354
- # expects mask of shape:
1355
- # [batch, key_tokens]
1356
- # adds singleton query_tokens dimension:
1357
- # [batch, 1, key_tokens]
1358
- # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
1359
- # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
1360
- # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
1361
- if attention_mask is not None:
1362
- # assume that mask is expressed as:
1363
- # (1 = keep, 0 = discard)
1364
- # convert mask into a bias that can be added to attention scores:
1365
- # (keep = +0, discard = -10000.0)
1366
- attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
1367
- attention_mask = attention_mask.unsqueeze(1)
1368
-
1369
- # convert encoder_attention_mask to a bias the same way we do for attention_mask
1370
- if encoder_attention_mask is not None:
1371
- encoder_attention_mask = (1 - encoder_attention_mask.to(sample.dtype)) * -10000.0
1372
- encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
1373
-
1374
- # 0. center input if necessary
1375
- if self.config.center_input_sample:
1376
- sample = 2 * sample - 1.0
1377
-
1378
- # 1. time
1379
- t_emb = self.get_time_embed(sample=sample, timestep=timestep)
1380
- emb = self.time_embedding(t_emb, timestep_cond)
1381
- aug_emb = None
1382
-
1383
- class_emb = self.get_class_embed(sample=sample, class_labels=class_labels)
1384
- if class_emb is not None:
1385
- if self.config.class_embeddings_concat:
1386
- emb = torch.cat([emb, class_emb], dim=-1)
1387
- else:
1388
- emb = emb + class_emb
1389
-
1390
- aug_emb = self.get_aug_embed(
1391
- emb=emb, encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
1392
- )
1393
- if self.config.addition_embed_type == "image_hint":
1394
- aug_emb, hint = aug_emb
1395
- sample = torch.cat([sample, hint], dim=1)
1396
-
1397
- emb = emb + aug_emb if aug_emb is not None else emb
1398
-
1399
- if self.time_embed_act is not None:
1400
- emb = self.time_embed_act(emb)
1401
-
1402
- encoder_hidden_states = self.process_encoder_hidden_states(
1403
- encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
1404
- )
1405
-
1406
- # 2. pre-process
1407
- sample = self.conv_in(sample)
1408
- controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
1409
- sample = sample + controlnet_cond
1410
-
1411
- # 2.5 GLIGEN position net
1412
- if cross_attention_kwargs is not None and cross_attention_kwargs.get("gligen", None) is not None:
1413
- cross_attention_kwargs = cross_attention_kwargs.copy()
1414
- gligen_args = cross_attention_kwargs.pop("gligen")
1415
- cross_attention_kwargs["gligen"] = {"objs": self.position_net(**gligen_args)}
1416
-
1417
- if cross_attention_kwargs is not None and cross_attention_kwargs.get("kv_drop_idx", None) is not None:
1418
- threshold = cross_attention_kwargs.pop("kv_drop_idx")
1419
- cross_attention_kwargs["kv_drop_idx"] = timestep<threshold
1420
-
1421
- # 3. down
1422
- # we're popping the `scale` instead of getting it because otherwise `scale` will be propagated
1423
- # to the internal blocks and will raise deprecation warnings. this will be confusing for our users.
1424
- if cross_attention_kwargs is not None:
1425
- cross_attention_kwargs = cross_attention_kwargs.copy()
1426
- lora_scale = cross_attention_kwargs.pop("scale", 1.0)
1427
- else:
1428
- lora_scale = 1.0
1429
-
1430
- if USE_PEFT_BACKEND:
1431
- # weight the lora layers by setting `lora_scale` for each PEFT layer
1432
- scale_lora_layers(self, lora_scale)
1433
-
1434
- is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None
1435
- # using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets
1436
- is_adapter = down_intrablock_additional_residuals is not None
1437
- # maintain backward compatibility for legacy usage, where
1438
- # T2I-Adapter and ControlNet both use down_block_additional_residuals arg
1439
- # but can only use one or the other
1440
- if not is_adapter and mid_block_additional_residual is None and down_block_additional_residuals is not None:
1441
- deprecate(
1442
- "T2I should not use down_block_additional_residuals",
1443
- "1.3.0",
1444
- "Passing intrablock residual connections with `down_block_additional_residuals` is deprecated \
1445
- and will be removed in diffusers 1.3.0. `down_block_additional_residuals` should only be used \
1446
- for ControlNet. Please make sure use `down_intrablock_additional_residuals` instead. ",
1447
- standard_warn=False,
1448
- )
1449
- down_intrablock_additional_residuals = down_block_additional_residuals
1450
- is_adapter = True
1451
-
1452
- down_block_res_samples = (sample,)
1453
- extracted_kvs = {}
1454
- for downsample_block in self.down_blocks:
1455
- if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
1456
- # For t2i-adapter CrossAttnDownBlock2D
1457
- additional_residuals = {}
1458
- if is_adapter and len(down_intrablock_additional_residuals) > 0:
1459
- additional_residuals["additional_residuals"] = down_intrablock_additional_residuals.pop(0)
1460
-
1461
- sample, res_samples, extracted_kv = downsample_block(
1462
- hidden_states=sample,
1463
- temb=emb,
1464
- encoder_hidden_states=encoder_hidden_states,
1465
- attention_mask=attention_mask,
1466
- cross_attention_kwargs=cross_attention_kwargs,
1467
- encoder_attention_mask=encoder_attention_mask,
1468
- **additional_residuals,
1469
- )
1470
- extracted_kvs.update(extracted_kv)
1471
- else:
1472
- sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
1473
- if is_adapter and len(down_intrablock_additional_residuals) > 0:
1474
- sample += down_intrablock_additional_residuals.pop(0)
1475
-
1476
- down_block_res_samples += res_samples
1477
-
1478
- if is_controlnet:
1479
- new_down_block_res_samples = ()
1480
-
1481
- for down_block_res_sample, down_block_additional_residual in zip(
1482
- down_block_res_samples, down_block_additional_residuals
1483
- ):
1484
- down_block_res_sample = down_block_res_sample + down_block_additional_residual
1485
- new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)
1486
-
1487
- down_block_res_samples = new_down_block_res_samples
1488
-
1489
- # 4. mid
1490
- if self.mid_block is not None:
1491
- if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
1492
- sample, extracted_kv = self.mid_block(
1493
- sample,
1494
- emb,
1495
- encoder_hidden_states=encoder_hidden_states,
1496
- attention_mask=attention_mask,
1497
- cross_attention_kwargs=cross_attention_kwargs,
1498
- encoder_attention_mask=encoder_attention_mask,
1499
- )
1500
- extracted_kvs.update(extracted_kv)
1501
- else:
1502
- sample = self.mid_block(sample, emb)
1503
-
1504
- # To support T2I-Adapter-XL
1505
- if (
1506
- is_adapter
1507
- and len(down_intrablock_additional_residuals) > 0
1508
- and sample.shape == down_intrablock_additional_residuals[0].shape
1509
- ):
1510
- sample += down_intrablock_additional_residuals.pop(0)
1511
-
1512
- if is_controlnet:
1513
- sample = sample + mid_block_additional_residual
1514
-
1515
- # 5. Control net blocks
1516
-
1517
- controlnet_down_block_res_samples = ()
1518
-
1519
- for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
1520
- down_block_res_sample = controlnet_block(down_block_res_sample)
1521
- controlnet_down_block_res_samples = controlnet_down_block_res_samples + (down_block_res_sample,)
1522
-
1523
- mid_block_res_sample = self.controlnet_mid_block(sample)
1524
-
1525
- # 6. up
1526
- for i, upsample_block in enumerate(self.up_blocks):
1527
- is_final_block = i == len(self.up_blocks) - 1
1528
-
1529
- res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
1530
- down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
1531
-
1532
- # if we have not reached the final block and need to forward the
1533
- # upsample size, we do it here
1534
- if not is_final_block and forward_upsample_size:
1535
- upsample_size = down_block_res_samples[-1].shape[2:]
1536
-
1537
- if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
1538
- sample, extract_kv = upsample_block(
1539
- hidden_states=sample,
1540
- temb=emb,
1541
- res_hidden_states_tuple=res_samples,
1542
- encoder_hidden_states=encoder_hidden_states,
1543
- cross_attention_kwargs=cross_attention_kwargs,
1544
- upsample_size=upsample_size,
1545
- attention_mask=attention_mask,
1546
- encoder_attention_mask=encoder_attention_mask,
1547
- )
1548
- extracted_kvs.update(extract_kv)
1549
- else:
1550
- sample = upsample_block(
1551
- hidden_states=sample,
1552
- temb=emb,
1553
- res_hidden_states_tuple=res_samples,
1554
- upsample_size=upsample_size,
1555
- )
1556
-
1557
- # 6. post-process
1558
- if self.conv_norm_out:
1559
- sample = self.conv_norm_out(sample)
1560
- sample = self.conv_act(sample)
1561
- sample = self.conv_out(sample)
1562
-
1563
- # 7. scaling
1564
- if guess_mode and not self.config.global_pool_conditions:
1565
- scales = torch.logspace(-1, 0, len(controlnet_down_block_res_samples) + 1, device=sample.device) # 0.1 to 1.0
1566
- scales = scales * conditioning_scale
1567
- controlnet_down_block_res_samples = [sample * scale for sample, scale in zip(controlnet_down_block_res_samples, scales)]
1568
- mid_block_res_sample = mid_block_res_sample * scales[-1] # last one
1569
- else:
1570
- controlnet_down_block_res_samples = [sample * conditioning_scale for sample in controlnet_down_block_res_samples]
1571
- mid_block_res_sample = mid_block_res_sample * conditioning_scale
1572
-
1573
- if self.config.global_pool_conditions:
1574
- controlnet_down_block_res_samples = [
1575
- torch.mean(sample, dim=(2, 3), keepdim=True) for sample in controlnet_down_block_res_samples
1576
- ]
1577
- mid_block_res_sample = torch.mean(mid_block_res_sample, dim=(2, 3), keepdim=True)
1578
-
1579
- if USE_PEFT_BACKEND:
1580
- # remove `lora_scale` from each PEFT layer
1581
- unscale_lora_layers(self, lora_scale)
1582
-
1583
- if not return_dict:
1584
- return (sample, extracted_kvs, controlnet_down_block_res_samples, mid_block_res_sample)
1585
-
1586
- return ExtractKVUNet2DConditionOutput(
1587
- sample=sample, cached_kvs=extracted_kvs,
1588
- down_block_res_samples=controlnet_down_block_res_samples, mid_block_res_sample=mid_block_res_sample
1589
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
pipelines/sdxl_instantir.py CHANGED
@@ -1377,6 +1377,7 @@ class InstantIRPipeline(
1377
  image = image * self.vae.config.scaling_factor
1378
  if needs_upcasting:
1379
  self.vae.to(dtype=torch.float16)
 
1380
  else:
1381
  height = int(height * self.vae_scale_factor)
1382
  width = int(width * self.vae_scale_factor)
 
1377
  image = image * self.vae.config.scaling_factor
1378
  if needs_upcasting:
1379
  self.vae.to(dtype=torch.float16)
1380
+ image = image.to(dtype=torch.float16)
1381
  else:
1382
  height = int(height * self.vae_scale_factor)
1383
  width = int(width * self.vae_scale_factor)
requirements.txt CHANGED
@@ -1,5 +1,6 @@
1
- diffusers
2
  pillow
 
3
  accelerate==0.25.0
4
  datasets==2.19.1
5
  einops==0.8.0
 
1
+ diffusers==0.28.1
2
  pillow
3
+ spaces
4
  accelerate==0.25.0
5
  datasets==2.19.1
6
  einops==0.8.0