SunderAli17 commited on
Commit
439abab
·
verified ·
1 Parent(s): 6c34fb6

Create controlnet.py

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