SunderAli17 commited on
Commit
d9c1219
1 Parent(s): 3047fca

Create unet_2d_condition.py

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