prithivMLmods commited on
Commit
7533876
·
verified ·
1 Parent(s): 79a2132

Delete controlnet_union.py

Browse files
Files changed (1) hide show
  1. controlnet_union.py +0 -1061
controlnet_union.py DELETED
@@ -1,1061 +0,0 @@
1
- from collections import OrderedDict
2
- from dataclasses import dataclass
3
- from typing import Any, Dict, List, Optional, Tuple, Union
4
-
5
- import torch
6
- from diffusers.configuration_utils import ConfigMixin, register_to_config
7
- from diffusers.loaders import FromOriginalModelMixin
8
- from diffusers.models.attention_processor import (
9
- ADDED_KV_ATTENTION_PROCESSORS,
10
- CROSS_ATTENTION_PROCESSORS,
11
- AttentionProcessor,
12
- AttnAddedKVProcessor,
13
- AttnProcessor,
14
- )
15
- from diffusers.models.embeddings import (
16
- TextImageProjection,
17
- TextImageTimeEmbedding,
18
- TextTimeEmbedding,
19
- TimestepEmbedding,
20
- Timesteps,
21
- )
22
- from diffusers.models.modeling_utils import ModelMixin
23
- from diffusers.models.unets.unet_2d_blocks import (
24
- CrossAttnDownBlock2D,
25
- DownBlock2D,
26
- UNetMidBlock2DCrossAttn,
27
- get_down_block,
28
- )
29
- from diffusers.models.unets.unet_2d_condition import UNet2DConditionModel
30
- from diffusers.utils import BaseOutput, logging
31
- from torch import nn
32
- from torch.nn import functional as F
33
-
34
- logger = logging.get_logger(__name__) # pylint: disable=invalid-name
35
-
36
-
37
- # Transformer Block
38
- # Used to exchange info between different conditions and input image
39
- # With reference to https://github.com/TencentARC/T2I-Adapter/blob/SD/ldm/modules/encoders/adapter.py#L147
40
- class QuickGELU(nn.Module):
41
- def forward(self, x: torch.Tensor):
42
- return x * torch.sigmoid(1.702 * x)
43
-
44
-
45
- class LayerNorm(nn.LayerNorm):
46
- """Subclass torch's LayerNorm to handle fp16."""
47
-
48
- def forward(self, x: torch.Tensor):
49
- orig_type = x.dtype
50
- ret = super().forward(x)
51
- return ret.type(orig_type)
52
-
53
-
54
- class ResidualAttentionBlock(nn.Module):
55
- def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
56
- super().__init__()
57
-
58
- self.attn = nn.MultiheadAttention(d_model, n_head)
59
- self.ln_1 = LayerNorm(d_model)
60
- self.mlp = nn.Sequential(
61
- OrderedDict(
62
- [
63
- ("c_fc", nn.Linear(d_model, d_model * 4)),
64
- ("gelu", QuickGELU()),
65
- ("c_proj", nn.Linear(d_model * 4, d_model)),
66
- ]
67
- )
68
- )
69
- self.ln_2 = LayerNorm(d_model)
70
- self.attn_mask = attn_mask
71
-
72
- def attention(self, x: torch.Tensor):
73
- self.attn_mask = (
74
- self.attn_mask.to(dtype=x.dtype, device=x.device)
75
- if self.attn_mask is not None
76
- else None
77
- )
78
- return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
79
-
80
- def forward(self, x: torch.Tensor):
81
- x = x + self.attention(self.ln_1(x))
82
- x = x + self.mlp(self.ln_2(x))
83
- return x
84
-
85
-
86
- # -----------------------------------------------------------------------------------------------------
87
-
88
- @dataclass
89
- class ControlNetOutput(BaseOutput):
90
- """
91
- The output of [`ControlNetModel`].
92
- Args:
93
- down_block_res_samples (`tuple[torch.Tensor]`):
94
- A tuple of downsample activations at different resolutions for each downsampling block. Each tensor should
95
- be of shape `(batch_size, channel * resolution, height //resolution, width // resolution)`. Output can be
96
- used to condition the original UNet's downsampling activations.
97
- mid_down_block_re_sample (`torch.Tensor`):
98
- The activation of the midde block (the lowest sample resolution). Each tensor should be of shape
99
- `(batch_size, channel * lowest_resolution, height // lowest_resolution, width // lowest_resolution)`.
100
- Output can be used to condition the original UNet's middle block activation.
101
- """
102
-
103
- down_block_res_samples: Tuple[torch.Tensor]
104
- mid_block_res_sample: torch.Tensor
105
-
106
-
107
- class ControlNetConditioningEmbedding(nn.Module):
108
- """
109
- Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN
110
- [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized
111
- training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the
112
- convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides
113
- (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
114
- model) to encode image-space conditions ... into feature maps ..."
115
- """
116
-
117
- # original setting is (16, 32, 96, 256)
118
- def __init__(
119
- self,
120
- conditioning_embedding_channels: int,
121
- conditioning_channels: int = 3,
122
- block_out_channels: Tuple[int] = (48, 96, 192, 384),
123
- ):
124
- super().__init__()
125
-
126
- self.conv_in = nn.Conv2d(
127
- conditioning_channels, block_out_channels[0], kernel_size=3, padding=1
128
- )
129
-
130
- self.blocks = nn.ModuleList([])
131
-
132
- for i in range(len(block_out_channels) - 1):
133
- channel_in = block_out_channels[i]
134
- channel_out = block_out_channels[i + 1]
135
- self.blocks.append(
136
- nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1)
137
- )
138
- self.blocks.append(
139
- nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2)
140
- )
141
-
142
- self.conv_out = zero_module(
143
- nn.Conv2d(
144
- block_out_channels[-1],
145
- conditioning_embedding_channels,
146
- kernel_size=3,
147
- padding=1,
148
- )
149
- )
150
-
151
- def forward(self, conditioning):
152
- embedding = self.conv_in(conditioning)
153
- embedding = F.silu(embedding)
154
-
155
- for block in self.blocks:
156
- embedding = block(embedding)
157
- embedding = F.silu(embedding)
158
-
159
- embedding = self.conv_out(embedding)
160
-
161
- return embedding
162
-
163
-
164
- class ControlNetModel_Union(ModelMixin, ConfigMixin, FromOriginalModelMixin):
165
- """
166
- A ControlNet model.
167
- Args:
168
- in_channels (`int`, defaults to 4):
169
- The number of channels in the input sample.
170
- flip_sin_to_cos (`bool`, defaults to `True`):
171
- Whether to flip the sin to cos in the time embedding.
172
- freq_shift (`int`, defaults to 0):
173
- The frequency shift to apply to the time embedding.
174
- down_block_types (`tuple[str]`, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
175
- The tuple of downsample blocks to use.
176
- only_cross_attention (`Union[bool, Tuple[bool]]`, defaults to `False`):
177
- block_out_channels (`tuple[int]`, defaults to `(320, 640, 1280, 1280)`):
178
- The tuple of output channels for each block.
179
- layers_per_block (`int`, defaults to 2):
180
- The number of layers per block.
181
- downsample_padding (`int`, defaults to 1):
182
- The padding to use for the downsampling convolution.
183
- mid_block_scale_factor (`float`, defaults to 1):
184
- The scale factor to use for the mid block.
185
- act_fn (`str`, defaults to "silu"):
186
- The activation function to use.
187
- norm_num_groups (`int`, *optional*, defaults to 32):
188
- The number of groups to use for the normalization. If None, normalization and activation layers is skipped
189
- in post-processing.
190
- norm_eps (`float`, defaults to 1e-5):
191
- The epsilon to use for the normalization.
192
- cross_attention_dim (`int`, defaults to 1280):
193
- The dimension of the cross attention features.
194
- transformer_layers_per_block (`int` or `Tuple[int]`, *optional*, defaults to 1):
195
- The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
196
- [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
197
- [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
198
- encoder_hid_dim (`int`, *optional*, defaults to None):
199
- If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
200
- dimension to `cross_attention_dim`.
201
- encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
202
- If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
203
- embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
204
- attention_head_dim (`Union[int, Tuple[int]]`, defaults to 8):
205
- The dimension of the attention heads.
206
- use_linear_projection (`bool`, defaults to `False`):
207
- class_embed_type (`str`, *optional*, defaults to `None`):
208
- The type of class embedding to use which is ultimately summed with the time embeddings. Choose from None,
209
- `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
210
- addition_embed_type (`str`, *optional*, defaults to `None`):
211
- Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
212
- "text". "text" will use the `TextTimeEmbedding` layer.
213
- num_class_embeds (`int`, *optional*, defaults to 0):
214
- Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
215
- class conditioning with `class_embed_type` equal to `None`.
216
- upcast_attention (`bool`, defaults to `False`):
217
- resnet_time_scale_shift (`str`, defaults to `"default"`):
218
- Time scale shift config for ResNet blocks (see `ResnetBlock2D`). Choose from `default` or `scale_shift`.
219
- projection_class_embeddings_input_dim (`int`, *optional*, defaults to `None`):
220
- The dimension of the `class_labels` input when `class_embed_type="projection"`. Required when
221
- `class_embed_type="projection"`.
222
- controlnet_conditioning_channel_order (`str`, defaults to `"rgb"`):
223
- The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
224
- conditioning_embedding_out_channels (`tuple[int]`, *optional*, defaults to `(16, 32, 96, 256)`):
225
- The tuple of output channel for each block in the `conditioning_embedding` layer.
226
- global_pool_conditions (`bool`, defaults to `False`):
227
- """
228
-
229
- _supports_gradient_checkpointing = True
230
-
231
- @register_to_config
232
- def __init__(
233
- self,
234
- in_channels: int = 4,
235
- conditioning_channels: int = 3,
236
- flip_sin_to_cos: bool = True,
237
- freq_shift: int = 0,
238
- down_block_types: Tuple[str] = (
239
- "CrossAttnDownBlock2D",
240
- "CrossAttnDownBlock2D",
241
- "CrossAttnDownBlock2D",
242
- "DownBlock2D",
243
- ),
244
- only_cross_attention: Union[bool, Tuple[bool]] = False,
245
- block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
246
- layers_per_block: int = 2,
247
- downsample_padding: int = 1,
248
- mid_block_scale_factor: float = 1,
249
- act_fn: str = "silu",
250
- norm_num_groups: Optional[int] = 32,
251
- norm_eps: float = 1e-5,
252
- cross_attention_dim: int = 1280,
253
- transformer_layers_per_block: Union[int, Tuple[int]] = 1,
254
- encoder_hid_dim: Optional[int] = None,
255
- encoder_hid_dim_type: Optional[str] = None,
256
- attention_head_dim: Union[int, Tuple[int]] = 8,
257
- num_attention_heads: Optional[Union[int, Tuple[int]]] = None,
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
- projection_class_embeddings_input_dim: Optional[int] = None,
266
- controlnet_conditioning_channel_order: str = "rgb",
267
- conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
268
- global_pool_conditions: bool = False,
269
- addition_embed_type_num_heads=64,
270
- num_control_type=6,
271
- ):
272
- super().__init__()
273
-
274
- # If `num_attention_heads` is not defined (which is the case for most models)
275
- # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
276
- # The reason for this behavior is to correct for incorrectly named variables that were introduced
277
- # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
278
- # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
279
- # which is why we correct for the naming here.
280
- num_attention_heads = num_attention_heads or attention_head_dim
281
-
282
- # Check inputs
283
- if len(block_out_channels) != len(down_block_types):
284
- raise ValueError(
285
- 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}."
286
- )
287
-
288
- if not isinstance(only_cross_attention, bool) and len(
289
- only_cross_attention
290
- ) != len(down_block_types):
291
- raise ValueError(
292
- 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}."
293
- )
294
-
295
- if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(
296
- down_block_types
297
- ):
298
- raise ValueError(
299
- 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}."
300
- )
301
-
302
- if isinstance(transformer_layers_per_block, int):
303
- transformer_layers_per_block = [transformer_layers_per_block] * len(
304
- down_block_types
305
- )
306
-
307
- # input
308
- conv_in_kernel = 3
309
- conv_in_padding = (conv_in_kernel - 1) // 2
310
- self.conv_in = nn.Conv2d(
311
- in_channels,
312
- block_out_channels[0],
313
- kernel_size=conv_in_kernel,
314
- padding=conv_in_padding,
315
- )
316
-
317
- # time
318
- time_embed_dim = block_out_channels[0] * 4
319
- self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
320
- timestep_input_dim = block_out_channels[0]
321
- self.time_embedding = TimestepEmbedding(
322
- timestep_input_dim,
323
- time_embed_dim,
324
- act_fn=act_fn,
325
- )
326
-
327
- if encoder_hid_dim_type is None and encoder_hid_dim is not None:
328
- encoder_hid_dim_type = "text_proj"
329
- self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
330
- logger.info(
331
- "encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined."
332
- )
333
-
334
- if encoder_hid_dim is None and encoder_hid_dim_type is not None:
335
- raise ValueError(
336
- f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
337
- )
338
-
339
- if encoder_hid_dim_type == "text_proj":
340
- self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
341
- elif encoder_hid_dim_type == "text_image_proj":
342
- # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
343
- # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
344
- # case when `addition_embed_type == "text_image_proj"` (Kadinsky 2.1)`
345
- self.encoder_hid_proj = TextImageProjection(
346
- text_embed_dim=encoder_hid_dim,
347
- image_embed_dim=cross_attention_dim,
348
- cross_attention_dim=cross_attention_dim,
349
- )
350
-
351
- elif encoder_hid_dim_type is not None:
352
- raise ValueError(
353
- f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'."
354
- )
355
- else:
356
- self.encoder_hid_proj = None
357
-
358
- # class embedding
359
- if class_embed_type is None and num_class_embeds is not None:
360
- self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
361
- elif class_embed_type == "timestep":
362
- self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
363
- elif class_embed_type == "identity":
364
- self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
365
- elif class_embed_type == "projection":
366
- if projection_class_embeddings_input_dim is None:
367
- raise ValueError(
368
- "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
369
- )
370
- # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
371
- # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
372
- # 2. it projects from an arbitrary input dimension.
373
- #
374
- # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
375
- # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
376
- # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
377
- self.class_embedding = TimestepEmbedding(
378
- projection_class_embeddings_input_dim, time_embed_dim
379
- )
380
- else:
381
- self.class_embedding = None
382
-
383
- if addition_embed_type == "text":
384
- if encoder_hid_dim is not None:
385
- text_time_embedding_from_dim = encoder_hid_dim
386
- else:
387
- text_time_embedding_from_dim = cross_attention_dim
388
-
389
- self.add_embedding = TextTimeEmbedding(
390
- text_time_embedding_from_dim,
391
- time_embed_dim,
392
- num_heads=addition_embed_type_num_heads,
393
- )
394
- elif addition_embed_type == "text_image":
395
- # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
396
- # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
397
- # case when `addition_embed_type == "text_image"` (Kadinsky 2.1)`
398
- self.add_embedding = TextImageTimeEmbedding(
399
- text_embed_dim=cross_attention_dim,
400
- image_embed_dim=cross_attention_dim,
401
- time_embed_dim=time_embed_dim,
402
- )
403
- elif addition_embed_type == "text_time":
404
- self.add_time_proj = Timesteps(
405
- addition_time_embed_dim, flip_sin_to_cos, freq_shift
406
- )
407
- self.add_embedding = TimestepEmbedding(
408
- projection_class_embeddings_input_dim, time_embed_dim
409
- )
410
-
411
- elif addition_embed_type is not None:
412
- raise ValueError(
413
- f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'."
414
- )
415
-
416
- # control net conditioning embedding
417
- self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
418
- conditioning_embedding_channels=block_out_channels[0],
419
- block_out_channels=conditioning_embedding_out_channels,
420
- conditioning_channels=conditioning_channels,
421
- )
422
-
423
- # Copyright by Qi Xin(2024/07/06)
424
- # Condition Transformer(fuse single/multi conditions with input image)
425
- # The Condition Transformer augment the feature representation of conditions
426
- # The overall design is somewhat like resnet. The output of Condition Transformer is used to predict a condition bias adding to the original condition feature.
427
- # num_control_type = 6
428
- num_trans_channel = 320
429
- num_trans_head = 8
430
- num_trans_layer = 1
431
- num_proj_channel = 320
432
- task_scale_factor = num_trans_channel**0.5
433
-
434
- self.task_embedding = nn.Parameter(
435
- task_scale_factor * torch.randn(num_control_type, num_trans_channel)
436
- )
437
- self.transformer_layes = nn.Sequential(
438
- *[
439
- ResidualAttentionBlock(num_trans_channel, num_trans_head)
440
- for _ in range(num_trans_layer)
441
- ]
442
- )
443
- self.spatial_ch_projs = zero_module(
444
- nn.Linear(num_trans_channel, num_proj_channel)
445
- )
446
- # -----------------------------------------------------------------------------------------------------
447
-
448
- # Copyright by Qi Xin(2024/07/06)
449
- # Control Encoder to distinguish different control conditions
450
- # A simple but effective module, consists of an embedding layer and a linear layer, to inject the control info to time embedding.
451
- self.control_type_proj = Timesteps(
452
- addition_time_embed_dim, flip_sin_to_cos, freq_shift
453
- )
454
- self.control_add_embedding = TimestepEmbedding(
455
- addition_time_embed_dim * num_control_type, time_embed_dim
456
- )
457
- # -----------------------------------------------------------------------------------------------------
458
-
459
- self.down_blocks = nn.ModuleList([])
460
- self.controlnet_down_blocks = nn.ModuleList([])
461
-
462
- if isinstance(only_cross_attention, bool):
463
- only_cross_attention = [only_cross_attention] * len(down_block_types)
464
-
465
- if isinstance(attention_head_dim, int):
466
- attention_head_dim = (attention_head_dim,) * len(down_block_types)
467
-
468
- if isinstance(num_attention_heads, int):
469
- num_attention_heads = (num_attention_heads,) * len(down_block_types)
470
-
471
- # down
472
- output_channel = block_out_channels[0]
473
-
474
- controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
475
- controlnet_block = zero_module(controlnet_block)
476
- self.controlnet_down_blocks.append(controlnet_block)
477
-
478
- for i, down_block_type in enumerate(down_block_types):
479
- input_channel = output_channel
480
- output_channel = block_out_channels[i]
481
- is_final_block = i == len(block_out_channels) - 1
482
-
483
- down_block = get_down_block(
484
- down_block_type,
485
- num_layers=layers_per_block,
486
- transformer_layers_per_block=transformer_layers_per_block[i],
487
- in_channels=input_channel,
488
- out_channels=output_channel,
489
- temb_channels=time_embed_dim,
490
- add_downsample=not is_final_block,
491
- resnet_eps=norm_eps,
492
- resnet_act_fn=act_fn,
493
- resnet_groups=norm_num_groups,
494
- cross_attention_dim=cross_attention_dim,
495
- num_attention_heads=num_attention_heads[i],
496
- attention_head_dim=attention_head_dim[i]
497
- if attention_head_dim[i] is not None
498
- else output_channel,
499
- downsample_padding=downsample_padding,
500
- use_linear_projection=use_linear_projection,
501
- only_cross_attention=only_cross_attention[i],
502
- upcast_attention=upcast_attention,
503
- resnet_time_scale_shift=resnet_time_scale_shift,
504
- )
505
- self.down_blocks.append(down_block)
506
-
507
- for _ in range(layers_per_block):
508
- controlnet_block = nn.Conv2d(
509
- output_channel, output_channel, kernel_size=1
510
- )
511
- controlnet_block = zero_module(controlnet_block)
512
- self.controlnet_down_blocks.append(controlnet_block)
513
-
514
- if not is_final_block:
515
- controlnet_block = nn.Conv2d(
516
- output_channel, output_channel, kernel_size=1
517
- )
518
- controlnet_block = zero_module(controlnet_block)
519
- self.controlnet_down_blocks.append(controlnet_block)
520
-
521
- # mid
522
- mid_block_channel = block_out_channels[-1]
523
-
524
- controlnet_block = nn.Conv2d(
525
- mid_block_channel, mid_block_channel, kernel_size=1
526
- )
527
- controlnet_block = zero_module(controlnet_block)
528
- self.controlnet_mid_block = controlnet_block
529
-
530
- self.mid_block = UNetMidBlock2DCrossAttn(
531
- transformer_layers_per_block=transformer_layers_per_block[-1],
532
- in_channels=mid_block_channel,
533
- temb_channels=time_embed_dim,
534
- resnet_eps=norm_eps,
535
- resnet_act_fn=act_fn,
536
- output_scale_factor=mid_block_scale_factor,
537
- resnet_time_scale_shift=resnet_time_scale_shift,
538
- cross_attention_dim=cross_attention_dim,
539
- num_attention_heads=num_attention_heads[-1],
540
- resnet_groups=norm_num_groups,
541
- use_linear_projection=use_linear_projection,
542
- upcast_attention=upcast_attention,
543
- )
544
-
545
- @classmethod
546
- def from_unet(
547
- cls,
548
- unet: UNet2DConditionModel,
549
- controlnet_conditioning_channel_order: str = "rgb",
550
- conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
551
- load_weights_from_unet: bool = True,
552
- ):
553
- r"""
554
- Instantiate a [`ControlNetModel`] from [`UNet2DConditionModel`].
555
- Parameters:
556
- unet (`UNet2DConditionModel`):
557
- The UNet model weights to copy to the [`ControlNetModel`]. All configuration options are also copied
558
- where applicable.
559
- """
560
- transformer_layers_per_block = (
561
- unet.config.transformer_layers_per_block
562
- if "transformer_layers_per_block" in unet.config
563
- else 1
564
- )
565
- encoder_hid_dim = (
566
- unet.config.encoder_hid_dim if "encoder_hid_dim" in unet.config else None
567
- )
568
- encoder_hid_dim_type = (
569
- unet.config.encoder_hid_dim_type
570
- if "encoder_hid_dim_type" in unet.config
571
- else None
572
- )
573
- addition_embed_type = (
574
- unet.config.addition_embed_type
575
- if "addition_embed_type" in unet.config
576
- else None
577
- )
578
- addition_time_embed_dim = (
579
- unet.config.addition_time_embed_dim
580
- if "addition_time_embed_dim" in unet.config
581
- else None
582
- )
583
-
584
- controlnet = cls(
585
- encoder_hid_dim=encoder_hid_dim,
586
- encoder_hid_dim_type=encoder_hid_dim_type,
587
- addition_embed_type=addition_embed_type,
588
- addition_time_embed_dim=addition_time_embed_dim,
589
- transformer_layers_per_block=transformer_layers_per_block,
590
- # transformer_layers_per_block=[1, 2, 5],
591
- in_channels=unet.config.in_channels,
592
- flip_sin_to_cos=unet.config.flip_sin_to_cos,
593
- freq_shift=unet.config.freq_shift,
594
- down_block_types=unet.config.down_block_types,
595
- only_cross_attention=unet.config.only_cross_attention,
596
- block_out_channels=unet.config.block_out_channels,
597
- layers_per_block=unet.config.layers_per_block,
598
- downsample_padding=unet.config.downsample_padding,
599
- mid_block_scale_factor=unet.config.mid_block_scale_factor,
600
- act_fn=unet.config.act_fn,
601
- norm_num_groups=unet.config.norm_num_groups,
602
- norm_eps=unet.config.norm_eps,
603
- cross_attention_dim=unet.config.cross_attention_dim,
604
- attention_head_dim=unet.config.attention_head_dim,
605
- num_attention_heads=unet.config.num_attention_heads,
606
- use_linear_projection=unet.config.use_linear_projection,
607
- class_embed_type=unet.config.class_embed_type,
608
- num_class_embeds=unet.config.num_class_embeds,
609
- upcast_attention=unet.config.upcast_attention,
610
- resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
611
- projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
612
- controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
613
- conditioning_embedding_out_channels=conditioning_embedding_out_channels,
614
- )
615
-
616
- if load_weights_from_unet:
617
- controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())
618
- controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())
619
- controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())
620
-
621
- if controlnet.class_embedding:
622
- controlnet.class_embedding.load_state_dict(
623
- unet.class_embedding.state_dict()
624
- )
625
-
626
- controlnet.down_blocks.load_state_dict(
627
- unet.down_blocks.state_dict(), strict=False
628
- )
629
- controlnet.mid_block.load_state_dict(
630
- unet.mid_block.state_dict(), strict=False
631
- )
632
-
633
- return controlnet
634
-
635
- @property
636
- # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
637
- def attn_processors(self) -> Dict[str, AttentionProcessor]:
638
- r"""
639
- Returns:
640
- `dict` of attention processors: A dictionary containing all attention processors used in the model with
641
- indexed by its weight name.
642
- """
643
- # set recursively
644
- processors = {}
645
-
646
- def fn_recursive_add_processors(
647
- name: str,
648
- module: torch.nn.Module,
649
- processors: Dict[str, AttentionProcessor],
650
- ):
651
- if hasattr(module, "get_processor"):
652
- processors[f"{name}.processor"] = module.get_processor(
653
- return_deprecated_lora=True
654
- )
655
-
656
- for sub_name, child in module.named_children():
657
- fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
658
-
659
- return processors
660
-
661
- for name, module in self.named_children():
662
- fn_recursive_add_processors(name, module, processors)
663
-
664
- return processors
665
-
666
- # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
667
- def set_attn_processor(
668
- self,
669
- processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]],
670
- _remove_lora=False,
671
- ):
672
- r"""
673
- Sets the attention processor to use to compute attention.
674
- Parameters:
675
- processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
676
- The instantiated processor class or a dictionary of processor classes that will be set as the processor
677
- for **all** `Attention` layers.
678
- If `processor` is a dict, the key needs to define the path to the corresponding cross attention
679
- processor. This is strongly recommended when setting trainable attention processors.
680
- """
681
- count = len(self.attn_processors.keys())
682
-
683
- if isinstance(processor, dict) and len(processor) != count:
684
- raise ValueError(
685
- f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
686
- f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
687
- )
688
-
689
- def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
690
- if hasattr(module, "set_processor"):
691
- if not isinstance(processor, dict):
692
- module.set_processor(processor, _remove_lora=_remove_lora)
693
- else:
694
- module.set_processor(
695
- processor.pop(f"{name}.processor"), _remove_lora=_remove_lora
696
- )
697
-
698
- for sub_name, child in module.named_children():
699
- fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
700
-
701
- for name, module in self.named_children():
702
- fn_recursive_attn_processor(name, module, processor)
703
-
704
- # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
705
- def set_default_attn_processor(self):
706
- """
707
- Disables custom attention processors and sets the default attention implementation.
708
- """
709
- if all(
710
- proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS
711
- for proc in self.attn_processors.values()
712
- ):
713
- processor = AttnAddedKVProcessor()
714
- elif all(
715
- proc.__class__ in CROSS_ATTENTION_PROCESSORS
716
- for proc in self.attn_processors.values()
717
- ):
718
- processor = AttnProcessor()
719
- else:
720
- raise ValueError(
721
- f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
722
- )
723
-
724
- self.set_attn_processor(processor, _remove_lora=True)
725
-
726
- # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attention_slice
727
- def set_attention_slice(self, slice_size):
728
- r"""
729
- Enable sliced attention computation.
730
- When this option is enabled, the attention module splits the input tensor in slices to compute attention in
731
- several steps. This is useful for saving some memory in exchange for a small decrease in speed.
732
- Args:
733
- slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
734
- When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
735
- `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
736
- provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
737
- must be a multiple of `slice_size`.
738
- """
739
- sliceable_head_dims = []
740
-
741
- def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
742
- if hasattr(module, "set_attention_slice"):
743
- sliceable_head_dims.append(module.sliceable_head_dim)
744
-
745
- for child in module.children():
746
- fn_recursive_retrieve_sliceable_dims(child)
747
-
748
- # retrieve number of attention layers
749
- for module in self.children():
750
- fn_recursive_retrieve_sliceable_dims(module)
751
-
752
- num_sliceable_layers = len(sliceable_head_dims)
753
-
754
- if slice_size == "auto":
755
- # half the attention head size is usually a good trade-off between
756
- # speed and memory
757
- slice_size = [dim // 2 for dim in sliceable_head_dims]
758
- elif slice_size == "max":
759
- # make smallest slice possible
760
- slice_size = num_sliceable_layers * [1]
761
-
762
- slice_size = (
763
- num_sliceable_layers * [slice_size]
764
- if not isinstance(slice_size, list)
765
- else slice_size
766
- )
767
-
768
- if len(slice_size) != len(sliceable_head_dims):
769
- raise ValueError(
770
- f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
771
- f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
772
- )
773
-
774
- for i in range(len(slice_size)):
775
- size = slice_size[i]
776
- dim = sliceable_head_dims[i]
777
- if size is not None and size > dim:
778
- raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
779
-
780
- # Recursively walk through all the children.
781
- # Any children which exposes the set_attention_slice method
782
- # gets the message
783
- def fn_recursive_set_attention_slice(
784
- module: torch.nn.Module, slice_size: List[int]
785
- ):
786
- if hasattr(module, "set_attention_slice"):
787
- module.set_attention_slice(slice_size.pop())
788
-
789
- for child in module.children():
790
- fn_recursive_set_attention_slice(child, slice_size)
791
-
792
- reversed_slice_size = list(reversed(slice_size))
793
- for module in self.children():
794
- fn_recursive_set_attention_slice(module, reversed_slice_size)
795
-
796
- def _set_gradient_checkpointing(self, module, value=False):
797
- if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):
798
- module.gradient_checkpointing = value
799
-
800
- def forward(
801
- self,
802
- sample: torch.FloatTensor,
803
- timestep: Union[torch.Tensor, float, int],
804
- encoder_hidden_states: torch.Tensor,
805
- controlnet_cond_list: torch.FloatTensor,
806
- conditioning_scale: float = 1.0,
807
- class_labels: Optional[torch.Tensor] = None,
808
- timestep_cond: Optional[torch.Tensor] = None,
809
- attention_mask: Optional[torch.Tensor] = None,
810
- added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
811
- cross_attention_kwargs: Optional[Dict[str, Any]] = None,
812
- guess_mode: bool = False,
813
- return_dict: bool = True,
814
- ) -> Union[ControlNetOutput, Tuple]:
815
- """
816
- The [`ControlNetModel`] forward method.
817
- Args:
818
- sample (`torch.FloatTensor`):
819
- The noisy input tensor.
820
- timestep (`Union[torch.Tensor, float, int]`):
821
- The number of timesteps to denoise an input.
822
- encoder_hidden_states (`torch.Tensor`):
823
- The encoder hidden states.
824
- controlnet_cond (`torch.FloatTensor`):
825
- The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
826
- conditioning_scale (`float`, defaults to `1.0`):
827
- The scale factor for ControlNet outputs.
828
- class_labels (`torch.Tensor`, *optional*, defaults to `None`):
829
- Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
830
- timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
831
- Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
832
- timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
833
- embeddings.
834
- attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
835
- An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
836
- is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
837
- negative values to the attention scores corresponding to "discard" tokens.
838
- added_cond_kwargs (`dict`):
839
- Additional conditions for the Stable Diffusion XL UNet.
840
- cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
841
- A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
842
- guess_mode (`bool`, defaults to `False`):
843
- In this mode, the ControlNet encoder tries its best to recognize the input content of the input even if
844
- you remove all prompts. A `guidance_scale` between 3.0 and 5.0 is recommended.
845
- return_dict (`bool`, defaults to `True`):
846
- Whether or not to return a [`~models.controlnet.ControlNetOutput`] instead of a plain tuple.
847
- Returns:
848
- [`~models.controlnet.ControlNetOutput`] **or** `tuple`:
849
- If `return_dict` is `True`, a [`~models.controlnet.ControlNetOutput`] is returned, otherwise a tuple is
850
- returned where the first element is the sample tensor.
851
- """
852
- # check channel order
853
- channel_order = self.config.controlnet_conditioning_channel_order
854
-
855
- if channel_order == "rgb":
856
- # in rgb order by default
857
- ...
858
- # elif channel_order == "bgr":
859
- # controlnet_cond = torch.flip(controlnet_cond, dims=[1])
860
- else:
861
- raise ValueError(
862
- f"unknown `controlnet_conditioning_channel_order`: {channel_order}"
863
- )
864
-
865
- # prepare attention_mask
866
- if attention_mask is not None:
867
- attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
868
- attention_mask = attention_mask.unsqueeze(1)
869
-
870
- # 1. time
871
- timesteps = timestep
872
- if not torch.is_tensor(timesteps):
873
- # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
874
- # This would be a good case for the `match` statement (Python 3.10+)
875
- is_mps = sample.device.type == "mps"
876
- if isinstance(timestep, float):
877
- dtype = torch.float32 if is_mps else torch.float64
878
- else:
879
- dtype = torch.int32 if is_mps else torch.int64
880
- timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
881
- elif len(timesteps.shape) == 0:
882
- timesteps = timesteps[None].to(sample.device)
883
-
884
- # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
885
- timesteps = timesteps.expand(sample.shape[0])
886
-
887
- t_emb = self.time_proj(timesteps)
888
-
889
- # timesteps does not contain any weights and will always return f32 tensors
890
- # but time_embedding might actually be running in fp16. so we need to cast here.
891
- # there might be better ways to encapsulate this.
892
- t_emb = t_emb.to(dtype=sample.dtype)
893
-
894
- emb = self.time_embedding(t_emb, timestep_cond)
895
- aug_emb = None
896
-
897
- if self.class_embedding is not None:
898
- if class_labels is None:
899
- raise ValueError(
900
- "class_labels should be provided when num_class_embeds > 0"
901
- )
902
-
903
- if self.config.class_embed_type == "timestep":
904
- class_labels = self.time_proj(class_labels)
905
-
906
- class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
907
- emb = emb + class_emb
908
-
909
- if self.config.addition_embed_type is not None:
910
- if self.config.addition_embed_type == "text":
911
- aug_emb = self.add_embedding(encoder_hidden_states)
912
-
913
- elif self.config.addition_embed_type == "text_time":
914
- if "text_embeds" not in added_cond_kwargs:
915
- raise ValueError(
916
- 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`"
917
- )
918
- text_embeds = added_cond_kwargs.get("text_embeds")
919
- if "time_ids" not in added_cond_kwargs:
920
- raise ValueError(
921
- 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`"
922
- )
923
- time_ids = added_cond_kwargs.get("time_ids")
924
- time_embeds = self.add_time_proj(time_ids.flatten())
925
- time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
926
-
927
- add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
928
- add_embeds = add_embeds.to(emb.dtype)
929
- aug_emb = self.add_embedding(add_embeds)
930
-
931
- # Copyright by Qi Xin(2024/07/06)
932
- # inject control type info to time embedding to distinguish different control conditions
933
- control_type = added_cond_kwargs.get("control_type")
934
- control_embeds = self.control_type_proj(control_type.flatten())
935
- control_embeds = control_embeds.reshape((t_emb.shape[0], -1))
936
- control_embeds = control_embeds.to(emb.dtype)
937
- control_emb = self.control_add_embedding(control_embeds)
938
- emb = emb + control_emb
939
- # ---------------------------------------------------------------------------------
940
-
941
- emb = emb + aug_emb if aug_emb is not None else emb
942
-
943
- # 2. pre-process
944
- sample = self.conv_in(sample)
945
- indices = torch.nonzero(control_type[0])
946
-
947
- # Copyright by Qi Xin(2024/07/06)
948
- # add single/multi conditons to input image.
949
- # Condition Transformer provides an easy and effective way to fuse different features naturally
950
- inputs = []
951
- condition_list = []
952
-
953
- for idx in range(indices.shape[0] + 1):
954
- if idx == indices.shape[0]:
955
- controlnet_cond = sample
956
- feat_seq = torch.mean(controlnet_cond, dim=(2, 3)) # N * C
957
- else:
958
- controlnet_cond = self.controlnet_cond_embedding(
959
- controlnet_cond_list[indices[idx][0]]
960
- )
961
- feat_seq = torch.mean(controlnet_cond, dim=(2, 3)) # N * C
962
- feat_seq = feat_seq + self.task_embedding[indices[idx][0]]
963
-
964
- inputs.append(feat_seq.unsqueeze(1))
965
- condition_list.append(controlnet_cond)
966
-
967
- x = torch.cat(inputs, dim=1) # NxLxC
968
- x = self.transformer_layes(x)
969
-
970
- controlnet_cond_fuser = sample * 0.0
971
- for idx in range(indices.shape[0]):
972
- alpha = self.spatial_ch_projs(x[:, idx])
973
- alpha = alpha.unsqueeze(-1).unsqueeze(-1)
974
- controlnet_cond_fuser += condition_list[idx] + alpha
975
-
976
- sample = sample + controlnet_cond_fuser
977
- # -------------------------------------------------------------------------------------------
978
-
979
- # 3. down
980
- down_block_res_samples = (sample,)
981
- for downsample_block in self.down_blocks:
982
- if (
983
- hasattr(downsample_block, "has_cross_attention")
984
- and downsample_block.has_cross_attention
985
- ):
986
- sample, res_samples = downsample_block(
987
- hidden_states=sample,
988
- temb=emb,
989
- encoder_hidden_states=encoder_hidden_states,
990
- attention_mask=attention_mask,
991
- cross_attention_kwargs=cross_attention_kwargs,
992
- )
993
- else:
994
- sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
995
-
996
- down_block_res_samples += res_samples
997
-
998
- # 4. mid
999
- if self.mid_block is not None:
1000
- sample = self.mid_block(
1001
- sample,
1002
- emb,
1003
- encoder_hidden_states=encoder_hidden_states,
1004
- attention_mask=attention_mask,
1005
- cross_attention_kwargs=cross_attention_kwargs,
1006
- )
1007
-
1008
- # 5. Control net blocks
1009
-
1010
- controlnet_down_block_res_samples = ()
1011
-
1012
- for down_block_res_sample, controlnet_block in zip(
1013
- down_block_res_samples, self.controlnet_down_blocks
1014
- ):
1015
- down_block_res_sample = controlnet_block(down_block_res_sample)
1016
- controlnet_down_block_res_samples = controlnet_down_block_res_samples + (
1017
- down_block_res_sample,
1018
- )
1019
-
1020
- down_block_res_samples = controlnet_down_block_res_samples
1021
-
1022
- mid_block_res_sample = self.controlnet_mid_block(sample)
1023
-
1024
- # 6. scaling
1025
- if guess_mode and not self.config.global_pool_conditions:
1026
- scales = torch.logspace(
1027
- -1, 0, len(down_block_res_samples) + 1, device=sample.device
1028
- ) # 0.1 to 1.0
1029
- scales = scales * conditioning_scale
1030
- down_block_res_samples = [
1031
- sample * scale for sample, scale in zip(down_block_res_samples, scales)
1032
- ]
1033
- mid_block_res_sample = mid_block_res_sample * scales[-1] # last one
1034
- else:
1035
- down_block_res_samples = [
1036
- sample * conditioning_scale for sample in down_block_res_samples
1037
- ]
1038
- mid_block_res_sample = mid_block_res_sample * conditioning_scale
1039
-
1040
- if self.config.global_pool_conditions:
1041
- down_block_res_samples = [
1042
- torch.mean(sample, dim=(2, 3), keepdim=True)
1043
- for sample in down_block_res_samples
1044
- ]
1045
- mid_block_res_sample = torch.mean(
1046
- mid_block_res_sample, dim=(2, 3), keepdim=True
1047
- )
1048
-
1049
- if not return_dict:
1050
- return (down_block_res_samples, mid_block_res_sample)
1051
-
1052
- return ControlNetOutput(
1053
- down_block_res_samples=down_block_res_samples,
1054
- mid_block_res_sample=mid_block_res_sample,
1055
- )
1056
-
1057
-
1058
- def zero_module(module):
1059
- for p in module.parameters():
1060
- nn.init.zeros_(p)
1061
- return module