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