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