a-r-r-o-w HF staff commited on
Commit
f7330e2
1 Parent(s): 5f8900c

Upload unet/modeling_unet.py with huggingface_hub

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