Patil commited on
Commit
6a58247
·
verified ·
1 Parent(s): 5a8f685

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ {
3
+ "_class_name": "ControlNetModel",
4
+ "_diffusers_version": "0.20.0.dev0",
5
+ "_name_or_path": "../controlnet-1-0-inpainting/checkpoint-20000/controlnet",
6
+ "act_fn": "silu",
7
+ "addition_embed_type": "text_time",
8
+ "addition_embed_type_num_heads": 64,
9
+ "addition_time_embed_dim": 256,
10
+ "attention_head_dim": [
11
+ 5,
12
+ 10,
13
+ 20
14
+ ],
15
+ "block_out_channels": [
16
+ 320,
17
+ 640,
18
+ 1280
19
+ ],
20
+ "class_embed_type": null,
21
+ "conditioning_channels": 5,
22
+ "conditioning_embedding_out_channels": [
23
+ 16,
24
+ 32,
25
+ 96,
26
+ 256
27
+ ],
28
+ "controlnet_conditioning_channel_order": "rgb",
29
+ "cross_attention_dim": 2048,
30
+ "down_block_types": [
31
+ "DownBlock2D",
32
+ "CrossAttnDownBlock2D",
33
+ "CrossAttnDownBlock2D"
34
+ ],
35
+ "downsample_padding": 1,
36
+ "encoder_hid_dim": null,
37
+ "encoder_hid_dim_type": null,
38
+ "flip_sin_to_cos": true,
39
+ "freq_shift": 0,
40
+ "global_pool_conditions": false,
41
+ "in_channels": 4,
42
+ "layers_per_block": 2,
43
+ "mid_block_scale_factor": 1,
44
+ "norm_eps": 1e-05,
45
+ "norm_num_groups": 32,
46
+ "num_attention_heads": null,
47
+ "num_class_embeds": null,
48
+ "only_cross_attention": false,
49
+ "projection_class_embeddings_input_dim": 2816,
50
+ "resnet_time_scale_shift": "default",
51
+ "transformer_layers_per_block": [
52
+ 1,
53
+ 2,
54
+ 10
55
+ ],
56
+ "upcast_attention": null,
57
+ "use_linear_projection": true
58
+ }
controlnet.py ADDED
@@ -0,0 +1,872 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from diffusers.models.unets.unet_2d_blocks import (
34
+ CrossAttnDownBlock2D,
35
+ DownBlock2D,
36
+ UNetMidBlock2D,
37
+ UNetMidBlock2DCrossAttn,
38
+ get_down_block,
39
+ )
40
+ from diffusers.models.unets.unet_2d_condition import UNet2DConditionModel
41
+
42
+
43
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
44
+
45
+
46
+ @dataclass
47
+ class ControlNetOutput(BaseOutput):
48
+ """
49
+ The output of [`ControlNetModel`].
50
+
51
+ Args:
52
+ down_block_res_samples (`tuple[torch.Tensor]`):
53
+ A tuple of downsample activations at different resolutions for each downsampling block. Each tensor should
54
+ be of shape `(batch_size, channel * resolution, height //resolution, width // resolution)`. Output can be
55
+ used to condition the original UNet's downsampling activations.
56
+ mid_down_block_re_sample (`torch.Tensor`):
57
+ The activation of the middle block (the lowest sample resolution). Each tensor should be of shape
58
+ `(batch_size, channel * lowest_resolution, height // lowest_resolution, width // lowest_resolution)`.
59
+ Output can be used to condition the original UNet's middle block activation.
60
+ """
61
+
62
+ down_block_res_samples: Tuple[torch.Tensor]
63
+ mid_block_res_sample: torch.Tensor
64
+
65
+
66
+ class ControlNetConditioningEmbedding(nn.Module):
67
+ """
68
+ Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN
69
+ [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized
70
+ training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the
71
+ convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides
72
+ (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
73
+ model) to encode image-space conditions ... into feature maps ..."
74
+ """
75
+
76
+ def __init__(
77
+ self,
78
+ conditioning_embedding_channels: int,
79
+ conditioning_channels: int = 5, # Bria: update to 5
80
+ block_out_channels: Tuple[int, ...] = (16, 32, 96, 256),
81
+ ):
82
+ super().__init__()
83
+
84
+ self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
85
+
86
+ self.blocks = nn.ModuleList([])
87
+
88
+ for i in range(len(block_out_channels) - 1):
89
+ channel_in = block_out_channels[i]
90
+ channel_out = block_out_channels[i + 1]
91
+ self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
92
+ self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=1)) # Bria: update stride to 1
93
+
94
+ self.conv_out = zero_module(
95
+ nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
96
+ )
97
+
98
+ def forward(self, conditioning):
99
+ embedding = self.conv_in(conditioning)
100
+ embedding = F.silu(embedding)
101
+
102
+ for block in self.blocks:
103
+ embedding = block(embedding)
104
+ embedding = F.silu(embedding)
105
+
106
+ embedding = self.conv_out(embedding)
107
+
108
+ return embedding
109
+
110
+
111
+ class ControlNetModel(ModelMixin, ConfigMixin, FromOriginalModelMixin):
112
+ """
113
+ A ControlNet model.
114
+
115
+ Args:
116
+ in_channels (`int`, defaults to 4):
117
+ The number of channels in the input sample.
118
+ flip_sin_to_cos (`bool`, defaults to `True`):
119
+ Whether to flip the sin to cos in the time embedding.
120
+ freq_shift (`int`, defaults to 0):
121
+ The frequency shift to apply to the time embedding.
122
+ down_block_types (`tuple[str]`, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
123
+ The tuple of downsample blocks to use.
124
+ only_cross_attention (`Union[bool, Tuple[bool]]`, defaults to `False`):
125
+ block_out_channels (`tuple[int]`, defaults to `(320, 640, 1280, 1280)`):
126
+ The tuple of output channels for each block.
127
+ layers_per_block (`int`, defaults to 2):
128
+ The number of layers per block.
129
+ downsample_padding (`int`, defaults to 1):
130
+ The padding to use for the downsampling convolution.
131
+ mid_block_scale_factor (`float`, defaults to 1):
132
+ The scale factor to use for the mid block.
133
+ act_fn (`str`, defaults to "silu"):
134
+ The activation function to use.
135
+ norm_num_groups (`int`, *optional*, defaults to 32):
136
+ The number of groups to use for the normalization. If None, normalization and activation layers is skipped
137
+ in post-processing.
138
+ norm_eps (`float`, defaults to 1e-5):
139
+ The epsilon to use for the normalization.
140
+ cross_attention_dim (`int`, defaults to 1280):
141
+ The dimension of the cross attention features.
142
+ transformer_layers_per_block (`int` or `Tuple[int]`, *optional*, defaults to 1):
143
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
144
+ [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
145
+ [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
146
+ encoder_hid_dim (`int`, *optional*, defaults to None):
147
+ If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
148
+ dimension to `cross_attention_dim`.
149
+ encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
150
+ If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
151
+ embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
152
+ attention_head_dim (`Union[int, Tuple[int]]`, defaults to 8):
153
+ The dimension of the attention heads.
154
+ use_linear_projection (`bool`, defaults to `False`):
155
+ class_embed_type (`str`, *optional*, defaults to `None`):
156
+ The type of class embedding to use which is ultimately summed with the time embeddings. Choose from None,
157
+ `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
158
+ addition_embed_type (`str`, *optional*, defaults to `None`):
159
+ Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
160
+ "text". "text" will use the `TextTimeEmbedding` layer.
161
+ num_class_embeds (`int`, *optional*, defaults to 0):
162
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
163
+ class conditioning with `class_embed_type` equal to `None`.
164
+ upcast_attention (`bool`, defaults to `False`):
165
+ resnet_time_scale_shift (`str`, defaults to `"default"`):
166
+ Time scale shift config for ResNet blocks (see `ResnetBlock2D`). Choose from `default` or `scale_shift`.
167
+ projection_class_embeddings_input_dim (`int`, *optional*, defaults to `None`):
168
+ The dimension of the `class_labels` input when `class_embed_type="projection"`. Required when
169
+ `class_embed_type="projection"`.
170
+ controlnet_conditioning_channel_order (`str`, defaults to `"rgb"`):
171
+ The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
172
+ conditioning_embedding_out_channels (`tuple[int]`, *optional*, defaults to `(16, 32, 96, 256)`):
173
+ The tuple of output channel for each block in the `conditioning_embedding` layer.
174
+ global_pool_conditions (`bool`, defaults to `False`):
175
+ TODO(Patrick) - unused parameter.
176
+ addition_embed_type_num_heads (`int`, defaults to 64):
177
+ The number of heads to use for the `TextTimeEmbedding` layer.
178
+ """
179
+
180
+ _supports_gradient_checkpointing = True
181
+
182
+ @register_to_config
183
+ def __init__(
184
+ self,
185
+ in_channels: int = 4,
186
+ conditioning_channels: int = 3,
187
+ flip_sin_to_cos: bool = True,
188
+ freq_shift: int = 0,
189
+ down_block_types: Tuple[str, ...] = (
190
+ "CrossAttnDownBlock2D",
191
+ "CrossAttnDownBlock2D",
192
+ "CrossAttnDownBlock2D",
193
+ "DownBlock2D",
194
+ ),
195
+ mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
196
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
197
+ block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280),
198
+ layers_per_block: int = 2,
199
+ downsample_padding: int = 1,
200
+ mid_block_scale_factor: float = 1,
201
+ act_fn: str = "silu",
202
+ norm_num_groups: Optional[int] = 32,
203
+ norm_eps: float = 1e-5,
204
+ cross_attention_dim: int = 1280,
205
+ transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
206
+ encoder_hid_dim: Optional[int] = None,
207
+ encoder_hid_dim_type: Optional[str] = None,
208
+ attention_head_dim: Union[int, Tuple[int, ...]] = 8,
209
+ num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None,
210
+ use_linear_projection: bool = False,
211
+ class_embed_type: Optional[str] = None,
212
+ addition_embed_type: Optional[str] = None,
213
+ addition_time_embed_dim: Optional[int] = None,
214
+ num_class_embeds: Optional[int] = None,
215
+ upcast_attention: bool = False,
216
+ resnet_time_scale_shift: str = "default",
217
+ projection_class_embeddings_input_dim: Optional[int] = None,
218
+ controlnet_conditioning_channel_order: str = "rgb",
219
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
220
+ global_pool_conditions: bool = False,
221
+ addition_embed_type_num_heads: int = 64,
222
+ ):
223
+ super().__init__()
224
+
225
+ # If `num_attention_heads` is not defined (which is the case for most models)
226
+ # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
227
+ # The reason for this behavior is to correct for incorrectly named variables that were introduced
228
+ # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
229
+ # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
230
+ # which is why we correct for the naming here.
231
+ num_attention_heads = num_attention_heads or attention_head_dim
232
+
233
+ # Check inputs
234
+ if len(block_out_channels) != len(down_block_types):
235
+ raise ValueError(
236
+ 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}."
237
+ )
238
+
239
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
240
+ raise ValueError(
241
+ 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}."
242
+ )
243
+
244
+ if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
245
+ raise ValueError(
246
+ 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}."
247
+ )
248
+
249
+ if isinstance(transformer_layers_per_block, int):
250
+ transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
251
+
252
+ # input
253
+ conv_in_kernel = 3
254
+ conv_in_padding = (conv_in_kernel - 1) // 2
255
+ self.conv_in = nn.Conv2d(
256
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
257
+ )
258
+
259
+ # time
260
+ time_embed_dim = block_out_channels[0] * 4
261
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
262
+ timestep_input_dim = block_out_channels[0]
263
+ self.time_embedding = TimestepEmbedding(
264
+ timestep_input_dim,
265
+ time_embed_dim,
266
+ act_fn=act_fn,
267
+ )
268
+
269
+ if encoder_hid_dim_type is None and encoder_hid_dim is not None:
270
+ encoder_hid_dim_type = "text_proj"
271
+ self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
272
+ logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.")
273
+
274
+ if encoder_hid_dim is None and encoder_hid_dim_type is not None:
275
+ raise ValueError(
276
+ f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
277
+ )
278
+
279
+ if encoder_hid_dim_type == "text_proj":
280
+ self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
281
+ elif encoder_hid_dim_type == "text_image_proj":
282
+ # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
283
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
284
+ # case when `addition_embed_type == "text_image_proj"` (Kandinsky 2.1)`
285
+ self.encoder_hid_proj = TextImageProjection(
286
+ text_embed_dim=encoder_hid_dim,
287
+ image_embed_dim=cross_attention_dim,
288
+ cross_attention_dim=cross_attention_dim,
289
+ )
290
+
291
+ elif encoder_hid_dim_type is not None:
292
+ raise ValueError(
293
+ f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'."
294
+ )
295
+ else:
296
+ self.encoder_hid_proj = None
297
+
298
+ # class embedding
299
+ if class_embed_type is None and num_class_embeds is not None:
300
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
301
+ elif class_embed_type == "timestep":
302
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
303
+ elif class_embed_type == "identity":
304
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
305
+ elif class_embed_type == "projection":
306
+ if projection_class_embeddings_input_dim is None:
307
+ raise ValueError(
308
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
309
+ )
310
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
311
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
312
+ # 2. it projects from an arbitrary input dimension.
313
+ #
314
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
315
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
316
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
317
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
318
+ else:
319
+ self.class_embedding = None
320
+
321
+ if addition_embed_type == "text":
322
+ if encoder_hid_dim is not None:
323
+ text_time_embedding_from_dim = encoder_hid_dim
324
+ else:
325
+ text_time_embedding_from_dim = cross_attention_dim
326
+
327
+ self.add_embedding = TextTimeEmbedding(
328
+ text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads
329
+ )
330
+ elif addition_embed_type == "text_image":
331
+ # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
332
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
333
+ # case when `addition_embed_type == "text_image"` (Kandinsky 2.1)`
334
+ self.add_embedding = TextImageTimeEmbedding(
335
+ text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim
336
+ )
337
+ elif addition_embed_type == "text_time":
338
+ self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)
339
+ self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
340
+
341
+ elif addition_embed_type is not None:
342
+ raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.")
343
+
344
+ # control net conditioning embedding
345
+ self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
346
+ conditioning_embedding_channels=block_out_channels[0],
347
+ block_out_channels=conditioning_embedding_out_channels,
348
+ conditioning_channels=conditioning_channels,
349
+ )
350
+
351
+ self.down_blocks = nn.ModuleList([])
352
+ self.controlnet_down_blocks = nn.ModuleList([])
353
+
354
+ if isinstance(only_cross_attention, bool):
355
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
356
+
357
+ if isinstance(attention_head_dim, int):
358
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
359
+
360
+ if isinstance(num_attention_heads, int):
361
+ num_attention_heads = (num_attention_heads,) * len(down_block_types)
362
+
363
+ # down
364
+ output_channel = block_out_channels[0]
365
+
366
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
367
+ controlnet_block = zero_module(controlnet_block)
368
+ self.controlnet_down_blocks.append(controlnet_block)
369
+
370
+ for i, down_block_type in enumerate(down_block_types):
371
+ input_channel = output_channel
372
+ output_channel = block_out_channels[i]
373
+ is_final_block = i == len(block_out_channels) - 1
374
+
375
+ down_block = get_down_block(
376
+ down_block_type,
377
+ num_layers=layers_per_block,
378
+ transformer_layers_per_block=transformer_layers_per_block[i],
379
+ in_channels=input_channel,
380
+ out_channels=output_channel,
381
+ temb_channels=time_embed_dim,
382
+ add_downsample=not is_final_block,
383
+ resnet_eps=norm_eps,
384
+ resnet_act_fn=act_fn,
385
+ resnet_groups=norm_num_groups,
386
+ cross_attention_dim=cross_attention_dim,
387
+ num_attention_heads=num_attention_heads[i],
388
+ attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
389
+ downsample_padding=downsample_padding,
390
+ use_linear_projection=use_linear_projection,
391
+ only_cross_attention=only_cross_attention[i],
392
+ upcast_attention=upcast_attention,
393
+ resnet_time_scale_shift=resnet_time_scale_shift,
394
+ )
395
+ self.down_blocks.append(down_block)
396
+
397
+ for _ in range(layers_per_block):
398
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
399
+ controlnet_block = zero_module(controlnet_block)
400
+ self.controlnet_down_blocks.append(controlnet_block)
401
+
402
+ if not is_final_block:
403
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
404
+ controlnet_block = zero_module(controlnet_block)
405
+ self.controlnet_down_blocks.append(controlnet_block)
406
+
407
+ # mid
408
+ mid_block_channel = block_out_channels[-1]
409
+
410
+ controlnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)
411
+ controlnet_block = zero_module(controlnet_block)
412
+ self.controlnet_mid_block = controlnet_block
413
+
414
+ if mid_block_type == "UNetMidBlock2DCrossAttn":
415
+ self.mid_block = UNetMidBlock2DCrossAttn(
416
+ transformer_layers_per_block=transformer_layers_per_block[-1],
417
+ in_channels=mid_block_channel,
418
+ temb_channels=time_embed_dim,
419
+ resnet_eps=norm_eps,
420
+ resnet_act_fn=act_fn,
421
+ output_scale_factor=mid_block_scale_factor,
422
+ resnet_time_scale_shift=resnet_time_scale_shift,
423
+ cross_attention_dim=cross_attention_dim,
424
+ num_attention_heads=num_attention_heads[-1],
425
+ resnet_groups=norm_num_groups,
426
+ use_linear_projection=use_linear_projection,
427
+ upcast_attention=upcast_attention,
428
+ )
429
+ elif mid_block_type == "UNetMidBlock2D":
430
+ self.mid_block = UNetMidBlock2D(
431
+ in_channels=block_out_channels[-1],
432
+ temb_channels=time_embed_dim,
433
+ num_layers=0,
434
+ resnet_eps=norm_eps,
435
+ resnet_act_fn=act_fn,
436
+ output_scale_factor=mid_block_scale_factor,
437
+ resnet_groups=norm_num_groups,
438
+ resnet_time_scale_shift=resnet_time_scale_shift,
439
+ add_attention=False,
440
+ )
441
+ else:
442
+ raise ValueError(f"unknown mid_block_type : {mid_block_type}")
443
+
444
+ @classmethod
445
+ def from_unet(
446
+ cls,
447
+ unet: UNet2DConditionModel,
448
+ controlnet_conditioning_channel_order: str = "rgb",
449
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
450
+ load_weights_from_unet: bool = True,
451
+ conditioning_channels: int = 3,
452
+ ):
453
+ r"""
454
+ Instantiate a [`ControlNetModel`] from [`UNet2DConditionModel`].
455
+
456
+ Parameters:
457
+ unet (`UNet2DConditionModel`):
458
+ The UNet model weights to copy to the [`ControlNetModel`]. All configuration options are also copied
459
+ where applicable.
460
+ """
461
+ transformer_layers_per_block = (
462
+ unet.config.transformer_layers_per_block if "transformer_layers_per_block" in unet.config else 1
463
+ )
464
+ encoder_hid_dim = unet.config.encoder_hid_dim if "encoder_hid_dim" in unet.config else None
465
+ encoder_hid_dim_type = unet.config.encoder_hid_dim_type if "encoder_hid_dim_type" in unet.config else None
466
+ addition_embed_type = unet.config.addition_embed_type if "addition_embed_type" in unet.config else None
467
+ addition_time_embed_dim = (
468
+ unet.config.addition_time_embed_dim if "addition_time_embed_dim" in unet.config else None
469
+ )
470
+
471
+ controlnet = cls(
472
+ encoder_hid_dim=encoder_hid_dim,
473
+ encoder_hid_dim_type=encoder_hid_dim_type,
474
+ addition_embed_type=addition_embed_type,
475
+ addition_time_embed_dim=addition_time_embed_dim,
476
+ transformer_layers_per_block=transformer_layers_per_block,
477
+ in_channels=unet.config.in_channels,
478
+ flip_sin_to_cos=unet.config.flip_sin_to_cos,
479
+ freq_shift=unet.config.freq_shift,
480
+ down_block_types=unet.config.down_block_types,
481
+ only_cross_attention=unet.config.only_cross_attention,
482
+ block_out_channels=unet.config.block_out_channels,
483
+ layers_per_block=unet.config.layers_per_block,
484
+ downsample_padding=unet.config.downsample_padding,
485
+ mid_block_scale_factor=unet.config.mid_block_scale_factor,
486
+ act_fn=unet.config.act_fn,
487
+ norm_num_groups=unet.config.norm_num_groups,
488
+ norm_eps=unet.config.norm_eps,
489
+ cross_attention_dim=unet.config.cross_attention_dim,
490
+ attention_head_dim=unet.config.attention_head_dim,
491
+ num_attention_heads=unet.config.num_attention_heads,
492
+ use_linear_projection=unet.config.use_linear_projection,
493
+ class_embed_type=unet.config.class_embed_type,
494
+ num_class_embeds=unet.config.num_class_embeds,
495
+ upcast_attention=unet.config.upcast_attention,
496
+ resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
497
+ projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
498
+ mid_block_type=unet.config.mid_block_type,
499
+ controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
500
+ conditioning_embedding_out_channels=conditioning_embedding_out_channels,
501
+ conditioning_channels=conditioning_channels,
502
+ )
503
+
504
+ if load_weights_from_unet:
505
+ controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())
506
+ controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())
507
+ controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())
508
+
509
+ if controlnet.class_embedding:
510
+ controlnet.class_embedding.load_state_dict(unet.class_embedding.state_dict())
511
+
512
+ if hasattr(controlnet, "add_embedding"):
513
+ controlnet.add_embedding.load_state_dict(unet.add_embedding.state_dict())
514
+
515
+ controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict())
516
+ controlnet.mid_block.load_state_dict(unet.mid_block.state_dict())
517
+
518
+ return controlnet
519
+
520
+ @property
521
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
522
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
523
+ r"""
524
+ Returns:
525
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
526
+ indexed by its weight name.
527
+ """
528
+ # set recursively
529
+ processors = {}
530
+
531
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
532
+ if hasattr(module, "get_processor"):
533
+ processors[f"{name}.processor"] = module.get_processor()
534
+
535
+ for sub_name, child in module.named_children():
536
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
537
+
538
+ return processors
539
+
540
+ for name, module in self.named_children():
541
+ fn_recursive_add_processors(name, module, processors)
542
+
543
+ return processors
544
+
545
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
546
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
547
+ r"""
548
+ Sets the attention processor to use to compute attention.
549
+
550
+ Parameters:
551
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
552
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
553
+ for **all** `Attention` layers.
554
+
555
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
556
+ processor. This is strongly recommended when setting trainable attention processors.
557
+
558
+ """
559
+ count = len(self.attn_processors.keys())
560
+
561
+ if isinstance(processor, dict) and len(processor) != count:
562
+ raise ValueError(
563
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
564
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
565
+ )
566
+
567
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
568
+ if hasattr(module, "set_processor"):
569
+ if not isinstance(processor, dict):
570
+ module.set_processor(processor)
571
+ else:
572
+ module.set_processor(processor.pop(f"{name}.processor"))
573
+
574
+ for sub_name, child in module.named_children():
575
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
576
+
577
+ for name, module in self.named_children():
578
+ fn_recursive_attn_processor(name, module, processor)
579
+
580
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
581
+ def set_default_attn_processor(self):
582
+ """
583
+ Disables custom attention processors and sets the default attention implementation.
584
+ """
585
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
586
+ processor = AttnAddedKVProcessor()
587
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
588
+ processor = AttnProcessor()
589
+ else:
590
+ raise ValueError(
591
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
592
+ )
593
+
594
+ self.set_attn_processor(processor)
595
+
596
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attention_slice
597
+ def set_attention_slice(self, slice_size: Union[str, int, List[int]]) -> None:
598
+ r"""
599
+ Enable sliced attention computation.
600
+
601
+ When this option is enabled, the attention module splits the input tensor in slices to compute attention in
602
+ several steps. This is useful for saving some memory in exchange for a small decrease in speed.
603
+
604
+ Args:
605
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
606
+ When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
607
+ `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
608
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
609
+ must be a multiple of `slice_size`.
610
+ """
611
+ sliceable_head_dims = []
612
+
613
+ def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
614
+ if hasattr(module, "set_attention_slice"):
615
+ sliceable_head_dims.append(module.sliceable_head_dim)
616
+
617
+ for child in module.children():
618
+ fn_recursive_retrieve_sliceable_dims(child)
619
+
620
+ # retrieve number of attention layers
621
+ for module in self.children():
622
+ fn_recursive_retrieve_sliceable_dims(module)
623
+
624
+ num_sliceable_layers = len(sliceable_head_dims)
625
+
626
+ if slice_size == "auto":
627
+ # half the attention head size is usually a good trade-off between
628
+ # speed and memory
629
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
630
+ elif slice_size == "max":
631
+ # make smallest slice possible
632
+ slice_size = num_sliceable_layers * [1]
633
+
634
+ slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
635
+
636
+ if len(slice_size) != len(sliceable_head_dims):
637
+ raise ValueError(
638
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
639
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
640
+ )
641
+
642
+ for i in range(len(slice_size)):
643
+ size = slice_size[i]
644
+ dim = sliceable_head_dims[i]
645
+ if size is not None and size > dim:
646
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
647
+
648
+ # Recursively walk through all the children.
649
+ # Any children which exposes the set_attention_slice method
650
+ # gets the message
651
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
652
+ if hasattr(module, "set_attention_slice"):
653
+ module.set_attention_slice(slice_size.pop())
654
+
655
+ for child in module.children():
656
+ fn_recursive_set_attention_slice(child, slice_size)
657
+
658
+ reversed_slice_size = list(reversed(slice_size))
659
+ for module in self.children():
660
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
661
+
662
+ def _set_gradient_checkpointing(self, module, value: bool = False) -> None:
663
+ if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):
664
+ module.gradient_checkpointing = value
665
+
666
+ def forward(
667
+ self,
668
+ sample: torch.Tensor,
669
+ timestep: Union[torch.Tensor, float, int],
670
+ encoder_hidden_states: torch.Tensor,
671
+ controlnet_cond: torch.Tensor,
672
+ conditioning_scale: float = 1.0,
673
+ class_labels: Optional[torch.Tensor] = None,
674
+ timestep_cond: Optional[torch.Tensor] = None,
675
+ attention_mask: Optional[torch.Tensor] = None,
676
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
677
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
678
+ guess_mode: bool = False,
679
+ return_dict: bool = True,
680
+ ) -> Union[ControlNetOutput, Tuple[Tuple[torch.Tensor, ...], torch.Tensor]]:
681
+ """
682
+ The [`ControlNetModel`] forward method.
683
+
684
+ Args:
685
+ sample (`torch.Tensor`):
686
+ The noisy input tensor.
687
+ timestep (`Union[torch.Tensor, float, int]`):
688
+ The number of timesteps to denoise an input.
689
+ encoder_hidden_states (`torch.Tensor`):
690
+ The encoder hidden states.
691
+ controlnet_cond (`torch.Tensor`):
692
+ The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
693
+ conditioning_scale (`float`, defaults to `1.0`):
694
+ The scale factor for ControlNet outputs.
695
+ class_labels (`torch.Tensor`, *optional*, defaults to `None`):
696
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
697
+ timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
698
+ Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
699
+ timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
700
+ embeddings.
701
+ attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
702
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
703
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
704
+ negative values to the attention scores corresponding to "discard" tokens.
705
+ added_cond_kwargs (`dict`):
706
+ Additional conditions for the Stable Diffusion XL UNet.
707
+ cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
708
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
709
+ guess_mode (`bool`, defaults to `False`):
710
+ In this mode, the ControlNet encoder tries its best to recognize the input content of the input even if
711
+ you remove all prompts. A `guidance_scale` between 3.0 and 5.0 is recommended.
712
+ return_dict (`bool`, defaults to `True`):
713
+ Whether or not to return a [`~models.controlnets.controlnet.ControlNetOutput`] instead of a plain
714
+ tuple.
715
+
716
+ Returns:
717
+ [`~models.controlnets.controlnet.ControlNetOutput`] **or** `tuple`:
718
+ If `return_dict` is `True`, a [`~models.controlnets.controlnet.ControlNetOutput`] is returned,
719
+ otherwise a tuple is returned where the first element is the sample tensor.
720
+ """
721
+ # check channel order
722
+ channel_order = self.config.controlnet_conditioning_channel_order
723
+
724
+ if channel_order == "rgb":
725
+ # in rgb order by default
726
+ ...
727
+ elif channel_order == "bgr":
728
+ controlnet_cond = torch.flip(controlnet_cond, dims=[1])
729
+ else:
730
+ raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}")
731
+
732
+ # prepare attention_mask
733
+ if attention_mask is not None:
734
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
735
+ attention_mask = attention_mask.unsqueeze(1)
736
+
737
+ # 1. time
738
+ timesteps = timestep
739
+ if not torch.is_tensor(timesteps):
740
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
741
+ # This would be a good case for the `match` statement (Python 3.10+)
742
+ is_mps = sample.device.type == "mps"
743
+ if isinstance(timestep, float):
744
+ dtype = torch.float32 if is_mps else torch.float64
745
+ else:
746
+ dtype = torch.int32 if is_mps else torch.int64
747
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
748
+ elif len(timesteps.shape) == 0:
749
+ timesteps = timesteps[None].to(sample.device)
750
+
751
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
752
+ timesteps = timesteps.expand(sample.shape[0])
753
+
754
+ t_emb = self.time_proj(timesteps)
755
+
756
+ # timesteps does not contain any weights and will always return f32 tensors
757
+ # but time_embedding might actually be running in fp16. so we need to cast here.
758
+ # there might be better ways to encapsulate this.
759
+ t_emb = t_emb.to(dtype=sample.dtype)
760
+
761
+ emb = self.time_embedding(t_emb, timestep_cond)
762
+ aug_emb = None
763
+
764
+ if self.class_embedding is not None:
765
+ if class_labels is None:
766
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
767
+
768
+ if self.config.class_embed_type == "timestep":
769
+ class_labels = self.time_proj(class_labels)
770
+
771
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
772
+ emb = emb + class_emb
773
+
774
+ if self.config.addition_embed_type is not None:
775
+ if self.config.addition_embed_type == "text":
776
+ aug_emb = self.add_embedding(encoder_hidden_states)
777
+
778
+ elif self.config.addition_embed_type == "text_time":
779
+ if "text_embeds" not in added_cond_kwargs:
780
+ raise ValueError(
781
+ 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`"
782
+ )
783
+ text_embeds = added_cond_kwargs.get("text_embeds")
784
+ if "time_ids" not in added_cond_kwargs:
785
+ raise ValueError(
786
+ 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`"
787
+ )
788
+ time_ids = added_cond_kwargs.get("time_ids")
789
+ time_embeds = self.add_time_proj(time_ids.flatten())
790
+ time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
791
+
792
+ add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
793
+ add_embeds = add_embeds.to(emb.dtype)
794
+ aug_emb = self.add_embedding(add_embeds)
795
+
796
+ emb = emb + aug_emb if aug_emb is not None else emb
797
+
798
+ # 2. pre-process
799
+ sample = self.conv_in(sample)
800
+
801
+ controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
802
+ sample = sample + controlnet_cond
803
+
804
+ # 3. down
805
+ down_block_res_samples = (sample,)
806
+ for downsample_block in self.down_blocks:
807
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
808
+ sample, res_samples = downsample_block(
809
+ hidden_states=sample,
810
+ temb=emb,
811
+ encoder_hidden_states=encoder_hidden_states,
812
+ attention_mask=attention_mask,
813
+ cross_attention_kwargs=cross_attention_kwargs,
814
+ )
815
+ else:
816
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
817
+
818
+ down_block_res_samples += res_samples
819
+
820
+ # 4. mid
821
+ if self.mid_block is not None:
822
+ if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
823
+ sample = self.mid_block(
824
+ sample,
825
+ 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 = self.mid_block(sample, emb)
832
+
833
+ # 5. Control net blocks
834
+
835
+ controlnet_down_block_res_samples = ()
836
+
837
+ for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
838
+ down_block_res_sample = controlnet_block(down_block_res_sample)
839
+ controlnet_down_block_res_samples = controlnet_down_block_res_samples + (down_block_res_sample,)
840
+
841
+ down_block_res_samples = controlnet_down_block_res_samples
842
+
843
+ mid_block_res_sample = self.controlnet_mid_block(sample)
844
+
845
+ # 6. scaling
846
+ if guess_mode and not self.config.global_pool_conditions:
847
+ scales = torch.logspace(-1, 0, len(down_block_res_samples) + 1, device=sample.device) # 0.1 to 1.0
848
+ scales = scales * conditioning_scale
849
+ down_block_res_samples = [sample * scale for sample, scale in zip(down_block_res_samples, scales)]
850
+ mid_block_res_sample = mid_block_res_sample * scales[-1] # last one
851
+ else:
852
+ down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
853
+ mid_block_res_sample = mid_block_res_sample * conditioning_scale
854
+
855
+ if self.config.global_pool_conditions:
856
+ down_block_res_samples = [
857
+ torch.mean(sample, dim=(2, 3), keepdim=True) for sample in down_block_res_samples
858
+ ]
859
+ mid_block_res_sample = torch.mean(mid_block_res_sample, dim=(2, 3), keepdim=True)
860
+
861
+ if not return_dict:
862
+ return (down_block_res_samples, mid_block_res_sample)
863
+
864
+ return ControlNetOutput(
865
+ down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
866
+ )
867
+
868
+
869
+ def zero_module(module):
870
+ for p in module.parameters():
871
+ nn.init.zeros_(p)
872
+ return module
diffusion_pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b17ecb76c0dfd3a60896f1eb1783d248ded411c0f9ca9a610352046e0c435910
3
+ size 5004473134
image_processor.py ADDED
@@ -0,0 +1,991 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import math
16
+ import warnings
17
+ from typing import List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import PIL.Image
21
+ import torch
22
+ import torch.nn.functional as F
23
+ from PIL import Image, ImageFilter, ImageOps
24
+
25
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
26
+ from diffusers.utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate
27
+ # from .utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate
28
+
29
+
30
+ PipelineImageInput = Union[
31
+ PIL.Image.Image,
32
+ np.ndarray,
33
+ torch.FloatTensor,
34
+ List[PIL.Image.Image],
35
+ List[np.ndarray],
36
+ List[torch.FloatTensor],
37
+ ]
38
+
39
+ PipelineDepthInput = PipelineImageInput
40
+
41
+
42
+ class VaeImageProcessor(ConfigMixin):
43
+ """
44
+ Image processor for VAE.
45
+
46
+ Args:
47
+ do_resize (`bool`, *optional*, defaults to `True`):
48
+ Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
49
+ `height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
50
+ vae_scale_factor (`int`, *optional*, defaults to `8`):
51
+ VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
52
+ resample (`str`, *optional*, defaults to `lanczos`):
53
+ Resampling filter to use when resizing the image.
54
+ do_normalize (`bool`, *optional*, defaults to `True`):
55
+ Whether to normalize the image to [-1,1].
56
+ do_binarize (`bool`, *optional*, defaults to `False`):
57
+ Whether to binarize the image to 0/1.
58
+ do_convert_rgb (`bool`, *optional*, defaults to be `False`):
59
+ Whether to convert the images to RGB format.
60
+ do_convert_grayscale (`bool`, *optional*, defaults to be `False`):
61
+ Whether to convert the images to grayscale format.
62
+ """
63
+
64
+ config_name = CONFIG_NAME
65
+
66
+ @register_to_config
67
+ def __init__(
68
+ self,
69
+ do_resize: bool = True,
70
+ vae_scale_factor: int = 8,
71
+ resample: str = "lanczos",
72
+ do_normalize: bool = True,
73
+ do_binarize: bool = False,
74
+ do_convert_rgb: bool = False,
75
+ do_convert_grayscale: bool = False,
76
+ ):
77
+ super().__init__()
78
+ if do_convert_rgb and do_convert_grayscale:
79
+ raise ValueError(
80
+ "`do_convert_rgb` and `do_convert_grayscale` can not both be set to `True`,"
81
+ " if you intended to convert the image into RGB format, please set `do_convert_grayscale = False`.",
82
+ " if you intended to convert the image into grayscale format, please set `do_convert_rgb = False`",
83
+ )
84
+ self.config.do_convert_rgb = False
85
+
86
+ @staticmethod
87
+ def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
88
+ """
89
+ Convert a numpy image or a batch of images to a PIL image.
90
+ """
91
+ if images.ndim == 3:
92
+ images = images[None, ...]
93
+ images = (images * 255).round().astype("uint8")
94
+ if images.shape[-1] == 1:
95
+ # special case for grayscale (single channel) images
96
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
97
+ else:
98
+ pil_images = [Image.fromarray(image) for image in images]
99
+
100
+ return pil_images
101
+
102
+ @staticmethod
103
+ def pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
104
+ """
105
+ Convert a PIL image or a list of PIL images to NumPy arrays.
106
+ """
107
+ if not isinstance(images, list):
108
+ images = [images]
109
+ images = [np.array(image).astype(np.float32) / 255.0 for image in images]
110
+ images = np.stack(images, axis=0)
111
+
112
+ return images
113
+
114
+ @staticmethod
115
+ def numpy_to_pt(images: np.ndarray) -> torch.FloatTensor:
116
+ """
117
+ Convert a NumPy image to a PyTorch tensor.
118
+ """
119
+ if images.ndim == 3:
120
+ images = images[..., None]
121
+
122
+ images = torch.from_numpy(images.transpose(0, 3, 1, 2))
123
+ return images
124
+
125
+ @staticmethod
126
+ def pt_to_numpy(images: torch.FloatTensor) -> np.ndarray:
127
+ """
128
+ Convert a PyTorch tensor to a NumPy image.
129
+ """
130
+ images = images.cpu().permute(0, 2, 3, 1).float().numpy()
131
+ return images
132
+
133
+ @staticmethod
134
+ def normalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
135
+ """
136
+ Normalize an image array to [-1,1].
137
+ """
138
+ return 2.0 * images - 1.0
139
+
140
+ @staticmethod
141
+ def denormalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
142
+ """
143
+ Denormalize an image array to [0,1].
144
+ """
145
+ return (images / 2 + 0.5).clamp(0, 1)
146
+
147
+ @staticmethod
148
+ def convert_to_rgb(image: PIL.Image.Image) -> PIL.Image.Image:
149
+ """
150
+ Converts a PIL image to RGB format.
151
+ """
152
+ image = image.convert("RGB")
153
+
154
+ return image
155
+
156
+ @staticmethod
157
+ def convert_to_grayscale(image: PIL.Image.Image) -> PIL.Image.Image:
158
+ """
159
+ Converts a PIL image to grayscale format.
160
+ """
161
+ image = image.convert("L")
162
+
163
+ return image
164
+
165
+ @staticmethod
166
+ def blur(image: PIL.Image.Image, blur_factor: int = 4) -> PIL.Image.Image:
167
+ """
168
+ Applies Gaussian blur to an image.
169
+ """
170
+ image = image.filter(ImageFilter.GaussianBlur(blur_factor))
171
+
172
+ return image
173
+
174
+ @staticmethod
175
+ def get_crop_region(mask_image: PIL.Image.Image, width: int, height: int, pad=0):
176
+ """
177
+ Finds a rectangular region that contains all masked ares in an image, and expands region to match the aspect ratio of the original image;
178
+ for example, if user drew mask in a 128x32 region, and the dimensions for processing are 512x512, the region will be expanded to 128x128.
179
+
180
+ Args:
181
+ mask_image (PIL.Image.Image): Mask image.
182
+ width (int): Width of the image to be processed.
183
+ height (int): Height of the image to be processed.
184
+ pad (int, optional): Padding to be added to the crop region. Defaults to 0.
185
+
186
+ Returns:
187
+ tuple: (x1, y1, x2, y2) represent a rectangular region that contains all masked ares in an image and matches the original aspect ratio.
188
+ """
189
+
190
+ mask_image = mask_image.convert("L")
191
+ mask = np.array(mask_image)
192
+
193
+ # 1. find a rectangular region that contains all masked ares in an image
194
+ h, w = mask.shape
195
+ crop_left = 0
196
+ for i in range(w):
197
+ if not (mask[:, i] == 0).all():
198
+ break
199
+ crop_left += 1
200
+
201
+ crop_right = 0
202
+ for i in reversed(range(w)):
203
+ if not (mask[:, i] == 0).all():
204
+ break
205
+ crop_right += 1
206
+
207
+ crop_top = 0
208
+ for i in range(h):
209
+ if not (mask[i] == 0).all():
210
+ break
211
+ crop_top += 1
212
+
213
+ crop_bottom = 0
214
+ for i in reversed(range(h)):
215
+ if not (mask[i] == 0).all():
216
+ break
217
+ crop_bottom += 1
218
+
219
+ # 2. add padding to the crop region
220
+ x1, y1, x2, y2 = (
221
+ int(max(crop_left - pad, 0)),
222
+ int(max(crop_top - pad, 0)),
223
+ int(min(w - crop_right + pad, w)),
224
+ int(min(h - crop_bottom + pad, h)),
225
+ )
226
+
227
+ # 3. expands crop region to match the aspect ratio of the image to be processed
228
+ ratio_crop_region = (x2 - x1) / (y2 - y1)
229
+ ratio_processing = width / height
230
+
231
+ if ratio_crop_region > ratio_processing:
232
+ desired_height = (x2 - x1) / ratio_processing
233
+ desired_height_diff = int(desired_height - (y2 - y1))
234
+ y1 -= desired_height_diff // 2
235
+ y2 += desired_height_diff - desired_height_diff // 2
236
+ if y2 >= mask_image.height:
237
+ diff = y2 - mask_image.height
238
+ y2 -= diff
239
+ y1 -= diff
240
+ if y1 < 0:
241
+ y2 -= y1
242
+ y1 -= y1
243
+ if y2 >= mask_image.height:
244
+ y2 = mask_image.height
245
+ else:
246
+ desired_width = (y2 - y1) * ratio_processing
247
+ desired_width_diff = int(desired_width - (x2 - x1))
248
+ x1 -= desired_width_diff // 2
249
+ x2 += desired_width_diff - desired_width_diff // 2
250
+ if x2 >= mask_image.width:
251
+ diff = x2 - mask_image.width
252
+ x2 -= diff
253
+ x1 -= diff
254
+ if x1 < 0:
255
+ x2 -= x1
256
+ x1 -= x1
257
+ if x2 >= mask_image.width:
258
+ x2 = mask_image.width
259
+
260
+ return x1, y1, x2, y2
261
+
262
+ def _resize_and_fill(
263
+ self,
264
+ image: PIL.Image.Image,
265
+ width: int,
266
+ height: int,
267
+ ) -> PIL.Image.Image:
268
+ """
269
+ Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, filling empty with data from image.
270
+
271
+ Args:
272
+ image: The image to resize.
273
+ width: The width to resize the image to.
274
+ height: The height to resize the image to.
275
+ """
276
+
277
+ ratio = width / height
278
+ src_ratio = image.width / image.height
279
+
280
+ src_w = width if ratio < src_ratio else image.width * height // image.height
281
+ src_h = height if ratio >= src_ratio else image.height * width // image.width
282
+
283
+ resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION["lanczos"])
284
+ res = Image.new("RGB", (width, height))
285
+ res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
286
+
287
+ if ratio < src_ratio:
288
+ fill_height = height // 2 - src_h // 2
289
+ if fill_height > 0:
290
+ res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0))
291
+ res.paste(
292
+ resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)),
293
+ box=(0, fill_height + src_h),
294
+ )
295
+ elif ratio > src_ratio:
296
+ fill_width = width // 2 - src_w // 2
297
+ if fill_width > 0:
298
+ res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0))
299
+ res.paste(
300
+ resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)),
301
+ box=(fill_width + src_w, 0),
302
+ )
303
+
304
+ return res
305
+
306
+ def _resize_and_crop(
307
+ self,
308
+ image: PIL.Image.Image,
309
+ width: int,
310
+ height: int,
311
+ ) -> PIL.Image.Image:
312
+ """
313
+ Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, cropping the excess.
314
+
315
+ Args:
316
+ image: The image to resize.
317
+ width: The width to resize the image to.
318
+ height: The height to resize the image to.
319
+ """
320
+ ratio = width / height
321
+ src_ratio = image.width / image.height
322
+
323
+ src_w = width if ratio > src_ratio else image.width * height // image.height
324
+ src_h = height if ratio <= src_ratio else image.height * width // image.width
325
+
326
+ resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION["lanczos"])
327
+ res = Image.new("RGB", (width, height))
328
+ res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
329
+ return res
330
+
331
+ def resize(
332
+ self,
333
+ image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
334
+ height: int,
335
+ width: int,
336
+ resize_mode: str = "default", # "default", "fill", "crop"
337
+ ) -> Union[PIL.Image.Image, np.ndarray, torch.Tensor]:
338
+ """
339
+ Resize image.
340
+
341
+ Args:
342
+ image (`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
343
+ The image input, can be a PIL image, numpy array or pytorch tensor.
344
+ height (`int`):
345
+ The height to resize to.
346
+ width (`int`):
347
+ The width to resize to.
348
+ resize_mode (`str`, *optional*, defaults to `default`):
349
+ The resize mode to use, can be one of `default` or `fill`. If `default`, will resize the image to fit
350
+ within the specified width and height, and it may not maintaining the original aspect ratio.
351
+ If `fill`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
352
+ within the dimensions, filling empty with data from image.
353
+ If `crop`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
354
+ within the dimensions, cropping the excess.
355
+ Note that resize_mode `fill` and `crop` are only supported for PIL image input.
356
+
357
+ Returns:
358
+ `PIL.Image.Image`, `np.ndarray` or `torch.Tensor`:
359
+ The resized image.
360
+ """
361
+ if resize_mode != "default" and not isinstance(image, PIL.Image.Image):
362
+ raise ValueError(f"Only PIL image input is supported for resize_mode {resize_mode}")
363
+ if isinstance(image, PIL.Image.Image):
364
+ if resize_mode == "default":
365
+ image = image.resize((width, height), resample=PIL_INTERPOLATION[self.config.resample])
366
+ elif resize_mode == "fill":
367
+ image = self._resize_and_fill(image, width, height)
368
+ elif resize_mode == "crop":
369
+ image = self._resize_and_crop(image, width, height)
370
+ else:
371
+ raise ValueError(f"resize_mode {resize_mode} is not supported")
372
+
373
+ elif isinstance(image, torch.Tensor):
374
+ image = torch.nn.functional.interpolate(
375
+ image,
376
+ size=(height, width),
377
+ )
378
+ elif isinstance(image, np.ndarray):
379
+ image = self.numpy_to_pt(image)
380
+ image = torch.nn.functional.interpolate(
381
+ image,
382
+ size=(height, width),
383
+ )
384
+ image = self.pt_to_numpy(image)
385
+ return image
386
+
387
+ def binarize(self, image: PIL.Image.Image) -> PIL.Image.Image:
388
+ """
389
+ Create a mask.
390
+
391
+ Args:
392
+ image (`PIL.Image.Image`):
393
+ The image input, should be a PIL image.
394
+
395
+ Returns:
396
+ `PIL.Image.Image`:
397
+ The binarized image. Values less than 0.5 are set to 0, values greater than 0.5 are set to 1.
398
+ """
399
+ image[image < 0.5] = 0
400
+ image[image >= 0.5] = 1
401
+
402
+ return image
403
+
404
+ def get_default_height_width(
405
+ self,
406
+ image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
407
+ height: Optional[int] = None,
408
+ width: Optional[int] = None,
409
+ ) -> Tuple[int, int]:
410
+ """
411
+ This function return the height and width that are downscaled to the next integer multiple of
412
+ `vae_scale_factor`.
413
+
414
+ Args:
415
+ image(`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
416
+ The image input, can be a PIL image, numpy array or pytorch tensor. if it is a numpy array, should have
417
+ shape `[batch, height, width]` or `[batch, height, width, channel]` if it is a pytorch tensor, should
418
+ have shape `[batch, channel, height, width]`.
419
+ height (`int`, *optional*, defaults to `None`):
420
+ The height in preprocessed image. If `None`, will use the height of `image` input.
421
+ width (`int`, *optional*`, defaults to `None`):
422
+ The width in preprocessed. If `None`, will use the width of the `image` input.
423
+ """
424
+
425
+ if height is None:
426
+ if isinstance(image, PIL.Image.Image):
427
+ height = image.height
428
+ elif isinstance(image, torch.Tensor):
429
+ height = image.shape[2]
430
+ else:
431
+ height = image.shape[1]
432
+
433
+ if width is None:
434
+ if isinstance(image, PIL.Image.Image):
435
+ width = image.width
436
+ elif isinstance(image, torch.Tensor):
437
+ width = image.shape[3]
438
+ else:
439
+ width = image.shape[2]
440
+
441
+ width, height = (
442
+ x - x % self.config.vae_scale_factor for x in (width, height)
443
+ ) # resize to integer multiple of vae_scale_factor
444
+
445
+ return height, width
446
+
447
+ def preprocess(
448
+ self,
449
+ image: PipelineImageInput,
450
+ height: Optional[int] = None,
451
+ width: Optional[int] = None,
452
+ resize_mode: str = "default", # "default", "fill", "crop"
453
+ crops_coords: Optional[Tuple[int, int, int, int]] = None,
454
+ ) -> torch.Tensor:
455
+ """
456
+ Preprocess the image input.
457
+
458
+ Args:
459
+ image (`pipeline_image_input`):
460
+ The image input, accepted formats are PIL images, NumPy arrays, PyTorch tensors; Also accept list of supported formats.
461
+ height (`int`, *optional*, defaults to `None`):
462
+ The height in preprocessed image. If `None`, will use the `get_default_height_width()` to get default height.
463
+ width (`int`, *optional*`, defaults to `None`):
464
+ The width in preprocessed. If `None`, will use get_default_height_width()` to get the default width.
465
+ resize_mode (`str`, *optional*, defaults to `default`):
466
+ The resize mode, can be one of `default` or `fill`. If `default`, will resize the image to fit
467
+ within the specified width and height, and it may not maintaining the original aspect ratio.
468
+ If `fill`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
469
+ within the dimensions, filling empty with data from image.
470
+ If `crop`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
471
+ within the dimensions, cropping the excess.
472
+ Note that resize_mode `fill` and `crop` are only supported for PIL image input.
473
+ crops_coords (`List[Tuple[int, int, int, int]]`, *optional*, defaults to `None`):
474
+ The crop coordinates for each image in the batch. If `None`, will not crop the image.
475
+ """
476
+ supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
477
+
478
+ # Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
479
+ if self.config.do_convert_grayscale and isinstance(image, (torch.Tensor, np.ndarray)) and image.ndim == 3:
480
+ if isinstance(image, torch.Tensor):
481
+ # if image is a pytorch tensor could have 2 possible shapes:
482
+ # 1. batch x height x width: we should insert the channel dimension at position 1
483
+ # 2. channel x height x width: we should insert batch dimension at position 0,
484
+ # however, since both channel and batch dimension has same size 1, it is same to insert at position 1
485
+ # for simplicity, we insert a dimension of size 1 at position 1 for both cases
486
+ image = image.unsqueeze(1)
487
+ else:
488
+ # if it is a numpy array, it could have 2 possible shapes:
489
+ # 1. batch x height x width: insert channel dimension on last position
490
+ # 2. height x width x channel: insert batch dimension on first position
491
+ if image.shape[-1] == 1:
492
+ image = np.expand_dims(image, axis=0)
493
+ else:
494
+ image = np.expand_dims(image, axis=-1)
495
+
496
+ if isinstance(image, supported_formats):
497
+ image = [image]
498
+ elif not (isinstance(image, list) and all(isinstance(i, supported_formats) for i in image)):
499
+ raise ValueError(
500
+ f"Input is in incorrect format: {[type(i) for i in image]}. Currently, we only support {', '.join(supported_formats)}"
501
+ )
502
+
503
+ if isinstance(image[0], PIL.Image.Image):
504
+ if crops_coords is not None:
505
+ image = [i.crop(crops_coords) for i in image]
506
+ if self.config.do_resize:
507
+ height, width = self.get_default_height_width(image[0], height, width)
508
+ image = [self.resize(i, height, width, resize_mode=resize_mode) for i in image]
509
+ if self.config.do_convert_rgb:
510
+ image = [self.convert_to_rgb(i) for i in image]
511
+ elif self.config.do_convert_grayscale:
512
+ image = [self.convert_to_grayscale(i) for i in image]
513
+ image = self.pil_to_numpy(image) # to np
514
+ image = self.numpy_to_pt(image) # to pt
515
+
516
+ elif isinstance(image[0], np.ndarray):
517
+ image = np.concatenate(image, axis=0) if image[0].ndim == 4 else np.stack(image, axis=0)
518
+
519
+ image = self.numpy_to_pt(image)
520
+
521
+ height, width = self.get_default_height_width(image, height, width)
522
+ if self.config.do_resize:
523
+ image = self.resize(image, height, width)
524
+
525
+ elif isinstance(image[0], torch.Tensor):
526
+ image = torch.cat(image, axis=0) if image[0].ndim == 4 else torch.stack(image, axis=0)
527
+
528
+ if self.config.do_convert_grayscale and image.ndim == 3:
529
+ image = image.unsqueeze(1)
530
+
531
+ channel = image.shape[1]
532
+ # don't need any preprocess if the image is latents
533
+ if channel >= 4:
534
+ return image
535
+
536
+ height, width = self.get_default_height_width(image, height, width)
537
+ if self.config.do_resize:
538
+ image = self.resize(image, height, width)
539
+
540
+ # expected range [0,1], normalize to [-1,1]
541
+ do_normalize = self.config.do_normalize
542
+ if do_normalize and image.min() < 0:
543
+ warnings.warn(
544
+ "Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
545
+ f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]",
546
+ FutureWarning,
547
+ )
548
+ do_normalize = False
549
+
550
+ if do_normalize:
551
+ image = self.normalize(image)
552
+
553
+ if self.config.do_binarize:
554
+ image = self.binarize(image)
555
+
556
+ return image
557
+
558
+ def postprocess(
559
+ self,
560
+ image: torch.FloatTensor,
561
+ output_type: str = "pil",
562
+ do_denormalize: Optional[List[bool]] = None,
563
+ ) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
564
+ """
565
+ Postprocess the image output from tensor to `output_type`.
566
+
567
+ Args:
568
+ image (`torch.FloatTensor`):
569
+ The image input, should be a pytorch tensor with shape `B x C x H x W`.
570
+ output_type (`str`, *optional*, defaults to `pil`):
571
+ The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
572
+ do_denormalize (`List[bool]`, *optional*, defaults to `None`):
573
+ Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
574
+ `VaeImageProcessor` config.
575
+
576
+ Returns:
577
+ `PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
578
+ The postprocessed image.
579
+ """
580
+ if not isinstance(image, torch.Tensor):
581
+ raise ValueError(
582
+ f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
583
+ )
584
+ if output_type not in ["latent", "pt", "np", "pil"]:
585
+ deprecation_message = (
586
+ f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
587
+ "`pil`, `np`, `pt`, `latent`"
588
+ )
589
+ deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
590
+ output_type = "np"
591
+
592
+ if output_type == "latent":
593
+ return image
594
+
595
+ if do_denormalize is None:
596
+ do_denormalize = [self.config.do_normalize] * image.shape[0]
597
+
598
+ image = torch.stack(
599
+ [self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
600
+ )
601
+
602
+ if output_type == "pt":
603
+ return image
604
+
605
+ image = self.pt_to_numpy(image)
606
+
607
+ if output_type == "np":
608
+ return image
609
+
610
+ if output_type == "pil":
611
+ return self.numpy_to_pil(image)
612
+
613
+ def apply_overlay(
614
+ self,
615
+ mask: PIL.Image.Image,
616
+ init_image: PIL.Image.Image,
617
+ image: PIL.Image.Image,
618
+ crop_coords: Optional[Tuple[int, int, int, int]] = None,
619
+ ) -> PIL.Image.Image:
620
+ """
621
+ overlay the inpaint output to the original image
622
+ """
623
+
624
+ width, height = image.width, image.height
625
+
626
+ init_image = self.resize(init_image, width=width, height=height)
627
+ mask = self.resize(mask, width=width, height=height)
628
+
629
+ init_image_masked = PIL.Image.new("RGBa", (width, height))
630
+ init_image_masked.paste(init_image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(mask.convert("L")))
631
+ init_image_masked = init_image_masked.convert("RGBA")
632
+
633
+ if crop_coords is not None:
634
+ x, y, x2, y2 = crop_coords
635
+ w = x2 - x
636
+ h = y2 - y
637
+ base_image = PIL.Image.new("RGBA", (width, height))
638
+ image = self.resize(image, height=h, width=w, resize_mode="crop")
639
+ base_image.paste(image, (x, y))
640
+ image = base_image.convert("RGB")
641
+
642
+ image = image.convert("RGBA")
643
+ image.alpha_composite(init_image_masked)
644
+ image = image.convert("RGB")
645
+
646
+ return image
647
+
648
+
649
+ class VaeImageProcessorLDM3D(VaeImageProcessor):
650
+ """
651
+ Image processor for VAE LDM3D.
652
+
653
+ Args:
654
+ do_resize (`bool`, *optional*, defaults to `True`):
655
+ Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
656
+ vae_scale_factor (`int`, *optional*, defaults to `8`):
657
+ VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
658
+ resample (`str`, *optional*, defaults to `lanczos`):
659
+ Resampling filter to use when resizing the image.
660
+ do_normalize (`bool`, *optional*, defaults to `True`):
661
+ Whether to normalize the image to [-1,1].
662
+ """
663
+
664
+ config_name = CONFIG_NAME
665
+
666
+ @register_to_config
667
+ def __init__(
668
+ self,
669
+ do_resize: bool = True,
670
+ vae_scale_factor: int = 8,
671
+ resample: str = "lanczos",
672
+ do_normalize: bool = True,
673
+ ):
674
+ super().__init__()
675
+
676
+ @staticmethod
677
+ def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
678
+ """
679
+ Convert a NumPy image or a batch of images to a PIL image.
680
+ """
681
+ if images.ndim == 3:
682
+ images = images[None, ...]
683
+ images = (images * 255).round().astype("uint8")
684
+ if images.shape[-1] == 1:
685
+ # special case for grayscale (single channel) images
686
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
687
+ else:
688
+ pil_images = [Image.fromarray(image[:, :, :3]) for image in images]
689
+
690
+ return pil_images
691
+
692
+ @staticmethod
693
+ def depth_pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
694
+ """
695
+ Convert a PIL image or a list of PIL images to NumPy arrays.
696
+ """
697
+ if not isinstance(images, list):
698
+ images = [images]
699
+
700
+ images = [np.array(image).astype(np.float32) / (2**16 - 1) for image in images]
701
+ images = np.stack(images, axis=0)
702
+ return images
703
+
704
+ @staticmethod
705
+ def rgblike_to_depthmap(image: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
706
+ """
707
+ Args:
708
+ image: RGB-like depth image
709
+
710
+ Returns: depth map
711
+
712
+ """
713
+ return image[:, :, 1] * 2**8 + image[:, :, 2]
714
+
715
+ def numpy_to_depth(self, images: np.ndarray) -> List[PIL.Image.Image]:
716
+ """
717
+ Convert a NumPy depth image or a batch of images to a PIL image.
718
+ """
719
+ if images.ndim == 3:
720
+ images = images[None, ...]
721
+ images_depth = images[:, :, :, 3:]
722
+ if images.shape[-1] == 6:
723
+ images_depth = (images_depth * 255).round().astype("uint8")
724
+ pil_images = [
725
+ Image.fromarray(self.rgblike_to_depthmap(image_depth), mode="I;16") for image_depth in images_depth
726
+ ]
727
+ elif images.shape[-1] == 4:
728
+ images_depth = (images_depth * 65535.0).astype(np.uint16)
729
+ pil_images = [Image.fromarray(image_depth, mode="I;16") for image_depth in images_depth]
730
+ else:
731
+ raise Exception("Not supported")
732
+
733
+ return pil_images
734
+
735
+ def postprocess(
736
+ self,
737
+ image: torch.FloatTensor,
738
+ output_type: str = "pil",
739
+ do_denormalize: Optional[List[bool]] = None,
740
+ ) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
741
+ """
742
+ Postprocess the image output from tensor to `output_type`.
743
+
744
+ Args:
745
+ image (`torch.FloatTensor`):
746
+ The image input, should be a pytorch tensor with shape `B x C x H x W`.
747
+ output_type (`str`, *optional*, defaults to `pil`):
748
+ The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
749
+ do_denormalize (`List[bool]`, *optional*, defaults to `None`):
750
+ Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
751
+ `VaeImageProcessor` config.
752
+
753
+ Returns:
754
+ `PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
755
+ The postprocessed image.
756
+ """
757
+ if not isinstance(image, torch.Tensor):
758
+ raise ValueError(
759
+ f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
760
+ )
761
+ if output_type not in ["latent", "pt", "np", "pil"]:
762
+ deprecation_message = (
763
+ f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
764
+ "`pil`, `np`, `pt`, `latent`"
765
+ )
766
+ deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
767
+ output_type = "np"
768
+
769
+ if do_denormalize is None:
770
+ do_denormalize = [self.config.do_normalize] * image.shape[0]
771
+
772
+ image = torch.stack(
773
+ [self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
774
+ )
775
+
776
+ image = self.pt_to_numpy(image)
777
+
778
+ if output_type == "np":
779
+ if image.shape[-1] == 6:
780
+ image_depth = np.stack([self.rgblike_to_depthmap(im[:, :, 3:]) for im in image], axis=0)
781
+ else:
782
+ image_depth = image[:, :, :, 3:]
783
+ return image[:, :, :, :3], image_depth
784
+
785
+ if output_type == "pil":
786
+ return self.numpy_to_pil(image), self.numpy_to_depth(image)
787
+ else:
788
+ raise Exception(f"This type {output_type} is not supported")
789
+
790
+ def preprocess(
791
+ self,
792
+ rgb: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
793
+ depth: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
794
+ height: Optional[int] = None,
795
+ width: Optional[int] = None,
796
+ target_res: Optional[int] = None,
797
+ ) -> torch.Tensor:
798
+ """
799
+ Preprocess the image input. Accepted formats are PIL images, NumPy arrays or PyTorch tensors.
800
+ """
801
+ supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
802
+
803
+ # Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
804
+ if self.config.do_convert_grayscale and isinstance(rgb, (torch.Tensor, np.ndarray)) and rgb.ndim == 3:
805
+ raise Exception("This is not yet supported")
806
+
807
+ if isinstance(rgb, supported_formats):
808
+ rgb = [rgb]
809
+ depth = [depth]
810
+ elif not (isinstance(rgb, list) and all(isinstance(i, supported_formats) for i in rgb)):
811
+ raise ValueError(
812
+ f"Input is in incorrect format: {[type(i) for i in rgb]}. Currently, we only support {', '.join(supported_formats)}"
813
+ )
814
+
815
+ if isinstance(rgb[0], PIL.Image.Image):
816
+ if self.config.do_convert_rgb:
817
+ raise Exception("This is not yet supported")
818
+ # rgb = [self.convert_to_rgb(i) for i in rgb]
819
+ # depth = [self.convert_to_depth(i) for i in depth] #TODO define convert_to_depth
820
+ if self.config.do_resize or target_res:
821
+ height, width = self.get_default_height_width(rgb[0], height, width) if not target_res else target_res
822
+ rgb = [self.resize(i, height, width) for i in rgb]
823
+ depth = [self.resize(i, height, width) for i in depth]
824
+ rgb = self.pil_to_numpy(rgb) # to np
825
+ rgb = self.numpy_to_pt(rgb) # to pt
826
+
827
+ depth = self.depth_pil_to_numpy(depth) # to np
828
+ depth = self.numpy_to_pt(depth) # to pt
829
+
830
+ elif isinstance(rgb[0], np.ndarray):
831
+ rgb = np.concatenate(rgb, axis=0) if rgb[0].ndim == 4 else np.stack(rgb, axis=0)
832
+ rgb = self.numpy_to_pt(rgb)
833
+ height, width = self.get_default_height_width(rgb, height, width)
834
+ if self.config.do_resize:
835
+ rgb = self.resize(rgb, height, width)
836
+
837
+ depth = np.concatenate(depth, axis=0) if rgb[0].ndim == 4 else np.stack(depth, axis=0)
838
+ depth = self.numpy_to_pt(depth)
839
+ height, width = self.get_default_height_width(depth, height, width)
840
+ if self.config.do_resize:
841
+ depth = self.resize(depth, height, width)
842
+
843
+ elif isinstance(rgb[0], torch.Tensor):
844
+ raise Exception("This is not yet supported")
845
+ # rgb = torch.cat(rgb, axis=0) if rgb[0].ndim == 4 else torch.stack(rgb, axis=0)
846
+
847
+ # if self.config.do_convert_grayscale and rgb.ndim == 3:
848
+ # rgb = rgb.unsqueeze(1)
849
+
850
+ # channel = rgb.shape[1]
851
+
852
+ # height, width = self.get_default_height_width(rgb, height, width)
853
+ # if self.config.do_resize:
854
+ # rgb = self.resize(rgb, height, width)
855
+
856
+ # depth = torch.cat(depth, axis=0) if depth[0].ndim == 4 else torch.stack(depth, axis=0)
857
+
858
+ # if self.config.do_convert_grayscale and depth.ndim == 3:
859
+ # depth = depth.unsqueeze(1)
860
+
861
+ # channel = depth.shape[1]
862
+ # # don't need any preprocess if the image is latents
863
+ # if depth == 4:
864
+ # return rgb, depth
865
+
866
+ # height, width = self.get_default_height_width(depth, height, width)
867
+ # if self.config.do_resize:
868
+ # depth = self.resize(depth, height, width)
869
+ # expected range [0,1], normalize to [-1,1]
870
+ do_normalize = self.config.do_normalize
871
+ if rgb.min() < 0 and do_normalize:
872
+ warnings.warn(
873
+ "Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
874
+ f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{rgb.min()},{rgb.max()}]",
875
+ FutureWarning,
876
+ )
877
+ do_normalize = False
878
+
879
+ if do_normalize:
880
+ rgb = self.normalize(rgb)
881
+ depth = self.normalize(depth)
882
+
883
+ if self.config.do_binarize:
884
+ rgb = self.binarize(rgb)
885
+ depth = self.binarize(depth)
886
+
887
+ return rgb, depth
888
+
889
+
890
+ class IPAdapterMaskProcessor(VaeImageProcessor):
891
+ """
892
+ Image processor for IP Adapter image masks.
893
+
894
+ Args:
895
+ do_resize (`bool`, *optional*, defaults to `True`):
896
+ Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
897
+ vae_scale_factor (`int`, *optional*, defaults to `8`):
898
+ VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
899
+ resample (`str`, *optional*, defaults to `lanczos`):
900
+ Resampling filter to use when resizing the image.
901
+ do_normalize (`bool`, *optional*, defaults to `False`):
902
+ Whether to normalize the image to [-1,1].
903
+ do_binarize (`bool`, *optional*, defaults to `True`):
904
+ Whether to binarize the image to 0/1.
905
+ do_convert_grayscale (`bool`, *optional*, defaults to be `True`):
906
+ Whether to convert the images to grayscale format.
907
+
908
+ """
909
+
910
+ config_name = CONFIG_NAME
911
+
912
+ @register_to_config
913
+ def __init__(
914
+ self,
915
+ do_resize: bool = True,
916
+ vae_scale_factor: int = 8,
917
+ resample: str = "lanczos",
918
+ do_normalize: bool = False,
919
+ do_binarize: bool = True,
920
+ do_convert_grayscale: bool = True,
921
+ ):
922
+ super().__init__(
923
+ do_resize=do_resize,
924
+ vae_scale_factor=vae_scale_factor,
925
+ resample=resample,
926
+ do_normalize=do_normalize,
927
+ do_binarize=do_binarize,
928
+ do_convert_grayscale=do_convert_grayscale,
929
+ )
930
+
931
+ @staticmethod
932
+ def downsample(mask: torch.FloatTensor, batch_size: int, num_queries: int, value_embed_dim: int):
933
+ """
934
+ Downsamples the provided mask tensor to match the expected dimensions for scaled dot-product attention.
935
+ If the aspect ratio of the mask does not match the aspect ratio of the output image, a warning is issued.
936
+
937
+ Args:
938
+ mask (`torch.FloatTensor`):
939
+ The input mask tensor generated with `IPAdapterMaskProcessor.preprocess()`.
940
+ batch_size (`int`):
941
+ The batch size.
942
+ num_queries (`int`):
943
+ The number of queries.
944
+ value_embed_dim (`int`):
945
+ The dimensionality of the value embeddings.
946
+
947
+ Returns:
948
+ `torch.FloatTensor`:
949
+ The downsampled mask tensor.
950
+
951
+ """
952
+ o_h = mask.shape[1]
953
+ o_w = mask.shape[2]
954
+ ratio = o_w / o_h
955
+ mask_h = int(math.sqrt(num_queries / ratio))
956
+ mask_h = int(mask_h) + int((num_queries % int(mask_h)) != 0)
957
+ mask_w = num_queries // mask_h
958
+
959
+ mask_downsample = F.interpolate(mask.unsqueeze(0), size=(mask_h, mask_w), mode="bicubic").squeeze(0)
960
+
961
+ # Repeat batch_size times
962
+ if mask_downsample.shape[0] < batch_size:
963
+ mask_downsample = mask_downsample.repeat(batch_size, 1, 1)
964
+
965
+ mask_downsample = mask_downsample.view(mask_downsample.shape[0], -1)
966
+
967
+ downsampled_area = mask_h * mask_w
968
+ # If the output image and the mask do not have the same aspect ratio, tensor shapes will not match
969
+ # Pad tensor if downsampled_mask.shape[1] is smaller than num_queries
970
+ if downsampled_area < num_queries:
971
+ warnings.warn(
972
+ "The aspect ratio of the mask does not match the aspect ratio of the output image. "
973
+ "Please update your masks or adjust the output size for optimal performance.",
974
+ UserWarning,
975
+ )
976
+ mask_downsample = F.pad(mask_downsample, (0, num_queries - mask_downsample.shape[1]), value=0.0)
977
+ # Discard last embeddings if downsampled_mask.shape[1] is bigger than num_queries
978
+ if downsampled_area > num_queries:
979
+ warnings.warn(
980
+ "The aspect ratio of the mask does not match the aspect ratio of the output image. "
981
+ "Please update your masks or adjust the output size for optimal performance.",
982
+ UserWarning,
983
+ )
984
+ mask_downsample = mask_downsample[:, :num_queries]
985
+
986
+ # Repeat last dimension to match SDPA output shape
987
+ mask_downsample = mask_downsample.view(mask_downsample.shape[0], mask_downsample.shape[1], 1).repeat(
988
+ 1, 1, value_embed_dim
989
+ )
990
+
991
+ return mask_downsample
pipeline_controlnet_sd_xl.py ADDED
@@ -0,0 +1,1601 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ import inspect
17
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import PIL.Image
21
+ import torch
22
+ import torch.nn.functional as F
23
+ from transformers import (
24
+ CLIPImageProcessor,
25
+ CLIPTextModel,
26
+ CLIPTextModelWithProjection,
27
+ CLIPTokenizer,
28
+ CLIPVisionModelWithProjection,
29
+ )
30
+
31
+ from diffusers.utils.import_utils import is_invisible_watermark_available
32
+
33
+ from image_processor import PipelineImageInput, VaeImageProcessor
34
+ from diffusers.loaders import (
35
+ FromSingleFileMixin,
36
+ IPAdapterMixin,
37
+ StableDiffusionXLLoraLoaderMixin,
38
+ TextualInversionLoaderMixin,
39
+ )
40
+ from controlnet import ControlNetModel
41
+ # from diffusers.models import AutoencoderKL, ControlNetModel, ImageProjection, UNet2DConditionModel
42
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
43
+ from diffusers.models.attention_processor import (
44
+ AttnProcessor2_0,
45
+ LoRAAttnProcessor2_0,
46
+ LoRAXFormersAttnProcessor,
47
+ XFormersAttnProcessor,
48
+ )
49
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
50
+ from diffusers.schedulers import KarrasDiffusionSchedulers
51
+ from diffusers.utils import (
52
+ USE_PEFT_BACKEND,
53
+ deprecate,
54
+ logging,
55
+ replace_example_docstring,
56
+ scale_lora_layers,
57
+ unscale_lora_layers,
58
+ )
59
+ from diffusers.utils.torch_utils import is_compiled_module, is_torch_version, randn_tensor
60
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
61
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
62
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
63
+
64
+ if is_invisible_watermark_available():
65
+ from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
66
+
67
+ from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel
68
+
69
+
70
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
71
+
72
+
73
+ EXAMPLE_DOC_STRING = """
74
+ Examples:
75
+ ```py
76
+ >>> # !pip install opencv-python transformers accelerate
77
+ >>> from diffusers import StableDiffusionXLControlNetPipeline, ControlNetModel, AutoencoderKL
78
+ >>> from diffusers.utils import load_image
79
+ >>> import numpy as np
80
+ >>> import torch
81
+
82
+ >>> import cv2
83
+ >>> from PIL import Image
84
+
85
+ >>> prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
86
+ >>> negative_prompt = "low quality, bad quality, sketches"
87
+
88
+ >>> # download an image
89
+ >>> image = load_image(
90
+ ... "https://hf.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
91
+ ... )
92
+
93
+ >>> # initialize the models and pipeline
94
+ >>> controlnet_conditioning_scale = 0.5 # recommended for good generalization
95
+ >>> controlnet = ControlNetModel.from_pretrained(
96
+ ... "diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16
97
+ ... )
98
+ >>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
99
+ >>> pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
100
+ ... "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, vae=vae, torch_dtype=torch.float16
101
+ ... )
102
+ >>> pipe.enable_model_cpu_offload()
103
+
104
+ >>> # get canny image
105
+ >>> image = np.array(image)
106
+ >>> image = cv2.Canny(image, 100, 200)
107
+ >>> image = image[:, :, None]
108
+ >>> image = np.concatenate([image, image, image], axis=2)
109
+ >>> canny_image = Image.fromarray(image)
110
+
111
+ >>> # generate image
112
+ >>> image = pipe(
113
+ ... prompt, controlnet_conditioning_scale=controlnet_conditioning_scale, image=canny_image
114
+ ... ).images[0]
115
+ ```
116
+ """
117
+
118
+
119
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
120
+ def retrieve_timesteps(
121
+ scheduler,
122
+ num_inference_steps: Optional[int] = None,
123
+ device: Optional[Union[str, torch.device]] = None,
124
+ timesteps: Optional[List[int]] = None,
125
+ sigmas: Optional[List[float]] = None,
126
+ **kwargs,
127
+ ):
128
+ r"""
129
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
130
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
131
+
132
+ Args:
133
+ scheduler (`SchedulerMixin`):
134
+ The scheduler to get timesteps from.
135
+ num_inference_steps (`int`):
136
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
137
+ must be `None`.
138
+ device (`str` or `torch.device`, *optional*):
139
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
140
+ timesteps (`List[int]`, *optional*):
141
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
142
+ `num_inference_steps` and `sigmas` must be `None`.
143
+ sigmas (`List[float]`, *optional*):
144
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
145
+ `num_inference_steps` and `timesteps` must be `None`.
146
+
147
+ Returns:
148
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
149
+ second element is the number of inference steps.
150
+ """
151
+ if timesteps is not None and sigmas is not None:
152
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
153
+ if timesteps is not None:
154
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
155
+ if not accepts_timesteps:
156
+ raise ValueError(
157
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
158
+ f" timestep schedules. Please check whether you are using the correct scheduler."
159
+ )
160
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
161
+ timesteps = scheduler.timesteps
162
+ num_inference_steps = len(timesteps)
163
+ elif sigmas is not None:
164
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
165
+ if not accept_sigmas:
166
+ raise ValueError(
167
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
168
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
169
+ )
170
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
171
+ timesteps = scheduler.timesteps
172
+ num_inference_steps = len(timesteps)
173
+ else:
174
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
175
+ timesteps = scheduler.timesteps
176
+ return timesteps, num_inference_steps
177
+
178
+
179
+ class StableDiffusionXLControlNetPipeline(
180
+ DiffusionPipeline,
181
+ StableDiffusionMixin,
182
+ TextualInversionLoaderMixin,
183
+ StableDiffusionXLLoraLoaderMixin,
184
+ IPAdapterMixin,
185
+ FromSingleFileMixin,
186
+ ):
187
+ r"""
188
+ Pipeline for text-to-image generation using Stable Diffusion XL with ControlNet guidance.
189
+
190
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
191
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
192
+
193
+ The pipeline also inherits the following loading methods:
194
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
195
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
196
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
197
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
198
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
199
+
200
+ Args:
201
+ vae ([`AutoencoderKL`]):
202
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
203
+ text_encoder ([`~transformers.CLIPTextModel`]):
204
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
205
+ text_encoder_2 ([`~transformers.CLIPTextModelWithProjection`]):
206
+ Second frozen text-encoder
207
+ ([laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)).
208
+ tokenizer ([`~transformers.CLIPTokenizer`]):
209
+ A `CLIPTokenizer` to tokenize text.
210
+ tokenizer_2 ([`~transformers.CLIPTokenizer`]):
211
+ A `CLIPTokenizer` to tokenize text.
212
+ unet ([`UNet2DConditionModel`]):
213
+ A `UNet2DConditionModel` to denoise the encoded image latents.
214
+ controlnet ([`ControlNetModel`] or `List[ControlNetModel]`):
215
+ Provides additional conditioning to the `unet` during the denoising process. If you set multiple
216
+ ControlNets as a list, the outputs from each ControlNet are added together to create one combined
217
+ additional conditioning.
218
+ scheduler ([`SchedulerMixin`]):
219
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
220
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
221
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
222
+ Whether the negative prompt embeddings should always be set to 0. Also see the config of
223
+ `stabilityai/stable-diffusion-xl-base-1-0`.
224
+ add_watermarker (`bool`, *optional*):
225
+ Whether to use the [invisible_watermark](https://github.com/ShieldMnt/invisible-watermark/) library to
226
+ watermark output images. If not defined, it defaults to `True` if the package is installed; otherwise no
227
+ watermarker is used.
228
+ """
229
+
230
+ # leave controlnet out on purpose because it iterates with unet
231
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
232
+ _optional_components = [
233
+ "tokenizer",
234
+ "tokenizer_2",
235
+ "text_encoder",
236
+ "text_encoder_2",
237
+ "feature_extractor",
238
+ "image_encoder",
239
+ ]
240
+ _callback_tensor_inputs = [
241
+ "latents",
242
+ "prompt_embeds",
243
+ "negative_prompt_embeds",
244
+ "add_text_embeds",
245
+ "add_time_ids",
246
+ "negative_pooled_prompt_embeds",
247
+ "negative_add_time_ids",
248
+ "image",
249
+ ]
250
+
251
+ def __init__(
252
+ self,
253
+ vae: AutoencoderKL,
254
+ text_encoder: CLIPTextModel,
255
+ text_encoder_2: CLIPTextModelWithProjection,
256
+ tokenizer: CLIPTokenizer,
257
+ tokenizer_2: CLIPTokenizer,
258
+ unet: UNet2DConditionModel,
259
+ controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel], MultiControlNetModel],
260
+ scheduler: KarrasDiffusionSchedulers,
261
+ force_zeros_for_empty_prompt: bool = True,
262
+ add_watermarker: Optional[bool] = None,
263
+ feature_extractor: CLIPImageProcessor = None,
264
+ image_encoder: CLIPVisionModelWithProjection = None,
265
+ ):
266
+ super().__init__()
267
+
268
+ if isinstance(controlnet, (list, tuple)):
269
+ controlnet = MultiControlNetModel(controlnet)
270
+
271
+ self.register_modules(
272
+ vae=vae,
273
+ text_encoder=text_encoder,
274
+ text_encoder_2=text_encoder_2,
275
+ tokenizer=tokenizer,
276
+ tokenizer_2=tokenizer_2,
277
+ unet=unet,
278
+ controlnet=controlnet,
279
+ scheduler=scheduler,
280
+ feature_extractor=feature_extractor,
281
+ image_encoder=image_encoder,
282
+ )
283
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
284
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
285
+ self.control_image_processor = VaeImageProcessor(
286
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
287
+ )
288
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
289
+
290
+ if add_watermarker:
291
+ self.watermark = StableDiffusionXLWatermarker()
292
+ else:
293
+ self.watermark = None
294
+
295
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
296
+
297
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
298
+ def encode_prompt(
299
+ self,
300
+ prompt: str,
301
+ prompt_2: Optional[str] = None,
302
+ device: Optional[torch.device] = None,
303
+ num_images_per_prompt: int = 1,
304
+ do_classifier_free_guidance: bool = True,
305
+ negative_prompt: Optional[str] = None,
306
+ negative_prompt_2: Optional[str] = None,
307
+ prompt_embeds: Optional[torch.Tensor] = None,
308
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
309
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
310
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
311
+ lora_scale: Optional[float] = None,
312
+ clip_skip: Optional[int] = None,
313
+ ):
314
+ r"""
315
+ Encodes the prompt into text encoder hidden states.
316
+
317
+ Args:
318
+ prompt (`str` or `List[str]`, *optional*):
319
+ prompt to be encoded
320
+ prompt_2 (`str` or `List[str]`, *optional*):
321
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
322
+ used in both text-encoders
323
+ device: (`torch.device`):
324
+ torch device
325
+ num_images_per_prompt (`int`):
326
+ number of images that should be generated per prompt
327
+ do_classifier_free_guidance (`bool`):
328
+ whether to use classifier free guidance or not
329
+ negative_prompt (`str` or `List[str]`, *optional*):
330
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
331
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
332
+ less than `1`).
333
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
334
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
335
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
336
+ prompt_embeds (`torch.Tensor`, *optional*):
337
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
338
+ provided, text embeddings will be generated from `prompt` input argument.
339
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
340
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
341
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
342
+ argument.
343
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
344
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
345
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
346
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
347
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
348
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
349
+ input argument.
350
+ lora_scale (`float`, *optional*):
351
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
352
+ clip_skip (`int`, *optional*):
353
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
354
+ the output of the pre-final layer will be used for computing the prompt embeddings.
355
+ """
356
+ device = device or self._execution_device
357
+
358
+ # set lora scale so that monkey patched LoRA
359
+ # function of text encoder can correctly access it
360
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
361
+ self._lora_scale = lora_scale
362
+
363
+ # dynamically adjust the LoRA scale
364
+ if self.text_encoder is not None:
365
+ if not USE_PEFT_BACKEND:
366
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
367
+ else:
368
+ scale_lora_layers(self.text_encoder, lora_scale)
369
+
370
+ if self.text_encoder_2 is not None:
371
+ if not USE_PEFT_BACKEND:
372
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
373
+ else:
374
+ scale_lora_layers(self.text_encoder_2, lora_scale)
375
+
376
+ prompt = [prompt] if isinstance(prompt, str) else prompt
377
+
378
+ if prompt is not None:
379
+ batch_size = len(prompt)
380
+ else:
381
+ batch_size = prompt_embeds.shape[0]
382
+
383
+ # Define tokenizers and text encoders
384
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
385
+ text_encoders = (
386
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
387
+ )
388
+
389
+ if prompt_embeds is None:
390
+ prompt_2 = prompt_2 or prompt
391
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
392
+
393
+ # textual inversion: process multi-vector tokens if necessary
394
+ prompt_embeds_list = []
395
+ prompts = [prompt, prompt_2]
396
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
397
+ if isinstance(self, TextualInversionLoaderMixin):
398
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
399
+
400
+ text_inputs = tokenizer(
401
+ prompt,
402
+ padding="max_length",
403
+ max_length=tokenizer.model_max_length,
404
+ truncation=True,
405
+ return_tensors="pt",
406
+ )
407
+
408
+ text_input_ids = text_inputs.input_ids
409
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
410
+
411
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
412
+ text_input_ids, untruncated_ids
413
+ ):
414
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
415
+ logger.warning(
416
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
417
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
418
+ )
419
+
420
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
421
+
422
+ # We are only ALWAYS interested in the pooled output of the final text encoder
423
+ pooled_prompt_embeds = prompt_embeds[0]
424
+ if clip_skip is None:
425
+ prompt_embeds = prompt_embeds.hidden_states[-2]
426
+ else:
427
+ # "2" because SDXL always indexes from the penultimate layer.
428
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
429
+
430
+ prompt_embeds_list.append(prompt_embeds)
431
+
432
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
433
+
434
+ # get unconditional embeddings for classifier free guidance
435
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
436
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
437
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
438
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
439
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
440
+ negative_prompt = negative_prompt or ""
441
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
442
+
443
+ # normalize str to list
444
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
445
+ negative_prompt_2 = (
446
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
447
+ )
448
+
449
+ uncond_tokens: List[str]
450
+ if prompt is not None and type(prompt) is not type(negative_prompt):
451
+ raise TypeError(
452
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
453
+ f" {type(prompt)}."
454
+ )
455
+ elif batch_size != len(negative_prompt):
456
+ raise ValueError(
457
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
458
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
459
+ " the batch size of `prompt`."
460
+ )
461
+ else:
462
+ uncond_tokens = [negative_prompt, negative_prompt_2]
463
+
464
+ negative_prompt_embeds_list = []
465
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
466
+ if isinstance(self, TextualInversionLoaderMixin):
467
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
468
+
469
+ max_length = prompt_embeds.shape[1]
470
+ uncond_input = tokenizer(
471
+ negative_prompt,
472
+ padding="max_length",
473
+ max_length=max_length,
474
+ truncation=True,
475
+ return_tensors="pt",
476
+ )
477
+
478
+ negative_prompt_embeds = text_encoder(
479
+ uncond_input.input_ids.to(device),
480
+ output_hidden_states=True,
481
+ )
482
+ # We are only ALWAYS interested in the pooled output of the final text encoder
483
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
484
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
485
+
486
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
487
+
488
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
489
+
490
+ if self.text_encoder_2 is not None:
491
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
492
+ else:
493
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
494
+
495
+ bs_embed, seq_len, _ = prompt_embeds.shape
496
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
497
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
498
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
499
+
500
+ if do_classifier_free_guidance:
501
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
502
+ seq_len = negative_prompt_embeds.shape[1]
503
+
504
+ if self.text_encoder_2 is not None:
505
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
506
+ else:
507
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
508
+
509
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
510
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
511
+
512
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
513
+ bs_embed * num_images_per_prompt, -1
514
+ )
515
+ if do_classifier_free_guidance:
516
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
517
+ bs_embed * num_images_per_prompt, -1
518
+ )
519
+
520
+ if self.text_encoder is not None:
521
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
522
+ # Retrieve the original scale by scaling back the LoRA layers
523
+ unscale_lora_layers(self.text_encoder, lora_scale)
524
+
525
+ if self.text_encoder_2 is not None:
526
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
527
+ # Retrieve the original scale by scaling back the LoRA layers
528
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
529
+
530
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
531
+
532
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
533
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
534
+ dtype = next(self.image_encoder.parameters()).dtype
535
+
536
+ if not isinstance(image, torch.Tensor):
537
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
538
+
539
+ image = image.to(device=device, dtype=dtype)
540
+ if output_hidden_states:
541
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
542
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
543
+ uncond_image_enc_hidden_states = self.image_encoder(
544
+ torch.zeros_like(image), output_hidden_states=True
545
+ ).hidden_states[-2]
546
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
547
+ num_images_per_prompt, dim=0
548
+ )
549
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
550
+ else:
551
+ image_embeds = self.image_encoder(image).image_embeds
552
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
553
+ uncond_image_embeds = torch.zeros_like(image_embeds)
554
+
555
+ return image_embeds, uncond_image_embeds
556
+
557
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
558
+ def prepare_ip_adapter_image_embeds(
559
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
560
+ ):
561
+ image_embeds = []
562
+ if do_classifier_free_guidance:
563
+ negative_image_embeds = []
564
+ if ip_adapter_image_embeds is None:
565
+ if not isinstance(ip_adapter_image, list):
566
+ ip_adapter_image = [ip_adapter_image]
567
+
568
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
569
+ raise ValueError(
570
+ 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."
571
+ )
572
+
573
+ for single_ip_adapter_image, image_proj_layer in zip(
574
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
575
+ ):
576
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
577
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
578
+ single_ip_adapter_image, device, 1, output_hidden_state
579
+ )
580
+
581
+ image_embeds.append(single_image_embeds[None, :])
582
+ if do_classifier_free_guidance:
583
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
584
+ else:
585
+ for single_image_embeds in ip_adapter_image_embeds:
586
+ if do_classifier_free_guidance:
587
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
588
+ negative_image_embeds.append(single_negative_image_embeds)
589
+ image_embeds.append(single_image_embeds)
590
+
591
+ ip_adapter_image_embeds = []
592
+ for i, single_image_embeds in enumerate(image_embeds):
593
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
594
+ if do_classifier_free_guidance:
595
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
596
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
597
+
598
+ single_image_embeds = single_image_embeds.to(device=device)
599
+ ip_adapter_image_embeds.append(single_image_embeds)
600
+
601
+ return ip_adapter_image_embeds
602
+
603
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
604
+ def prepare_extra_step_kwargs(self, generator, eta):
605
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
606
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
607
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
608
+ # and should be between [0, 1]
609
+
610
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
611
+ extra_step_kwargs = {}
612
+ if accepts_eta:
613
+ extra_step_kwargs["eta"] = eta
614
+
615
+ # check if the scheduler accepts generator
616
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
617
+ if accepts_generator:
618
+ extra_step_kwargs["generator"] = generator
619
+ return extra_step_kwargs
620
+
621
+ def check_inputs(
622
+ self,
623
+ prompt,
624
+ prompt_2,
625
+ image,
626
+ callback_steps,
627
+ negative_prompt=None,
628
+ negative_prompt_2=None,
629
+ prompt_embeds=None,
630
+ negative_prompt_embeds=None,
631
+ pooled_prompt_embeds=None,
632
+ ip_adapter_image=None,
633
+ ip_adapter_image_embeds=None,
634
+ negative_pooled_prompt_embeds=None,
635
+ controlnet_conditioning_scale=1.0,
636
+ control_guidance_start=0.0,
637
+ control_guidance_end=1.0,
638
+ callback_on_step_end_tensor_inputs=None,
639
+ ):
640
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
641
+ raise ValueError(
642
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
643
+ f" {type(callback_steps)}."
644
+ )
645
+
646
+ if callback_on_step_end_tensor_inputs is not None and not all(
647
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
648
+ ):
649
+ raise ValueError(
650
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
651
+ )
652
+
653
+ if prompt is not None and prompt_embeds is not None:
654
+ raise ValueError(
655
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
656
+ " only forward one of the two."
657
+ )
658
+ elif prompt_2 is not None and prompt_embeds is not None:
659
+ raise ValueError(
660
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
661
+ " only forward one of the two."
662
+ )
663
+ elif prompt is None and prompt_embeds is None:
664
+ raise ValueError(
665
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
666
+ )
667
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
668
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
669
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
670
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
671
+
672
+ if negative_prompt is not None and negative_prompt_embeds is not None:
673
+ raise ValueError(
674
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
675
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
676
+ )
677
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
678
+ raise ValueError(
679
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
680
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
681
+ )
682
+
683
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
684
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
685
+ raise ValueError(
686
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
687
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
688
+ f" {negative_prompt_embeds.shape}."
689
+ )
690
+
691
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
692
+ raise ValueError(
693
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
694
+ )
695
+
696
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
697
+ raise ValueError(
698
+ "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
699
+ )
700
+
701
+ # `prompt` needs more sophisticated handling when there are multiple
702
+ # conditionings.
703
+ if isinstance(self.controlnet, MultiControlNetModel):
704
+ if isinstance(prompt, list):
705
+ logger.warning(
706
+ f"You have {len(self.controlnet.nets)} ControlNets and you have passed {len(prompt)}"
707
+ " prompts. The conditionings will be fixed across the prompts."
708
+ )
709
+
710
+ # Check `image`
711
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
712
+ self.controlnet, torch._dynamo.eval_frame.OptimizedModule
713
+ )
714
+ if (
715
+ isinstance(self.controlnet, ControlNetModel)
716
+ or is_compiled
717
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
718
+ ):
719
+ self.check_image(image, prompt, prompt_embeds)
720
+ elif (
721
+ isinstance(self.controlnet, MultiControlNetModel)
722
+ or is_compiled
723
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
724
+ ):
725
+ if not isinstance(image, list):
726
+ raise TypeError("For multiple controlnets: `image` must be type `list`")
727
+
728
+ # When `image` is a nested list:
729
+ # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
730
+ elif any(isinstance(i, list) for i in image):
731
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
732
+ elif len(image) != len(self.controlnet.nets):
733
+ raise ValueError(
734
+ f"For multiple controlnets: `image` must have the same length as the number of controlnets, but got {len(image)} images and {len(self.controlnet.nets)} ControlNets."
735
+ )
736
+
737
+ for image_ in image:
738
+ self.check_image(image_, prompt, prompt_embeds)
739
+ else:
740
+ assert False
741
+
742
+ # Check `controlnet_conditioning_scale`
743
+ if (
744
+ isinstance(self.controlnet, ControlNetModel)
745
+ or is_compiled
746
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
747
+ ):
748
+ if not isinstance(controlnet_conditioning_scale, float):
749
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
750
+ elif (
751
+ isinstance(self.controlnet, MultiControlNetModel)
752
+ or is_compiled
753
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
754
+ ):
755
+ if isinstance(controlnet_conditioning_scale, list):
756
+ if any(isinstance(i, list) for i in controlnet_conditioning_scale):
757
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
758
+ elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
759
+ self.controlnet.nets
760
+ ):
761
+ raise ValueError(
762
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
763
+ " the same length as the number of controlnets"
764
+ )
765
+ else:
766
+ assert False
767
+
768
+ if not isinstance(control_guidance_start, (tuple, list)):
769
+ control_guidance_start = [control_guidance_start]
770
+
771
+ if not isinstance(control_guidance_end, (tuple, list)):
772
+ control_guidance_end = [control_guidance_end]
773
+
774
+ if len(control_guidance_start) != len(control_guidance_end):
775
+ raise ValueError(
776
+ f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list."
777
+ )
778
+
779
+ if isinstance(self.controlnet, MultiControlNetModel):
780
+ if len(control_guidance_start) != len(self.controlnet.nets):
781
+ raise ValueError(
782
+ f"`control_guidance_start`: {control_guidance_start} has {len(control_guidance_start)} elements but there are {len(self.controlnet.nets)} controlnets available. Make sure to provide {len(self.controlnet.nets)}."
783
+ )
784
+
785
+ for start, end in zip(control_guidance_start, control_guidance_end):
786
+ if start >= end:
787
+ raise ValueError(
788
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
789
+ )
790
+ if start < 0.0:
791
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
792
+ if end > 1.0:
793
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
794
+
795
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
796
+ raise ValueError(
797
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
798
+ )
799
+
800
+ if ip_adapter_image_embeds is not None:
801
+ if not isinstance(ip_adapter_image_embeds, list):
802
+ raise ValueError(
803
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
804
+ )
805
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
806
+ raise ValueError(
807
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
808
+ )
809
+
810
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.check_image
811
+ def check_image(self, image, prompt, prompt_embeds):
812
+ image_is_pil = isinstance(image, PIL.Image.Image)
813
+ image_is_tensor = isinstance(image, torch.Tensor)
814
+ image_is_np = isinstance(image, np.ndarray)
815
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
816
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
817
+ image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
818
+
819
+ if (
820
+ not image_is_pil
821
+ and not image_is_tensor
822
+ and not image_is_np
823
+ and not image_is_pil_list
824
+ and not image_is_tensor_list
825
+ and not image_is_np_list
826
+ ):
827
+ raise TypeError(
828
+ f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
829
+ )
830
+
831
+ if image_is_pil:
832
+ image_batch_size = 1
833
+ else:
834
+ image_batch_size = len(image)
835
+
836
+ if prompt is not None and isinstance(prompt, str):
837
+ prompt_batch_size = 1
838
+ elif prompt is not None and isinstance(prompt, list):
839
+ prompt_batch_size = len(prompt)
840
+ elif prompt_embeds is not None:
841
+ prompt_batch_size = prompt_embeds.shape[0]
842
+
843
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
844
+ raise ValueError(
845
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
846
+ )
847
+
848
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.prepare_image
849
+ def prepare_image(
850
+ self,
851
+ image,
852
+ width,
853
+ height,
854
+ batch_size,
855
+ num_images_per_prompt,
856
+ device,
857
+ dtype,
858
+ do_classifier_free_guidance=False,
859
+ guess_mode=False,
860
+ ):
861
+ image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
862
+ image_batch_size = image.shape[0]
863
+
864
+ if image_batch_size == 1:
865
+ repeat_by = batch_size
866
+ else:
867
+ # image batch size is the same as prompt batch size
868
+ repeat_by = num_images_per_prompt
869
+
870
+ image = image.repeat_interleave(repeat_by, dim=0)
871
+
872
+ image = image.to(device=device, dtype=dtype)
873
+
874
+ if do_classifier_free_guidance and not guess_mode:
875
+ image = torch.cat([image] * 2)
876
+
877
+ return image
878
+
879
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
880
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
881
+ shape = (
882
+ batch_size,
883
+ num_channels_latents,
884
+ int(height) // self.vae_scale_factor,
885
+ int(width) // self.vae_scale_factor,
886
+ )
887
+ if isinstance(generator, list) and len(generator) != batch_size:
888
+ raise ValueError(
889
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
890
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
891
+ )
892
+
893
+ if latents is None:
894
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
895
+ else:
896
+ latents = latents.to(device)
897
+
898
+ # scale the initial noise by the standard deviation required by the scheduler
899
+ latents = latents * self.scheduler.init_noise_sigma
900
+ return latents
901
+
902
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline._get_add_time_ids
903
+ def _get_add_time_ids(
904
+ self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
905
+ ):
906
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
907
+
908
+ passed_add_embed_dim = (
909
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
910
+ )
911
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
912
+
913
+ if expected_add_embed_dim != passed_add_embed_dim:
914
+ raise ValueError(
915
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
916
+ )
917
+
918
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
919
+ return add_time_ids
920
+
921
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
922
+ def upcast_vae(self):
923
+ dtype = self.vae.dtype
924
+ self.vae.to(dtype=torch.float32)
925
+ use_torch_2_0_or_xformers = isinstance(
926
+ self.vae.decoder.mid_block.attentions[0].processor,
927
+ (
928
+ AttnProcessor2_0,
929
+ XFormersAttnProcessor,
930
+ ),
931
+ )
932
+ # if xformers or torch_2_0 is used attention block does not need
933
+ # to be in float32 which can save lots of memory
934
+ if use_torch_2_0_or_xformers:
935
+ self.vae.post_quant_conv.to(dtype)
936
+ self.vae.decoder.conv_in.to(dtype)
937
+ self.vae.decoder.mid_block.to(dtype)
938
+
939
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
940
+ def get_guidance_scale_embedding(
941
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
942
+ ) -> torch.Tensor:
943
+ """
944
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
945
+
946
+ Args:
947
+ w (`torch.Tensor`):
948
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
949
+ embedding_dim (`int`, *optional*, defaults to 512):
950
+ Dimension of the embeddings to generate.
951
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
952
+ Data type of the generated embeddings.
953
+
954
+ Returns:
955
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
956
+ """
957
+ assert len(w.shape) == 1
958
+ w = w * 1000.0
959
+
960
+ half_dim = embedding_dim // 2
961
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
962
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
963
+ emb = w.to(dtype)[:, None] * emb[None, :]
964
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
965
+ if embedding_dim % 2 == 1: # zero pad
966
+ emb = torch.nn.functional.pad(emb, (0, 1))
967
+ assert emb.shape == (w.shape[0], embedding_dim)
968
+ return emb
969
+
970
+ @property
971
+ def guidance_scale(self):
972
+ return self._guidance_scale
973
+
974
+ @property
975
+ def clip_skip(self):
976
+ return self._clip_skip
977
+
978
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
979
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
980
+ # corresponds to doing no classifier free guidance.
981
+ @property
982
+ def do_classifier_free_guidance(self):
983
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
984
+
985
+ @property
986
+ def cross_attention_kwargs(self):
987
+ return self._cross_attention_kwargs
988
+
989
+ @property
990
+ def denoising_end(self):
991
+ return self._denoising_end
992
+
993
+ @property
994
+ def num_timesteps(self):
995
+ return self._num_timesteps
996
+
997
+ @property
998
+ def interrupt(self):
999
+ return self._interrupt
1000
+
1001
+ @torch.no_grad()
1002
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
1003
+ def __call__(
1004
+ self,
1005
+ prompt: Union[str, List[str]] = None,
1006
+ prompt_2: Optional[Union[str, List[str]]] = None,
1007
+ image: PipelineImageInput = None,
1008
+ height: Optional[int] = None,
1009
+ width: Optional[int] = None,
1010
+ num_inference_steps: int = 50,
1011
+ timesteps: List[int] = None,
1012
+ sigmas: List[float] = None,
1013
+ denoising_end: Optional[float] = None,
1014
+ guidance_scale: float = 5.0,
1015
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1016
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
1017
+ num_images_per_prompt: Optional[int] = 1,
1018
+ eta: float = 0.0,
1019
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1020
+ latents: Optional[torch.Tensor] = None,
1021
+ prompt_embeds: Optional[torch.Tensor] = None,
1022
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1023
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
1024
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
1025
+ ip_adapter_image: Optional[PipelineImageInput] = None,
1026
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
1027
+ output_type: Optional[str] = "pil",
1028
+ return_dict: bool = True,
1029
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1030
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
1031
+ guess_mode: bool = False,
1032
+ control_guidance_start: Union[float, List[float]] = 0.0,
1033
+ control_guidance_end: Union[float, List[float]] = 1.0,
1034
+ original_size: Tuple[int, int] = None,
1035
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
1036
+ target_size: Tuple[int, int] = None,
1037
+ negative_original_size: Optional[Tuple[int, int]] = None,
1038
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
1039
+ negative_target_size: Optional[Tuple[int, int]] = None,
1040
+ clip_skip: Optional[int] = None,
1041
+ callback_on_step_end: Optional[
1042
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
1043
+ ] = None,
1044
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1045
+ **kwargs,
1046
+ ):
1047
+ r"""
1048
+ The call function to the pipeline for generation.
1049
+
1050
+ Args:
1051
+ prompt (`str` or `List[str]`, *optional*):
1052
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
1053
+ prompt_2 (`str` or `List[str]`, *optional*):
1054
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
1055
+ used in both text-encoders.
1056
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
1057
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
1058
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
1059
+ specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted
1060
+ as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or
1061
+ width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`,
1062
+ images must be passed as a list such that each element of the list can be correctly batched for input
1063
+ to a single ControlNet.
1064
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1065
+ The height in pixels of the generated image. Anything below 512 pixels won't work well for
1066
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1067
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1068
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1069
+ The width in pixels of the generated image. Anything below 512 pixels won't work well for
1070
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1071
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1072
+ num_inference_steps (`int`, *optional*, defaults to 50):
1073
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1074
+ expense of slower inference.
1075
+ timesteps (`List[int]`, *optional*):
1076
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
1077
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
1078
+ passed will be used. Must be in descending order.
1079
+ sigmas (`List[float]`, *optional*):
1080
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
1081
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
1082
+ will be used.
1083
+ denoising_end (`float`, *optional*):
1084
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
1085
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
1086
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
1087
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
1088
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
1089
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
1090
+ guidance_scale (`float`, *optional*, defaults to 5.0):
1091
+ A higher guidance scale value encourages the model to generate images closely linked to the text
1092
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
1093
+ negative_prompt (`str` or `List[str]`, *optional*):
1094
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
1095
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
1096
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
1097
+ The prompt or prompts to guide what to not include in image generation. This is sent to `tokenizer_2`
1098
+ and `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders.
1099
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1100
+ The number of images to generate per prompt.
1101
+ eta (`float`, *optional*, defaults to 0.0):
1102
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
1103
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
1104
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1105
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
1106
+ generation deterministic.
1107
+ latents (`torch.Tensor`, *optional*):
1108
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
1109
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1110
+ tensor is generated by sampling using the supplied random `generator`.
1111
+ prompt_embeds (`torch.Tensor`, *optional*):
1112
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
1113
+ provided, text embeddings are generated from the `prompt` input argument.
1114
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1115
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
1116
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
1117
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
1118
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
1119
+ not provided, pooled text embeddings are generated from `prompt` input argument.
1120
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
1121
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs (prompt
1122
+ weighting). If not provided, pooled `negative_prompt_embeds` are generated from `negative_prompt` input
1123
+ argument.
1124
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1125
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
1126
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
1127
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
1128
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
1129
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
1130
+ output_type (`str`, *optional*, defaults to `"pil"`):
1131
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
1132
+ return_dict (`bool`, *optional*, defaults to `True`):
1133
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1134
+ plain tuple.
1135
+ cross_attention_kwargs (`dict`, *optional*):
1136
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
1137
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1138
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
1139
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
1140
+ to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
1141
+ the corresponding scale as a list.
1142
+ guess_mode (`bool`, *optional*, defaults to `False`):
1143
+ The ControlNet encoder tries to recognize the content of the input image even if you remove all
1144
+ prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
1145
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
1146
+ The percentage of total steps at which the ControlNet starts applying.
1147
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
1148
+ The percentage of total steps at which the ControlNet stops applying.
1149
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1150
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1151
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
1152
+ explained in section 2.2 of
1153
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1154
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1155
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1156
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1157
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1158
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1159
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1160
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1161
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
1162
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1163
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1164
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
1165
+ micro-conditioning as explained in section 2.2 of
1166
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1167
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1168
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1169
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
1170
+ micro-conditioning as explained in section 2.2 of
1171
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1172
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1173
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1174
+ To negatively condition the generation process based on a target image resolution. It should be as same
1175
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
1176
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1177
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1178
+ clip_skip (`int`, *optional*):
1179
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1180
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1181
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
1182
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
1183
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
1184
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
1185
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
1186
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1187
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1188
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1189
+ `._callback_tensor_inputs` attribute of your pipeline class.
1190
+
1191
+ Examples:
1192
+
1193
+ Returns:
1194
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1195
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
1196
+ otherwise a `tuple` is returned containing the output images.
1197
+ """
1198
+
1199
+ callback = kwargs.pop("callback", None)
1200
+ callback_steps = kwargs.pop("callback_steps", None)
1201
+
1202
+ if callback is not None:
1203
+ deprecate(
1204
+ "callback",
1205
+ "1.0.0",
1206
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1207
+ )
1208
+ if callback_steps is not None:
1209
+ deprecate(
1210
+ "callback_steps",
1211
+ "1.0.0",
1212
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1213
+ )
1214
+
1215
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
1216
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
1217
+
1218
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
1219
+
1220
+ # align format for control guidance
1221
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
1222
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
1223
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
1224
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
1225
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
1226
+ mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
1227
+ control_guidance_start, control_guidance_end = (
1228
+ mult * [control_guidance_start],
1229
+ mult * [control_guidance_end],
1230
+ )
1231
+
1232
+ # 1. Check inputs. Raise error if not correct
1233
+ self.check_inputs(
1234
+ prompt,
1235
+ prompt_2,
1236
+ image,
1237
+ callback_steps,
1238
+ negative_prompt,
1239
+ negative_prompt_2,
1240
+ prompt_embeds,
1241
+ negative_prompt_embeds,
1242
+ pooled_prompt_embeds,
1243
+ ip_adapter_image,
1244
+ ip_adapter_image_embeds,
1245
+ negative_pooled_prompt_embeds,
1246
+ controlnet_conditioning_scale,
1247
+ control_guidance_start,
1248
+ control_guidance_end,
1249
+ callback_on_step_end_tensor_inputs,
1250
+ )
1251
+
1252
+ self._guidance_scale = guidance_scale
1253
+ self._clip_skip = clip_skip
1254
+ self._cross_attention_kwargs = cross_attention_kwargs
1255
+ self._denoising_end = denoising_end
1256
+ self._interrupt = False
1257
+
1258
+ # 2. Define call parameters
1259
+ if prompt is not None and isinstance(prompt, str):
1260
+ batch_size = 1
1261
+ elif prompt is not None and isinstance(prompt, list):
1262
+ batch_size = len(prompt)
1263
+ else:
1264
+ batch_size = prompt_embeds.shape[0]
1265
+
1266
+ device = self._execution_device
1267
+
1268
+ if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
1269
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
1270
+
1271
+ global_pool_conditions = (
1272
+ controlnet.config.global_pool_conditions
1273
+ if isinstance(controlnet, ControlNetModel)
1274
+ else controlnet.nets[0].config.global_pool_conditions
1275
+ )
1276
+ guess_mode = guess_mode or global_pool_conditions
1277
+
1278
+ # 3.1 Encode input prompt
1279
+ text_encoder_lora_scale = (
1280
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1281
+ )
1282
+ (
1283
+ prompt_embeds,
1284
+ negative_prompt_embeds,
1285
+ pooled_prompt_embeds,
1286
+ negative_pooled_prompt_embeds,
1287
+ ) = self.encode_prompt(
1288
+ prompt,
1289
+ prompt_2,
1290
+ device,
1291
+ num_images_per_prompt,
1292
+ self.do_classifier_free_guidance,
1293
+ negative_prompt,
1294
+ negative_prompt_2,
1295
+ prompt_embeds=prompt_embeds,
1296
+ negative_prompt_embeds=negative_prompt_embeds,
1297
+ pooled_prompt_embeds=pooled_prompt_embeds,
1298
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1299
+ lora_scale=text_encoder_lora_scale,
1300
+ clip_skip=self.clip_skip,
1301
+ )
1302
+
1303
+ # 3.2 Encode ip_adapter_image
1304
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1305
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1306
+ ip_adapter_image,
1307
+ ip_adapter_image_embeds,
1308
+ device,
1309
+ batch_size * num_images_per_prompt,
1310
+ self.do_classifier_free_guidance,
1311
+ )
1312
+
1313
+ # 4. Prepare image
1314
+ if isinstance(controlnet, ControlNetModel):
1315
+ image = self.prepare_image(
1316
+ image=image,
1317
+ width=width,
1318
+ height=height,
1319
+ batch_size=batch_size * num_images_per_prompt,
1320
+ num_images_per_prompt=num_images_per_prompt,
1321
+ device=device,
1322
+ dtype=controlnet.dtype,
1323
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1324
+ guess_mode=guess_mode,
1325
+ )
1326
+ height, width = image.shape[-2:]
1327
+ height, width = height*self.vae_scale_factor, width*self.vae_scale_factor # Bria: update for vae controlnet
1328
+ elif isinstance(controlnet, MultiControlNetModel):
1329
+ images = []
1330
+
1331
+ for image_ in image:
1332
+ image_ = self.prepare_image(
1333
+ image=image_,
1334
+ width=width,
1335
+ height=height,
1336
+ batch_size=batch_size * num_images_per_prompt,
1337
+ num_images_per_prompt=num_images_per_prompt,
1338
+ device=device,
1339
+ dtype=controlnet.dtype,
1340
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1341
+ guess_mode=guess_mode,
1342
+ )
1343
+
1344
+ images.append(image_)
1345
+
1346
+ image = images
1347
+ height, width = image[0].shape[-2:]
1348
+ else:
1349
+ assert False
1350
+
1351
+ # 5. Prepare timesteps
1352
+ timesteps, num_inference_steps = retrieve_timesteps(
1353
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
1354
+ )
1355
+ self._num_timesteps = len(timesteps)
1356
+
1357
+ # 6. Prepare latent variables
1358
+ num_channels_latents = self.unet.config.in_channels
1359
+ latents = self.prepare_latents(
1360
+ batch_size * num_images_per_prompt,
1361
+ num_channels_latents,
1362
+ height,
1363
+ width,
1364
+ prompt_embeds.dtype,
1365
+ device,
1366
+ generator,
1367
+ latents,
1368
+ )
1369
+
1370
+ # 6.5 Optionally get Guidance Scale Embedding
1371
+ timestep_cond = None
1372
+ if self.unet.config.time_cond_proj_dim is not None:
1373
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1374
+ timestep_cond = self.get_guidance_scale_embedding(
1375
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1376
+ ).to(device=device, dtype=latents.dtype)
1377
+
1378
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1379
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1380
+
1381
+ # 7.1 Create tensor stating which controlnets to keep
1382
+ controlnet_keep = []
1383
+ for i in range(len(timesteps)):
1384
+ keeps = [
1385
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
1386
+ for s, e in zip(control_guidance_start, control_guidance_end)
1387
+ ]
1388
+ controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)
1389
+
1390
+ # 7.2 Prepare added time ids & embeddings
1391
+ if isinstance(image, list):
1392
+ original_size = original_size or image[0].shape[-2:]
1393
+ else:
1394
+ original_size = original_size or image.shape[-2:]
1395
+ target_size = target_size or (height, width)
1396
+
1397
+ add_text_embeds = pooled_prompt_embeds
1398
+ if self.text_encoder_2 is None:
1399
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1400
+ else:
1401
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1402
+
1403
+ add_time_ids = self._get_add_time_ids(
1404
+ original_size,
1405
+ crops_coords_top_left,
1406
+ target_size,
1407
+ dtype=prompt_embeds.dtype,
1408
+ text_encoder_projection_dim=text_encoder_projection_dim,
1409
+ )
1410
+
1411
+ if negative_original_size is not None and negative_target_size is not None:
1412
+ negative_add_time_ids = self._get_add_time_ids(
1413
+ negative_original_size,
1414
+ negative_crops_coords_top_left,
1415
+ negative_target_size,
1416
+ dtype=prompt_embeds.dtype,
1417
+ text_encoder_projection_dim=text_encoder_projection_dim,
1418
+ )
1419
+ else:
1420
+ negative_add_time_ids = add_time_ids
1421
+
1422
+ if self.do_classifier_free_guidance:
1423
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1424
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1425
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
1426
+
1427
+ prompt_embeds = prompt_embeds.to(device)
1428
+ add_text_embeds = add_text_embeds.to(device)
1429
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1430
+
1431
+ # 8. Denoising loop
1432
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1433
+
1434
+ # 8.1 Apply denoising_end
1435
+ if (
1436
+ self.denoising_end is not None
1437
+ and isinstance(self.denoising_end, float)
1438
+ and self.denoising_end > 0
1439
+ and self.denoising_end < 1
1440
+ ):
1441
+ discrete_timestep_cutoff = int(
1442
+ round(
1443
+ self.scheduler.config.num_train_timesteps
1444
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1445
+ )
1446
+ )
1447
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1448
+ timesteps = timesteps[:num_inference_steps]
1449
+
1450
+ is_unet_compiled = is_compiled_module(self.unet)
1451
+ is_controlnet_compiled = is_compiled_module(self.controlnet)
1452
+ is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
1453
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1454
+ for i, t in enumerate(timesteps):
1455
+ if self.interrupt:
1456
+ continue
1457
+
1458
+ # Relevant thread:
1459
+ # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
1460
+ if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1:
1461
+ torch._inductor.cudagraph_mark_step_begin()
1462
+ # expand the latents if we are doing classifier free guidance
1463
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1464
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1465
+
1466
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1467
+
1468
+ # controlnet(s) inference
1469
+ if guess_mode and self.do_classifier_free_guidance:
1470
+ # Infer ControlNet only for the conditional batch.
1471
+ control_model_input = latents
1472
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
1473
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
1474
+ controlnet_added_cond_kwargs = {
1475
+ "text_embeds": add_text_embeds.chunk(2)[1],
1476
+ "time_ids": add_time_ids.chunk(2)[1],
1477
+ }
1478
+ else:
1479
+ control_model_input = latent_model_input
1480
+ controlnet_prompt_embeds = prompt_embeds
1481
+ controlnet_added_cond_kwargs = added_cond_kwargs
1482
+
1483
+ if isinstance(controlnet_keep[i], list):
1484
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
1485
+ else:
1486
+ controlnet_cond_scale = controlnet_conditioning_scale
1487
+ if isinstance(controlnet_cond_scale, list):
1488
+ controlnet_cond_scale = controlnet_cond_scale[0]
1489
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
1490
+
1491
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
1492
+ control_model_input,
1493
+ t,
1494
+ encoder_hidden_states=controlnet_prompt_embeds,
1495
+ controlnet_cond=image,
1496
+ conditioning_scale=cond_scale,
1497
+ guess_mode=guess_mode,
1498
+ added_cond_kwargs=controlnet_added_cond_kwargs,
1499
+ return_dict=False,
1500
+ )
1501
+
1502
+ if guess_mode and self.do_classifier_free_guidance:
1503
+ # Inferred ControlNet only for the conditional batch.
1504
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
1505
+ # add 0 to the unconditional batch to keep it unchanged.
1506
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
1507
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
1508
+
1509
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1510
+ added_cond_kwargs["image_embeds"] = image_embeds
1511
+
1512
+ # predict the noise residual
1513
+ noise_pred = self.unet(
1514
+ latent_model_input,
1515
+ t,
1516
+ encoder_hidden_states=prompt_embeds,
1517
+ timestep_cond=timestep_cond,
1518
+ cross_attention_kwargs=self.cross_attention_kwargs,
1519
+ down_block_additional_residuals=down_block_res_samples,
1520
+ mid_block_additional_residual=mid_block_res_sample,
1521
+ added_cond_kwargs=added_cond_kwargs,
1522
+ return_dict=False,
1523
+ )[0]
1524
+
1525
+ # perform guidance
1526
+ if self.do_classifier_free_guidance:
1527
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1528
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1529
+
1530
+ # compute the previous noisy sample x_t -> x_t-1
1531
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1532
+
1533
+ if callback_on_step_end is not None:
1534
+ callback_kwargs = {}
1535
+ for k in callback_on_step_end_tensor_inputs:
1536
+ callback_kwargs[k] = locals()[k]
1537
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1538
+
1539
+ latents = callback_outputs.pop("latents", latents)
1540
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1541
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1542
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1543
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1544
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1545
+ )
1546
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1547
+ negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
1548
+ image = callback_outputs.pop("image", image)
1549
+
1550
+ # call the callback, if provided
1551
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1552
+ progress_bar.update()
1553
+ if callback is not None and i % callback_steps == 0:
1554
+ step_idx = i // getattr(self.scheduler, "order", 1)
1555
+ callback(step_idx, t, latents)
1556
+
1557
+ if not output_type == "latent":
1558
+ # make sure the VAE is in float32 mode, as it overflows in float16
1559
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1560
+
1561
+ if needs_upcasting:
1562
+ self.upcast_vae()
1563
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1564
+
1565
+ # unscale/denormalize the latents
1566
+ # denormalize with the mean and std if available and not None
1567
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1568
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1569
+ if has_latents_mean and has_latents_std:
1570
+ latents_mean = (
1571
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1572
+ )
1573
+ latents_std = (
1574
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1575
+ )
1576
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1577
+ else:
1578
+ latents = latents / self.vae.config.scaling_factor
1579
+
1580
+ image = self.vae.decode(latents, return_dict=False)[0]
1581
+
1582
+ # cast back to fp16 if needed
1583
+ if needs_upcasting:
1584
+ self.vae.to(dtype=torch.float16)
1585
+ else:
1586
+ image = latents
1587
+
1588
+ if not output_type == "latent":
1589
+ # apply watermark if available
1590
+ if self.watermark is not None:
1591
+ image = self.watermark.apply_watermark(image)
1592
+
1593
+ image = self.image_processor.postprocess(image, output_type=output_type)
1594
+
1595
+ # Offload all models
1596
+ self.maybe_free_model_hooks()
1597
+
1598
+ if not return_dict:
1599
+ return (image,)
1600
+
1601
+ return StableDiffusionXLPipelineOutput(images=image)
requirements.txt ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==2.1.0
2
+ accelerate==0.31.0
3
+ aiofiles==23.2.1
4
+ aiohttp==3.9.5
5
+ aiosignal==1.3.1
6
+ altair==5.3.0
7
+ annotated-types==0.7.0
8
+ anyio==4.4.0
9
+ asttokens @ file:///home/conda/feedstock_root/build_artifacts/asttokens_1698341106958/work
10
+ async-timeout==4.0.3
11
+ attrs==23.2.0
12
+ bitsandbytes==0.43.1
13
+ blessed==1.20.0
14
+ boto3==1.34.119
15
+ botocore==1.34.119
16
+ braceexpand==0.1.7
17
+ certifi==2024.6.2
18
+ charset-normalizer==3.3.2
19
+ click==8.1.7
20
+ cloudpickle==2.2.1
21
+ comm @ file:///home/conda/feedstock_root/build_artifacts/comm_1710320294760/work
22
+ contourpy==1.2.1
23
+ cycler==0.12.1
24
+ datasets==2.19.2
25
+ debugpy @ file:///home/conda/feedstock_root/build_artifacts/debugpy_1707444420542/work
26
+ decorator @ file:///home/conda/feedstock_root/build_artifacts/decorator_1641555617451/work
27
+ diffusers==0.31.0
28
+ dill==0.3.8
29
+ dnspython==2.6.1
30
+ docker==7.1.0
31
+ docker-pycreds==0.4.0
32
+ email_validator==2.2.0
33
+ evaluate==0.4.2
34
+ exceptiongroup @ file:///home/conda/feedstock_root/build_artifacts/exceptiongroup_1704921103267/work
35
+ executing @ file:///home/conda/feedstock_root/build_artifacts/executing_1698579936712/work
36
+ fastapi==0.111.0
37
+ fastapi-cli==0.0.4
38
+ ffmpy==0.3.2
39
+ filelock==3.14.0
40
+ fonttools==4.53.0
41
+ frozenlist==1.4.1
42
+ fsspec==2024.3.1
43
+ gitdb==4.0.11
44
+ GitPython==3.1.43
45
+ google-pasta==0.2.0
46
+ gpustat==1.1.1
47
+ gradio==3.41.2
48
+ gradio_client==0.5.0
49
+ grpcio==1.64.1
50
+ h11==0.14.0
51
+ httpcore==1.0.5
52
+ httptools==0.6.1
53
+ httpx==0.27.0
54
+ huggingface-hub==0.23.2
55
+ idna==3.7
56
+ importlib-metadata==6.11.0
57
+ importlib_resources==6.4.0
58
+ ipykernel @ file:///home/conda/feedstock_root/build_artifacts/ipykernel_1708996548741/work
59
+ ipython @ file:///home/conda/feedstock_root/build_artifacts/ipython_1717182742060/work
60
+ jedi @ file:///home/conda/feedstock_root/build_artifacts/jedi_1696326070614/work
61
+ Jinja2==3.1.4
62
+ jmespath==1.0.1
63
+ jsonschema==4.22.0
64
+ jsonschema-specifications==2023.12.1
65
+ jupyter_client @ file:///home/conda/feedstock_root/build_artifacts/jupyter_client_1716472197302/work
66
+ jupyter_core @ file:///home/conda/feedstock_root/build_artifacts/jupyter_core_1710257277185/work
67
+ kiwisolver==1.4.5
68
+ Markdown==3.6
69
+ markdown-it-py==3.0.0
70
+ MarkupSafe==2.1.5
71
+ matplotlib==3.9.0
72
+ matplotlib-inline @ file:///home/conda/feedstock_root/build_artifacts/matplotlib-inline_1713250518406/work
73
+ mdurl==0.1.2
74
+ mediapy==1.2.1
75
+ mpmath==1.3.0
76
+ multidict==6.0.5
77
+ multiprocess==0.70.16
78
+ nest_asyncio @ file:///home/conda/feedstock_root/build_artifacts/nest-asyncio_1705850609492/work
79
+ networkx==3.3
80
+ numpy==1.26.4
81
+ nvidia-cublas-cu12==12.1.3.1
82
+ nvidia-cuda-cupti-cu12==12.1.105
83
+ nvidia-cuda-nvrtc-cu12==12.1.105
84
+ nvidia-cuda-runtime-cu12==12.1.105
85
+ nvidia-cudnn-cu12==8.9.2.26
86
+ nvidia-cufft-cu12==11.0.2.54
87
+ nvidia-curand-cu12==10.3.2.106
88
+ nvidia-cusolver-cu12==11.4.5.107
89
+ nvidia-cusparse-cu12==12.1.0.106
90
+ nvidia-ml-py==12.555.43
91
+ nvidia-ml-py3==7.352.0
92
+ nvidia-nccl-cu12==2.20.5
93
+ nvidia-nvjitlink-cu12==12.5.40
94
+ nvidia-nvtx-cu12==12.1.105
95
+ opencv-python==4.10.0.82
96
+ orjson==3.10.6
97
+ packaging @ file:///home/conda/feedstock_root/build_artifacts/packaging_1710075952259/work
98
+ pandas==2.2.2
99
+ parso @ file:///home/conda/feedstock_root/build_artifacts/parso_1712320355065/work
100
+ pathos==0.3.2
101
+ pexpect @ file:///home/conda/feedstock_root/build_artifacts/pexpect_1706113125309/work
102
+ pickleshare @ file:///home/conda/feedstock_root/build_artifacts/pickleshare_1602536217715/work
103
+ pillow==10.3.0
104
+ platformdirs @ file:///home/conda/feedstock_root/build_artifacts/platformdirs_1715777629804/work
105
+ pox==0.3.4
106
+ ppft==1.7.6.8
107
+ prompt_toolkit @ file:///home/conda/feedstock_root/build_artifacts/prompt-toolkit_1717583537988/work
108
+ protobuf==4.25.3
109
+ psutil @ file:///home/conda/feedstock_root/build_artifacts/psutil_1705722392846/work
110
+ ptyprocess @ file:///home/conda/feedstock_root/build_artifacts/ptyprocess_1609419310487/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl
111
+ pure-eval @ file:///home/conda/feedstock_root/build_artifacts/pure_eval_1642875951954/work
112
+ pyarrow==16.1.0
113
+ pyarrow-hotfix==0.6
114
+ pydantic==2.8.2
115
+ pydantic_core==2.20.1
116
+ pydub==0.25.1
117
+ Pygments @ file:///home/conda/feedstock_root/build_artifacts/pygments_1714846767233/work
118
+ pyparsing==3.1.2
119
+ python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/python-dateutil_1709299778482/work
120
+ python-dotenv==1.0.1
121
+ python-multipart==0.0.9
122
+ python-rapidjson==1.18
123
+ pytz==2024.1
124
+ PyYAML==6.0.1
125
+ pyzmq @ file:///home/conda/feedstock_root/build_artifacts/pyzmq_1715024398995/work
126
+ referencing==0.35.1
127
+ regex==2024.5.15
128
+ requests==2.32.3
129
+ requests-toolbelt==1.0.0
130
+ rich==13.7.1
131
+ rpds-py==0.18.1
132
+ s3transfer==0.10.1
133
+ safetensors==0.4.3
134
+ sagemaker==2.221.1
135
+ sagemaker-ssh-helper==2.2.0
136
+ schema==0.7.7
137
+ scipy==1.13.1
138
+ semantic-version==2.10.0
139
+ sentry-sdk==2.4.0
140
+ setproctitle==1.3.3
141
+ shellingham==1.5.4
142
+ six @ file:///home/conda/feedstock_root/build_artifacts/six_1620240208055/work
143
+ smdebug-rulesconfig==1.0.1
144
+ smmap==5.0.1
145
+ sniffio==1.3.1
146
+ stack-data @ file:///home/conda/feedstock_root/build_artifacts/stack_data_1669632077133/work
147
+ starlette==0.37.2
148
+ sympy==1.12.1
149
+ tblib==3.0.0
150
+ tensorboard==2.16.2
151
+ tensorboard-data-server==0.7.2
152
+ tensorboardX==2.6.2.2
153
+ tokenizers==0.19.1
154
+ toolz==0.12.1
155
+ torch==2.3.0
156
+ torchaudio==2.3.0
157
+ torchtools==0.1.4
158
+ torchvision==0.18.0
159
+ tornado @ file:///home/conda/feedstock_root/build_artifacts/tornado_1708363098266/work
160
+ tqdm==4.66.4
161
+ traitlets @ file:///home/conda/feedstock_root/build_artifacts/traitlets_1713535121073/work
162
+ transformers==4.41.2
163
+ triton==2.3.0
164
+ tritonclient==2.47.0
165
+ typer==0.12.3
166
+ typing_extensions @ file:///home/conda/feedstock_root/build_artifacts/typing_extensions_1717287769032/work
167
+ tzdata==2024.1
168
+ ujson==5.10.0
169
+ urllib3==2.2.1
170
+ uvicorn==0.30.1
171
+ uvloop==0.19.0
172
+ wandb==0.17.0
173
+ watchfiles==0.22.0
174
+ wcwidth @ file:///home/conda/feedstock_root/build_artifacts/wcwidth_1704731205417/work
175
+ webdataset==0.2.86
176
+ websockets==11.0.3
177
+ Werkzeug==3.0.3
178
+ xformers==0.0.26.post1
179
+ xxhash==3.4.1
180
+ yarl==1.9.4
181
+ zipp @ file:///home/conda/feedstock_root/build_artifacts/zipp_1695255097490/work