ValerianFourel commited on
Commit
953fa77
·
verified ·
1 Parent(s): c6bfebc

Upload folder using huggingface_hub

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