JohnWeck commited on
Commit
e27420f
·
verified ·
1 Parent(s): b763406

Upload 19 files

Browse files
StableDiffusion/Our_Attention.py ADDED
The diff for this file is too large to render. See raw diff
 
StableDiffusion/Our_AttnBlock.py ADDED
@@ -0,0 +1,693 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any, Dict, Optional
15
+
16
+ import torch
17
+ import torch.nn.functional as F
18
+ from torch import nn
19
+
20
+ from diffusers.utils import deprecate, logging
21
+ from diffusers.utils.torch_utils import maybe_allow_in_graph
22
+ from diffusers.models.activations import GEGLU, GELU, ApproximateGELU
23
+ from .Our_Attention import Attention, DualAttnProcessor
24
+ from diffusers.models.embeddings import SinusoidalPositionalEmbedding
25
+ from diffusers.models.normalization import AdaLayerNorm, AdaLayerNormContinuous, AdaLayerNormZero, RMSNorm
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+
31
+ def _chunked_feed_forward(ff: nn.Module, hidden_states: torch.Tensor, chunk_dim: int, chunk_size: int):
32
+ # "feed_forward_chunk_size" can be used to save memory
33
+ if hidden_states.shape[chunk_dim] % chunk_size != 0:
34
+ raise ValueError(
35
+ f"`hidden_states` dimension to be chunked: {hidden_states.shape[chunk_dim]} has to be divisible by chunk size: {chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."
36
+ )
37
+
38
+ num_chunks = hidden_states.shape[chunk_dim] // chunk_size
39
+ ff_output = torch.cat(
40
+ [ff(hid_slice) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)],
41
+ dim=chunk_dim,
42
+ )
43
+ return ff_output
44
+
45
+
46
+ @maybe_allow_in_graph
47
+ class GatedSelfAttentionDense(nn.Module):
48
+ r"""
49
+ A gated self-attention dense layer that combines visual features and object features.
50
+
51
+ Parameters:
52
+ query_dim (`int`): The number of channels in the query.
53
+ context_dim (`int`): The number of channels in the context.
54
+ n_heads (`int`): The number of heads to use for attention.
55
+ d_head (`int`): The number of channels in each head.
56
+ """
57
+
58
+ def __init__(self, query_dim: int, context_dim: int, n_heads: int, d_head: int):
59
+ super().__init__()
60
+
61
+ # we need a linear projection since we need cat visual feature and obj feature
62
+ self.linear = nn.Linear(context_dim, query_dim)
63
+
64
+ self.attn = Attention(query_dim=query_dim, heads=n_heads, dim_head=d_head)
65
+ self.ff = FeedForward(query_dim, activation_fn="geglu")
66
+
67
+ self.norm1 = nn.LayerNorm(query_dim)
68
+ self.norm2 = nn.LayerNorm(query_dim)
69
+
70
+ self.register_parameter("alpha_attn", nn.Parameter(torch.tensor(0.0)))
71
+ self.register_parameter("alpha_dense", nn.Parameter(torch.tensor(0.0)))
72
+
73
+ self.enabled = True
74
+
75
+ def forward(self, x: torch.Tensor, objs: torch.Tensor) -> torch.Tensor:
76
+ if not self.enabled:
77
+ return x
78
+
79
+ n_visual = x.shape[1]
80
+ objs = self.linear(objs)
81
+
82
+ x = x + self.alpha_attn.tanh() * self.attn(self.norm1(torch.cat([x, objs], dim=1)))[:, :n_visual, :]
83
+ x = x + self.alpha_dense.tanh() * self.ff(self.norm2(x))
84
+
85
+ return x
86
+
87
+
88
+ @maybe_allow_in_graph
89
+ class BasicTransformerBlock(nn.Module):
90
+ r"""
91
+ A basic Transformer block.
92
+
93
+ Parameters:
94
+ dim (`int`): The number of channels in the input and output.
95
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
96
+ attention_head_dim (`int`): The number of channels in each head.
97
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
98
+ cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
99
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
100
+ num_embeds_ada_norm (:
101
+ obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
102
+ attention_bias (:
103
+ obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
104
+ only_cross_attention (`bool`, *optional*):
105
+ Whether to use only cross-attention layers. In this case two cross attention layers are used.
106
+ double_self_attention (`bool`, *optional*):
107
+ Whether to use two self-attention layers. In this case no cross attention layers are used.
108
+ upcast_attention (`bool`, *optional*):
109
+ Whether to upcast the attention computation to float32. This is useful for mixed precision training.
110
+ norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
111
+ Whether to use learnable elementwise affine parameters for normalization.
112
+ norm_type (`str`, *optional*, defaults to `"layer_norm"`):
113
+ The normalization layer to use. Can be `"layer_norm"`, `"ada_norm"` or `"ada_norm_zero"`.
114
+ final_dropout (`bool` *optional*, defaults to False):
115
+ Whether to apply a final dropout after the last feed-forward layer.
116
+ attention_type (`str`, *optional*, defaults to `"default"`):
117
+ The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`.
118
+ positional_embeddings (`str`, *optional*, defaults to `None`):
119
+ The type of positional embeddings to apply to.
120
+ num_positional_embeddings (`int`, *optional*, defaults to `None`):
121
+ The maximum number of positional embeddings to apply.
122
+ """
123
+
124
+ def __init__(
125
+ self,
126
+ dim: int,
127
+ num_attention_heads: int,
128
+ attention_head_dim: int,
129
+ dropout=0.0,
130
+ cross_attention_dim: Optional[int] = None,
131
+ activation_fn: str = "geglu",
132
+ num_embeds_ada_norm: Optional[int] = None,
133
+ attention_bias: bool = False,
134
+ only_cross_attention: bool = False,
135
+ double_self_attention: bool = False,
136
+ upcast_attention: bool = False,
137
+ norm_elementwise_affine: bool = True,
138
+ norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single', 'ada_norm_continuous', 'layer_norm_i2vgen'
139
+ norm_eps: float = 1e-5,
140
+ final_dropout: bool = False,
141
+ attention_type: str = "default",
142
+ positional_embeddings: Optional[str] = None,
143
+ num_positional_embeddings: Optional[int] = None,
144
+ ada_norm_continous_conditioning_embedding_dim: Optional[int] = None,
145
+ ada_norm_bias: Optional[int] = None,
146
+ ff_inner_dim: Optional[int] = None,
147
+ ff_bias: bool = True,
148
+ attention_out_bias: bool = True,
149
+ dual_attention: bool = False,
150
+ ):
151
+ super().__init__()
152
+ self.only_cross_attention = only_cross_attention
153
+
154
+ # We keep these boolean flags for backward-compatibility.
155
+ self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
156
+ self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
157
+ self.use_ada_layer_norm_single = norm_type == "ada_norm_single"
158
+ self.use_layer_norm = norm_type == "layer_norm"
159
+ self.use_ada_layer_norm_continuous = norm_type == "ada_norm_continuous"
160
+
161
+ if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
162
+ raise ValueError(
163
+ f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
164
+ f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
165
+ )
166
+
167
+ self.norm_type = norm_type
168
+ self.num_embeds_ada_norm = num_embeds_ada_norm
169
+ self.dual_attention = dual_attention
170
+
171
+ if positional_embeddings and (num_positional_embeddings is None):
172
+ raise ValueError(
173
+ "If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined."
174
+ )
175
+
176
+ if positional_embeddings == "sinusoidal":
177
+ self.pos_embed = SinusoidalPositionalEmbedding(dim, max_seq_length=num_positional_embeddings)
178
+ else:
179
+ self.pos_embed = None
180
+
181
+ # Define 3 blocks. Each block has its own normalization layer.
182
+ # 1. Self-Attn
183
+ if norm_type == "ada_norm":
184
+ self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
185
+ elif norm_type == "ada_norm_zero":
186
+ self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
187
+ elif norm_type == "ada_norm_continuous":
188
+ self.norm1 = AdaLayerNormContinuous(
189
+ dim,
190
+ ada_norm_continous_conditioning_embedding_dim,
191
+ norm_elementwise_affine,
192
+ norm_eps,
193
+ ada_norm_bias,
194
+ "rms_norm",
195
+ )
196
+ else:
197
+ self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
198
+
199
+ self.attn1 = Attention(
200
+ query_dim=dim,
201
+ heads=num_attention_heads,
202
+ dim_head=attention_head_dim,
203
+ dropout=dropout,
204
+ bias=attention_bias,
205
+ cross_attention_dim=cross_attention_dim if only_cross_attention else None,
206
+ upcast_attention=upcast_attention,
207
+ out_bias=attention_out_bias,
208
+ )
209
+
210
+ # 2. Cross-Attn
211
+ if cross_attention_dim is not None or double_self_attention:
212
+ # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
213
+ # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
214
+ # the second cross attention block.
215
+ if norm_type == "ada_norm":
216
+ self.norm2 = AdaLayerNorm(dim, num_embeds_ada_norm)
217
+ elif norm_type == "ada_norm_continuous":
218
+ self.norm2 = AdaLayerNormContinuous(
219
+ dim,
220
+ ada_norm_continous_conditioning_embedding_dim,
221
+ norm_elementwise_affine,
222
+ norm_eps,
223
+ ada_norm_bias,
224
+ "rms_norm",
225
+ )
226
+ else:
227
+ self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
228
+
229
+ self.attn2 = Attention(
230
+ query_dim=dim,
231
+ cross_attention_dim=cross_attention_dim if not double_self_attention else None,
232
+ heads=num_attention_heads,
233
+ dim_head=attention_head_dim,
234
+ dropout=dropout,
235
+ bias=attention_bias,
236
+ upcast_attention=upcast_attention,
237
+ out_bias=attention_out_bias,
238
+ ) # is self-attn if encoder_hidden_states is none
239
+
240
+ if dual_attention:
241
+
242
+ self.attn3 = Attention(
243
+ query_dim=dim,
244
+ cross_attention_dim=None,
245
+ heads=num_attention_heads,
246
+ dim_head=attention_head_dim,
247
+ dropout=dropout,
248
+ bias=attention_bias,
249
+ upcast_attention=upcast_attention,
250
+ out_bias=attention_out_bias,
251
+ processor=DualAttnProcessor(hidden_size=dim),
252
+ dual_attn=True
253
+ )
254
+ else:
255
+ self.norm2 = None
256
+ self.attn2 = None
257
+
258
+ # 3. Feed-forward
259
+ if norm_type == "ada_norm_continuous":
260
+ self.norm3 = AdaLayerNormContinuous(
261
+ dim,
262
+ ada_norm_continous_conditioning_embedding_dim,
263
+ norm_elementwise_affine,
264
+ norm_eps,
265
+ ada_norm_bias,
266
+ "layer_norm",
267
+ )
268
+
269
+ elif norm_type in ["ada_norm_zero", "ada_norm", "layer_norm", "ada_norm_continuous"]:
270
+ self.norm3 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
271
+ elif norm_type == "layer_norm_i2vgen":
272
+ self.norm3 = None
273
+
274
+ self.ff = FeedForward(
275
+ dim,
276
+ dropout=dropout,
277
+ activation_fn=activation_fn,
278
+ final_dropout=final_dropout,
279
+ inner_dim=ff_inner_dim,
280
+ bias=ff_bias,
281
+ )
282
+
283
+ # 4. Fuser
284
+ if attention_type == "gated" or attention_type == "gated-text-image":
285
+ self.fuser = GatedSelfAttentionDense(dim, cross_attention_dim, num_attention_heads, attention_head_dim)
286
+
287
+ # 5. Scale-shift for PixArt-Alpha.
288
+ if norm_type == "ada_norm_single":
289
+ self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)
290
+
291
+ # let chunk size default to None
292
+ self._chunk_size = None
293
+ self._chunk_dim = 0
294
+
295
+ def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
296
+ # Sets chunk feed-forward
297
+ self._chunk_size = chunk_size
298
+ self._chunk_dim = dim
299
+
300
+ def forward(
301
+ self,
302
+ hidden_states: torch.FloatTensor,
303
+ attention_mask: Optional[torch.FloatTensor] = None,
304
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
305
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
306
+ timestep: Optional[torch.LongTensor] = None,
307
+ cross_attention_kwargs: Dict[str, Any] = None,
308
+ class_labels: Optional[torch.LongTensor] = None,
309
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
310
+ ) -> torch.FloatTensor:
311
+ if cross_attention_kwargs is not None:
312
+ if cross_attention_kwargs.get("scale", None) is not None:
313
+ logger.warning("Passing `scale` to `cross_attention_kwargs` is depcrecated. `scale` will be ignored.")
314
+
315
+ # Notice that normalization is always applied before the real computation in the following blocks.
316
+ # 0. Self-Attention
317
+ batch_size = hidden_states.shape[0]
318
+
319
+ if self.norm_type == "ada_norm":
320
+ norm_hidden_states = self.norm1(hidden_states, timestep)
321
+ elif self.norm_type == "ada_norm_zero":
322
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
323
+ hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
324
+ )
325
+ elif self.norm_type in ["layer_norm", "layer_norm_i2vgen"]:
326
+ norm_hidden_states = self.norm1(hidden_states)
327
+ elif self.norm_type == "ada_norm_continuous":
328
+ norm_hidden_states = self.norm1(hidden_states, added_cond_kwargs["pooled_text_emb"])
329
+ elif self.norm_type == "ada_norm_single":
330
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
331
+ self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
332
+ ).chunk(6, dim=1)
333
+ norm_hidden_states = self.norm1(hidden_states)
334
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
335
+ norm_hidden_states = norm_hidden_states.squeeze(1)
336
+ else:
337
+ raise ValueError("Incorrect norm used")
338
+
339
+ if self.pos_embed is not None:
340
+ norm_hidden_states = self.pos_embed(norm_hidden_states)
341
+
342
+ # 1. Prepare GLIGEN inputs
343
+ cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
344
+ gligen_kwargs = cross_attention_kwargs.pop("gligen", None)
345
+
346
+ attn_output = self.attn1(
347
+ norm_hidden_states,
348
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
349
+ attention_mask=attention_mask,
350
+ **cross_attention_kwargs,
351
+ )
352
+ if self.norm_type == "ada_norm_zero":
353
+ attn_output = gate_msa.unsqueeze(1) * attn_output
354
+ elif self.norm_type == "ada_norm_single":
355
+ attn_output = gate_msa * attn_output
356
+
357
+ hidden_states = attn_output + hidden_states
358
+ if hidden_states.ndim == 4:
359
+ hidden_states = hidden_states.squeeze(1)
360
+
361
+ # 1.2 GLIGEN Control
362
+ if gligen_kwargs is not None:
363
+ hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"])
364
+
365
+ # 3. Cross-Attention
366
+ if self.attn2 is not None:
367
+ if self.norm_type == "ada_norm":
368
+ norm_hidden_states = self.norm2(hidden_states, timestep)
369
+ elif self.norm_type in ["ada_norm_zero", "layer_norm", "layer_norm_i2vgen"]:
370
+ norm_hidden_states = self.norm2(hidden_states)
371
+ elif self.norm_type == "ada_norm_single":
372
+ # For PixArt norm2 isn't applied here:
373
+ # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
374
+ norm_hidden_states = hidden_states
375
+ elif self.norm_type == "ada_norm_continuous":
376
+ norm_hidden_states = self.norm2(hidden_states, added_cond_kwargs["pooled_text_emb"])
377
+ else:
378
+ raise ValueError("Incorrect norm")
379
+
380
+ if self.pos_embed is not None and self.norm_type != "ada_norm_single":
381
+ norm_hidden_states = self.pos_embed(norm_hidden_states)
382
+
383
+ attn_output = self.attn2(
384
+ norm_hidden_states,
385
+ encoder_hidden_states=encoder_hidden_states,
386
+ attention_mask=encoder_attention_mask,
387
+ **cross_attention_kwargs,
388
+ )
389
+ hidden_states = attn_output + hidden_states
390
+
391
+ # 4. Feed-forward
392
+ # i2vgen doesn't have this norm 🤷‍♂️
393
+ if self.norm_type == "ada_norm_continuous":
394
+ norm_hidden_states = self.norm3(hidden_states, added_cond_kwargs["pooled_text_emb"])
395
+ elif not self.norm_type == "ada_norm_single":
396
+ norm_hidden_states = self.norm3(hidden_states)
397
+
398
+ if self.dual_attention:
399
+
400
+ attn_output = self.attn3(
401
+ norm_hidden_states,
402
+ encoder_hidden_states=None,
403
+ attention_mask=attention_mask,
404
+ **cross_attention_kwargs,
405
+ )
406
+
407
+ norm_hidden_states = attn_output + norm_hidden_states
408
+
409
+ if self.norm_type == "ada_norm_zero":
410
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
411
+
412
+ if self.norm_type == "ada_norm_single":
413
+ norm_hidden_states = self.norm2(hidden_states)
414
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
415
+
416
+ if self._chunk_size is not None:
417
+ # "feed_forward_chunk_size" can be used to save memory
418
+ ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size)
419
+ else:
420
+ ff_output = self.ff(norm_hidden_states)
421
+
422
+ if self.norm_type == "ada_norm_zero":
423
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
424
+ elif self.norm_type == "ada_norm_single":
425
+ ff_output = gate_mlp * ff_output
426
+
427
+ hidden_states = ff_output + hidden_states
428
+ if hidden_states.ndim == 4:
429
+ hidden_states = hidden_states.squeeze(1)
430
+
431
+ return hidden_states
432
+
433
+
434
+ @maybe_allow_in_graph
435
+ class TemporalBasicTransformerBlock(nn.Module):
436
+ r"""
437
+ A basic Transformer block for video like data.
438
+
439
+ Parameters:
440
+ dim (`int`): The number of channels in the input and output.
441
+ time_mix_inner_dim (`int`): The number of channels for temporal attention.
442
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
443
+ attention_head_dim (`int`): The number of channels in each head.
444
+ cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
445
+ """
446
+
447
+ def __init__(
448
+ self,
449
+ dim: int,
450
+ time_mix_inner_dim: int,
451
+ num_attention_heads: int,
452
+ attention_head_dim: int,
453
+ cross_attention_dim: Optional[int] = None,
454
+ ):
455
+ super().__init__()
456
+ self.is_res = dim == time_mix_inner_dim
457
+
458
+ self.norm_in = nn.LayerNorm(dim)
459
+
460
+ # Define 3 blocks. Each block has its own normalization layer.
461
+ # 1. Self-Attn
462
+ self.ff_in = FeedForward(
463
+ dim,
464
+ dim_out=time_mix_inner_dim,
465
+ activation_fn="geglu",
466
+ )
467
+
468
+ self.norm1 = nn.LayerNorm(time_mix_inner_dim)
469
+ self.attn1 = Attention(
470
+ query_dim=time_mix_inner_dim,
471
+ heads=num_attention_heads,
472
+ dim_head=attention_head_dim,
473
+ cross_attention_dim=None,
474
+ )
475
+
476
+ # 2. Cross-Attn
477
+ if cross_attention_dim is not None:
478
+ # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
479
+ # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
480
+ # the second cross attention block.
481
+ self.norm2 = nn.LayerNorm(time_mix_inner_dim)
482
+ self.attn2 = Attention(
483
+ query_dim=time_mix_inner_dim,
484
+ cross_attention_dim=cross_attention_dim,
485
+ heads=num_attention_heads,
486
+ dim_head=attention_head_dim,
487
+ ) # is self-attn if encoder_hidden_states is none
488
+ else:
489
+ self.norm2 = None
490
+ self.attn2 = None
491
+
492
+ # 3. Feed-forward
493
+ self.norm3 = nn.LayerNorm(time_mix_inner_dim)
494
+ self.ff = FeedForward(time_mix_inner_dim, activation_fn="geglu")
495
+
496
+ # let chunk size default to None
497
+ self._chunk_size = None
498
+ self._chunk_dim = None
499
+
500
+ def set_chunk_feed_forward(self, chunk_size: Optional[int], **kwargs):
501
+ # Sets chunk feed-forward
502
+ self._chunk_size = chunk_size
503
+ # chunk dim should be hardcoded to 1 to have better speed vs. memory trade-off
504
+ self._chunk_dim = 1
505
+
506
+ def forward(
507
+ self,
508
+ hidden_states: torch.FloatTensor,
509
+ num_frames: int,
510
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
511
+ ) -> torch.FloatTensor:
512
+ # Notice that normalization is always applied before the real computation in the following blocks.
513
+ # 0. Self-Attention
514
+ batch_size = hidden_states.shape[0]
515
+
516
+ batch_frames, seq_length, channels = hidden_states.shape
517
+ batch_size = batch_frames // num_frames
518
+
519
+ hidden_states = hidden_states[None, :].reshape(batch_size, num_frames, seq_length, channels)
520
+ hidden_states = hidden_states.permute(0, 2, 1, 3)
521
+ hidden_states = hidden_states.reshape(batch_size * seq_length, num_frames, channels)
522
+
523
+ residual = hidden_states
524
+ hidden_states = self.norm_in(hidden_states)
525
+
526
+ if self._chunk_size is not None:
527
+ hidden_states = _chunked_feed_forward(self.ff_in, hidden_states, self._chunk_dim, self._chunk_size)
528
+ else:
529
+ hidden_states = self.ff_in(hidden_states)
530
+
531
+ if self.is_res:
532
+ hidden_states = hidden_states + residual
533
+
534
+ norm_hidden_states = self.norm1(hidden_states)
535
+ attn_output = self.attn1(norm_hidden_states, encoder_hidden_states=None)
536
+ hidden_states = attn_output + hidden_states
537
+
538
+ # 3. Cross-Attention
539
+ if self.attn2 is not None:
540
+ norm_hidden_states = self.norm2(hidden_states)
541
+ attn_output = self.attn2(norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
542
+ hidden_states = attn_output + hidden_states
543
+
544
+ # 4. Feed-forward
545
+ norm_hidden_states = self.norm3(hidden_states)
546
+
547
+ if self._chunk_size is not None:
548
+ ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size)
549
+ else:
550
+ ff_output = self.ff(norm_hidden_states)
551
+
552
+ if self.is_res:
553
+ hidden_states = ff_output + hidden_states
554
+ else:
555
+ hidden_states = ff_output
556
+
557
+ hidden_states = hidden_states[None, :].reshape(batch_size, seq_length, num_frames, channels)
558
+ hidden_states = hidden_states.permute(0, 2, 1, 3)
559
+ hidden_states = hidden_states.reshape(batch_size * num_frames, seq_length, channels)
560
+
561
+ return hidden_states
562
+
563
+
564
+ class SkipFFTransformerBlock(nn.Module):
565
+ def __init__(
566
+ self,
567
+ dim: int,
568
+ num_attention_heads: int,
569
+ attention_head_dim: int,
570
+ kv_input_dim: int,
571
+ kv_input_dim_proj_use_bias: bool,
572
+ dropout=0.0,
573
+ cross_attention_dim: Optional[int] = None,
574
+ attention_bias: bool = False,
575
+ attention_out_bias: bool = True,
576
+ ):
577
+ super().__init__()
578
+ if kv_input_dim != dim:
579
+ self.kv_mapper = nn.Linear(kv_input_dim, dim, kv_input_dim_proj_use_bias)
580
+ else:
581
+ self.kv_mapper = None
582
+
583
+ self.norm1 = RMSNorm(dim, 1e-06)
584
+
585
+ self.attn1 = Attention(
586
+ query_dim=dim,
587
+ heads=num_attention_heads,
588
+ dim_head=attention_head_dim,
589
+ dropout=dropout,
590
+ bias=attention_bias,
591
+ cross_attention_dim=cross_attention_dim,
592
+ out_bias=attention_out_bias,
593
+ )
594
+
595
+ self.norm2 = RMSNorm(dim, 1e-06)
596
+
597
+ self.attn2 = Attention(
598
+ query_dim=dim,
599
+ cross_attention_dim=cross_attention_dim,
600
+ heads=num_attention_heads,
601
+ dim_head=attention_head_dim,
602
+ dropout=dropout,
603
+ bias=attention_bias,
604
+ out_bias=attention_out_bias,
605
+ )
606
+
607
+ def forward(self, hidden_states, encoder_hidden_states, cross_attention_kwargs):
608
+ cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
609
+
610
+ if self.kv_mapper is not None:
611
+ encoder_hidden_states = self.kv_mapper(F.silu(encoder_hidden_states))
612
+
613
+ norm_hidden_states = self.norm1(hidden_states)
614
+
615
+ attn_output = self.attn1(
616
+ norm_hidden_states,
617
+ encoder_hidden_states=encoder_hidden_states,
618
+ **cross_attention_kwargs,
619
+ )
620
+
621
+ hidden_states = attn_output + hidden_states
622
+
623
+ norm_hidden_states = self.norm2(hidden_states)
624
+
625
+ attn_output = self.attn2(
626
+ norm_hidden_states,
627
+ encoder_hidden_states=encoder_hidden_states,
628
+ **cross_attention_kwargs,
629
+ )
630
+
631
+ hidden_states = attn_output + hidden_states
632
+
633
+ return hidden_states
634
+
635
+
636
+ class FeedForward(nn.Module):
637
+ r"""
638
+ A feed-forward layer.
639
+
640
+ Parameters:
641
+ dim (`int`): The number of channels in the input.
642
+ dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
643
+ mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
644
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
645
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
646
+ final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
647
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
648
+ """
649
+
650
+ def __init__(
651
+ self,
652
+ dim: int,
653
+ dim_out: Optional[int] = None,
654
+ mult: int = 4,
655
+ dropout: float = 0.0,
656
+ activation_fn: str = "geglu",
657
+ final_dropout: bool = False,
658
+ inner_dim=None,
659
+ bias: bool = True,
660
+ ):
661
+ super().__init__()
662
+ if inner_dim is None:
663
+ inner_dim = int(dim * mult)
664
+ dim_out = dim_out if dim_out is not None else dim
665
+ linear_cls = nn.Linear
666
+
667
+ if activation_fn == "gelu":
668
+ act_fn = GELU(dim, inner_dim, bias=bias)
669
+ if activation_fn == "gelu-approximate":
670
+ act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
671
+ elif activation_fn == "geglu":
672
+ act_fn = GEGLU(dim, inner_dim, bias=bias)
673
+ elif activation_fn == "geglu-approximate":
674
+ act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
675
+
676
+ self.net = nn.ModuleList([])
677
+ # project in
678
+ self.net.append(act_fn)
679
+ # project dropout
680
+ self.net.append(nn.Dropout(dropout))
681
+ # project out
682
+ self.net.append(linear_cls(inner_dim, dim_out, bias=bias))
683
+ # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
684
+ if final_dropout:
685
+ self.net.append(nn.Dropout(dropout))
686
+
687
+ def forward(self, hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
688
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
689
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
690
+ deprecate("scale", "1.0.0", deprecation_message)
691
+ for module in self.net:
692
+ hidden_states = module(hidden_states)
693
+ return hidden_states
StableDiffusion/Our_Pipe.py ADDED
@@ -0,0 +1,1014 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import torch
19
+ from packaging import version
20
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
21
+
22
+ from diffusers.configuration_utils import FrozenDict
23
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
24
+ # from .Our_Processor import VaeImageProcessor
25
+ from diffusers.loaders import FromSingleFileMixin, IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
26
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
27
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
28
+ from diffusers.schedulers import KarrasDiffusionSchedulers
29
+ from diffusers.utils import (
30
+ USE_PEFT_BACKEND,
31
+ deprecate,
32
+ logging,
33
+ replace_example_docstring,
34
+ scale_lora_layers,
35
+ unscale_lora_layers,
36
+ )
37
+ from diffusers.utils.torch_utils import randn_tensor
38
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
39
+ from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
40
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
41
+
42
+
43
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
44
+
45
+ EXAMPLE_DOC_STRING = """
46
+ Examples:
47
+ ```py
48
+ >>> import torch
49
+ >>> from diffusers import StableDiffusionPipeline
50
+
51
+ >>> pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
52
+ >>> pipe = pipe.to("cuda")
53
+
54
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
55
+ >>> image = pipe(prompt).images[0]
56
+ ```
57
+ """
58
+
59
+
60
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
61
+ """
62
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
63
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
64
+ """
65
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
66
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
67
+ # rescale the results from guidance (fixes overexposure)
68
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
69
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
70
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
71
+ return noise_cfg
72
+
73
+
74
+ def retrieve_timesteps(
75
+ scheduler,
76
+ num_inference_steps: Optional[int] = None,
77
+ device: Optional[Union[str, torch.device]] = None,
78
+ timesteps: Optional[List[int]] = None,
79
+ **kwargs,
80
+ ):
81
+ """
82
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
83
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
84
+
85
+ Args:
86
+ scheduler (`SchedulerMixin`):
87
+ The scheduler to get timesteps from.
88
+ num_inference_steps (`int`):
89
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
90
+ `timesteps` must be `None`.
91
+ device (`str` or `torch.device`, *optional*):
92
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
93
+ timesteps (`List[int]`, *optional*):
94
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
95
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
96
+ must be `None`.
97
+
98
+ Returns:
99
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
100
+ second element is the number of inference steps.
101
+ """
102
+ if timesteps is not None:
103
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
104
+ if not accepts_timesteps:
105
+ raise ValueError(
106
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
107
+ f" timestep schedules. Please check whether you are using the correct scheduler."
108
+ )
109
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
110
+ timesteps = scheduler.timesteps
111
+ num_inference_steps = len(timesteps)
112
+ else:
113
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
114
+ timesteps = scheduler.timesteps
115
+ return timesteps, num_inference_steps
116
+
117
+
118
+ class StableDiffusionPipeline(
119
+ DiffusionPipeline,
120
+ StableDiffusionMixin,
121
+ TextualInversionLoaderMixin,
122
+ LoraLoaderMixin,
123
+ IPAdapterMixin,
124
+ FromSingleFileMixin,
125
+ ):
126
+ r"""
127
+ Pipeline for text-to-image generation using Stable Diffusion.
128
+
129
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
130
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
131
+
132
+ The pipeline also inherits the following loading methods:
133
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
134
+ - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
135
+ - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
136
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
137
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
138
+
139
+ Args:
140
+ vae ([`AutoencoderKL`]):
141
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
142
+ text_encoder ([`~transformers.CLIPTextModel`]):
143
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
144
+ tokenizer ([`~transformers.CLIPTokenizer`]):
145
+ A `CLIPTokenizer` to tokenize text.
146
+ unet ([`UNet2DConditionModel`]):
147
+ A `UNet2DConditionModel` to denoise the encoded image latents.
148
+ scheduler ([`SchedulerMixin`]):
149
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
150
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
151
+ safety_checker ([`StableDiffusionSafetyChecker`]):
152
+ Classification module that estimates whether generated images could be considered offensive or harmful.
153
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
154
+ about a model's potential harms.
155
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
156
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
157
+ """
158
+
159
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
160
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
161
+ _exclude_from_cpu_offload = ["safety_checker"]
162
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
163
+
164
+ def __init__(
165
+ self,
166
+ vae: AutoencoderKL,
167
+ text_encoder: CLIPTextModel,
168
+ tokenizer: CLIPTokenizer,
169
+ unet: UNet2DConditionModel,
170
+ scheduler: KarrasDiffusionSchedulers,
171
+ safety_checker: StableDiffusionSafetyChecker,
172
+ feature_extractor: CLIPImageProcessor,
173
+ image_encoder: CLIPVisionModelWithProjection = None,
174
+ requires_safety_checker: bool = True,
175
+ ):
176
+ super().__init__()
177
+
178
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
179
+ deprecation_message = (
180
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
181
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
182
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
183
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
184
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
185
+ " file"
186
+ )
187
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
188
+ new_config = dict(scheduler.config)
189
+ new_config["steps_offset"] = 1
190
+ scheduler._internal_dict = FrozenDict(new_config)
191
+
192
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
193
+ deprecation_message = (
194
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
195
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
196
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
197
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
198
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
199
+ )
200
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
201
+ new_config = dict(scheduler.config)
202
+ new_config["clip_sample"] = False
203
+ scheduler._internal_dict = FrozenDict(new_config)
204
+
205
+ if safety_checker is None and requires_safety_checker:
206
+ logger.warning(
207
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
208
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
209
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
210
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
211
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
212
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
213
+ )
214
+
215
+ if safety_checker is not None and feature_extractor is None:
216
+ raise ValueError(
217
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
218
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
219
+ )
220
+
221
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
222
+ version.parse(unet.config._diffusers_version).base_version
223
+ ) < version.parse("0.9.0.dev0")
224
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
225
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
226
+ deprecation_message = (
227
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
228
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
229
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
230
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
231
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
232
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
233
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
234
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
235
+ " the `unet/config.json` file"
236
+ )
237
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
238
+ new_config = dict(unet.config)
239
+ new_config["sample_size"] = 64
240
+ unet._internal_dict = FrozenDict(new_config)
241
+
242
+ self.register_modules(
243
+ vae=vae,
244
+ text_encoder=text_encoder,
245
+ tokenizer=tokenizer,
246
+ unet=unet,
247
+ scheduler=scheduler,
248
+ safety_checker=safety_checker,
249
+ feature_extractor=feature_extractor,
250
+ image_encoder=image_encoder,
251
+ )
252
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
253
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
254
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
255
+
256
+ def _encode_prompt(
257
+ self,
258
+ prompt,
259
+ device,
260
+ num_images_per_prompt,
261
+ do_classifier_free_guidance,
262
+ negative_prompt=None,
263
+ prompt_embeds: Optional[torch.FloatTensor] = None,
264
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
265
+ lora_scale: Optional[float] = None,
266
+ **kwargs,
267
+ ):
268
+ deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
269
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
270
+
271
+ prompt_embeds_tuple = self.encode_prompt(
272
+ prompt=prompt,
273
+ device=device,
274
+ num_images_per_prompt=num_images_per_prompt,
275
+ do_classifier_free_guidance=do_classifier_free_guidance,
276
+ negative_prompt=negative_prompt,
277
+ prompt_embeds=prompt_embeds,
278
+ negative_prompt_embeds=negative_prompt_embeds,
279
+ lora_scale=lora_scale,
280
+ **kwargs,
281
+ )
282
+
283
+ # concatenate for backwards comp
284
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
285
+
286
+ return prompt_embeds
287
+
288
+ def encode_prompt(
289
+ self,
290
+ prompt,
291
+ device,
292
+ num_images_per_prompt,
293
+ do_classifier_free_guidance,
294
+ negative_prompt=None,
295
+ prompt_embeds: Optional[torch.FloatTensor] = None,
296
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
297
+ lora_scale: Optional[float] = None,
298
+ clip_skip: Optional[int] = None,
299
+ ):
300
+ r"""
301
+ Encodes the prompt into text encoder hidden states.
302
+
303
+ Args:
304
+ prompt (`str` or `List[str]`, *optional*):
305
+ prompt to be encoded
306
+ device: (`torch.device`):
307
+ torch device
308
+ num_images_per_prompt (`int`):
309
+ number of images that should be generated per prompt
310
+ do_classifier_free_guidance (`bool`):
311
+ whether to use classifier free guidance or not
312
+ negative_prompt (`str` or `List[str]`, *optional*):
313
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
314
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
315
+ less than `1`).
316
+ prompt_embeds (`torch.FloatTensor`, *optional*):
317
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
318
+ provided, text embeddings will be generated from `prompt` input argument.
319
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
320
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
321
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
322
+ argument.
323
+ lora_scale (`float`, *optional*):
324
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
325
+ clip_skip (`int`, *optional*):
326
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
327
+ the output of the pre-final layer will be used for computing the prompt embeddings.
328
+ """
329
+ # set lora scale so that monkey patched LoRA
330
+ # function of text encoder can correctly access it
331
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
332
+ self._lora_scale = lora_scale
333
+
334
+ # dynamically adjust the LoRA scale
335
+ if not USE_PEFT_BACKEND:
336
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
337
+ else:
338
+ scale_lora_layers(self.text_encoder, lora_scale)
339
+
340
+ if prompt is not None and isinstance(prompt, str):
341
+ batch_size = 1
342
+ elif prompt is not None and isinstance(prompt, list):
343
+ batch_size = len(prompt)
344
+ else:
345
+ batch_size = prompt_embeds.shape[0]
346
+
347
+ if prompt_embeds is None:
348
+ # textual inversion: process multi-vector tokens if necessary
349
+ if isinstance(self, TextualInversionLoaderMixin):
350
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
351
+
352
+ text_inputs = self.tokenizer(
353
+ prompt,
354
+ padding="max_length",
355
+ max_length=self.tokenizer.model_max_length,
356
+ truncation=True,
357
+ return_tensors="pt",
358
+ )
359
+ text_input_ids = text_inputs.input_ids
360
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
361
+
362
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
363
+ text_input_ids, untruncated_ids
364
+ ):
365
+ removed_text = self.tokenizer.batch_decode(
366
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
367
+ )
368
+ logger.warning(
369
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
370
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
371
+ )
372
+
373
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
374
+ attention_mask = text_inputs.attention_mask.to(device)
375
+ else:
376
+ attention_mask = None
377
+
378
+ if clip_skip is None:
379
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
380
+ prompt_embeds = prompt_embeds[0]
381
+ else:
382
+ prompt_embeds = self.text_encoder(
383
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
384
+ )
385
+ # Access the `hidden_states` first, that contains a tuple of
386
+ # all the hidden states from the encoder layers. Then index into
387
+ # the tuple to access the hidden states from the desired layer.
388
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
389
+ # We also need to apply the final LayerNorm here to not mess with the
390
+ # representations. The `last_hidden_states` that we typically use for
391
+ # obtaining the final prompt representations passes through the LayerNorm
392
+ # layer.
393
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
394
+
395
+ if self.text_encoder is not None:
396
+ prompt_embeds_dtype = self.text_encoder.dtype
397
+ elif self.unet is not None:
398
+ prompt_embeds_dtype = self.unet.dtype
399
+ else:
400
+ prompt_embeds_dtype = prompt_embeds.dtype
401
+
402
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
403
+
404
+ bs_embed, seq_len, _ = prompt_embeds.shape
405
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
406
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
407
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
408
+
409
+ # get unconditional embeddings for classifier free guidance
410
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
411
+ uncond_tokens: List[str]
412
+ if negative_prompt is None:
413
+ uncond_tokens = [""] * batch_size
414
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
415
+ raise TypeError(
416
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
417
+ f" {type(prompt)}."
418
+ )
419
+ elif isinstance(negative_prompt, str):
420
+ uncond_tokens = [negative_prompt]
421
+ elif batch_size != len(negative_prompt):
422
+ raise ValueError(
423
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
424
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
425
+ " the batch size of `prompt`."
426
+ )
427
+ else:
428
+ uncond_tokens = negative_prompt
429
+
430
+ # textual inversion: process multi-vector tokens if necessary
431
+ if isinstance(self, TextualInversionLoaderMixin):
432
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
433
+
434
+ max_length = prompt_embeds.shape[1]
435
+ uncond_input = self.tokenizer(
436
+ uncond_tokens,
437
+ padding="max_length",
438
+ max_length=max_length,
439
+ truncation=True,
440
+ return_tensors="pt",
441
+ )
442
+
443
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
444
+ attention_mask = uncond_input.attention_mask.to(device)
445
+ else:
446
+ attention_mask = None
447
+
448
+ negative_prompt_embeds = self.text_encoder(
449
+ uncond_input.input_ids.to(device),
450
+ attention_mask=attention_mask,
451
+ )
452
+ negative_prompt_embeds = negative_prompt_embeds[0]
453
+
454
+ if do_classifier_free_guidance:
455
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
456
+ seq_len = negative_prompt_embeds.shape[1]
457
+
458
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
459
+
460
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
461
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
462
+
463
+ if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
464
+ # Retrieve the original scale by scaling back the LoRA layers
465
+ unscale_lora_layers(self.text_encoder, lora_scale)
466
+
467
+ return prompt_embeds, negative_prompt_embeds
468
+
469
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
470
+ dtype = next(self.image_encoder.parameters()).dtype
471
+
472
+ if not isinstance(image, torch.Tensor):
473
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
474
+
475
+ image = image.to(device=device, dtype=dtype)
476
+ if output_hidden_states:
477
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
478
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
479
+ uncond_image_enc_hidden_states = self.image_encoder(
480
+ torch.zeros_like(image), output_hidden_states=True
481
+ ).hidden_states[-2]
482
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
483
+ num_images_per_prompt, dim=0
484
+ )
485
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
486
+ else:
487
+ image_embeds = self.image_encoder(image).image_embeds
488
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
489
+ uncond_image_embeds = torch.zeros_like(image_embeds)
490
+
491
+ return image_embeds, uncond_image_embeds
492
+
493
+ def prepare_ip_adapter_image_embeds(
494
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
495
+ ):
496
+ if ip_adapter_image_embeds is None:
497
+ if not isinstance(ip_adapter_image, list):
498
+ ip_adapter_image = [ip_adapter_image]
499
+
500
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
501
+ raise ValueError(
502
+ 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."
503
+ )
504
+
505
+ image_embeds = []
506
+ for single_ip_adapter_image, image_proj_layer in zip(
507
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
508
+ ):
509
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
510
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
511
+ single_ip_adapter_image, device, 1, output_hidden_state
512
+ )
513
+ single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
514
+ single_negative_image_embeds = torch.stack(
515
+ [single_negative_image_embeds] * num_images_per_prompt, dim=0
516
+ )
517
+
518
+ if do_classifier_free_guidance:
519
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
520
+ single_image_embeds = single_image_embeds.to(device)
521
+
522
+ image_embeds.append(single_image_embeds)
523
+ else:
524
+ repeat_dims = [1]
525
+ image_embeds = []
526
+ for single_image_embeds in ip_adapter_image_embeds:
527
+ if do_classifier_free_guidance:
528
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
529
+ single_image_embeds = single_image_embeds.repeat(
530
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
531
+ )
532
+ single_negative_image_embeds = single_negative_image_embeds.repeat(
533
+ num_images_per_prompt, *(repeat_dims * len(single_negative_image_embeds.shape[1:]))
534
+ )
535
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
536
+ else:
537
+ single_image_embeds = single_image_embeds.repeat(
538
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
539
+ )
540
+ image_embeds.append(single_image_embeds)
541
+
542
+ return image_embeds
543
+
544
+ def run_safety_checker(self, image, device, dtype):
545
+ if self.safety_checker is None:
546
+ has_nsfw_concept = None
547
+ else:
548
+ if torch.is_tensor(image):
549
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
550
+ else:
551
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
552
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
553
+ image, has_nsfw_concept = self.safety_checker(
554
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
555
+ )
556
+ return image, has_nsfw_concept
557
+
558
+ def decode_latents(self, latents):
559
+ deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
560
+ deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
561
+
562
+ latents = 1 / self.vae.config.scaling_factor * latents
563
+ image = self.vae.decode(latents, return_dict=False)[0]
564
+ image = (image / 2 + 0.5).clamp(0, 1)
565
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
566
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
567
+ return image
568
+
569
+ def prepare_extra_step_kwargs(self, generator, eta):
570
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
571
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
572
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
573
+ # and should be between [0, 1]
574
+
575
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
576
+ extra_step_kwargs = {}
577
+ if accepts_eta:
578
+ extra_step_kwargs["eta"] = eta
579
+
580
+ # check if the scheduler accepts generator
581
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
582
+ if accepts_generator:
583
+ extra_step_kwargs["generator"] = generator
584
+ return extra_step_kwargs
585
+
586
+ def check_inputs(
587
+ self,
588
+ prompt,
589
+ height,
590
+ width,
591
+ callback_steps,
592
+ negative_prompt=None,
593
+ prompt_embeds=None,
594
+ negative_prompt_embeds=None,
595
+ ip_adapter_image=None,
596
+ ip_adapter_image_embeds=None,
597
+ callback_on_step_end_tensor_inputs=None,
598
+ ):
599
+ if height % 8 != 0 or width % 8 != 0:
600
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
601
+
602
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
603
+ raise ValueError(
604
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
605
+ f" {type(callback_steps)}."
606
+ )
607
+ if callback_on_step_end_tensor_inputs is not None and not all(
608
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
609
+ ):
610
+ raise ValueError(
611
+ 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]}"
612
+ )
613
+
614
+ if prompt is not None and prompt_embeds is not None:
615
+ raise ValueError(
616
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
617
+ " only forward one of the two."
618
+ )
619
+ elif prompt is None and prompt_embeds is None:
620
+ raise ValueError(
621
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
622
+ )
623
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
624
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
625
+
626
+ if negative_prompt is not None and negative_prompt_embeds is not None:
627
+ raise ValueError(
628
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
629
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
630
+ )
631
+
632
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
633
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
634
+ raise ValueError(
635
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
636
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
637
+ f" {negative_prompt_embeds.shape}."
638
+ )
639
+
640
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
641
+ raise ValueError(
642
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
643
+ )
644
+
645
+ if ip_adapter_image_embeds is not None:
646
+ if not isinstance(ip_adapter_image_embeds, list):
647
+ raise ValueError(
648
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
649
+ )
650
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
651
+ raise ValueError(
652
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
653
+ )
654
+
655
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
656
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
657
+ if isinstance(generator, list) and len(generator) != batch_size:
658
+ raise ValueError(
659
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
660
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
661
+ )
662
+
663
+ if latents is None:
664
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
665
+ else:
666
+ latents = latents.to(device)
667
+
668
+ # scale the initial noise by the standard deviation required by the scheduler
669
+ latents = latents * self.scheduler.init_noise_sigma
670
+ return latents
671
+
672
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
673
+ def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
674
+ """
675
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
676
+
677
+ Args:
678
+ timesteps (`torch.Tensor`):
679
+ generate embedding vectors at these timesteps
680
+ embedding_dim (`int`, *optional*, defaults to 512):
681
+ dimension of the embeddings to generate
682
+ dtype:
683
+ data type of the generated embeddings
684
+
685
+ Returns:
686
+ `torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
687
+ """
688
+ assert len(w.shape) == 1
689
+ w = w * 1000.0
690
+
691
+ half_dim = embedding_dim // 2
692
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
693
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
694
+ emb = w.to(dtype)[:, None] * emb[None, :]
695
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
696
+ if embedding_dim % 2 == 1: # zero pad
697
+ emb = torch.nn.functional.pad(emb, (0, 1))
698
+ assert emb.shape == (w.shape[0], embedding_dim)
699
+ return emb
700
+
701
+ @property
702
+ def guidance_scale(self):
703
+ return self._guidance_scale
704
+
705
+ @property
706
+ def guidance_rescale(self):
707
+ return self._guidance_rescale
708
+
709
+ @property
710
+ def clip_skip(self):
711
+ return self._clip_skip
712
+
713
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
714
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
715
+ # corresponds to doing no classifier free guidance.
716
+ @property
717
+ def do_classifier_free_guidance(self):
718
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
719
+
720
+ @property
721
+ def cross_attention_kwargs(self):
722
+ return self._cross_attention_kwargs
723
+
724
+ @property
725
+ def num_timesteps(self):
726
+ return self._num_timesteps
727
+
728
+ @property
729
+ def interrupt(self):
730
+ return self._interrupt
731
+
732
+ @torch.no_grad()
733
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
734
+ def __call__(
735
+ self,
736
+ prompt: Union[str, List[str]] = None,
737
+ height: Optional[int] = None,
738
+ width: Optional[int] = None,
739
+ num_inference_steps: int = 50,
740
+ timesteps: List[int] = None,
741
+ guidance_scale: float = 7.5,
742
+ negative_prompt: Optional[Union[str, List[str]]] = None,
743
+ num_images_per_prompt: Optional[int] = 1,
744
+ eta: float = 0.0,
745
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
746
+ latents: Optional[torch.FloatTensor] = None,
747
+ prompt_embeds: Optional[torch.FloatTensor] = None,
748
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
749
+ ip_adapter_image: Optional[PipelineImageInput] = None,
750
+ ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None,
751
+ output_type: Optional[str] = "pil",
752
+ return_dict: bool = True,
753
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
754
+ guidance_rescale: float = 0.0,
755
+ clip_skip: Optional[int] = None,
756
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
757
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
758
+ **kwargs,
759
+ ):
760
+ r"""
761
+ The call function to the pipeline for generation.
762
+
763
+ Args:
764
+ prompt (`str` or `List[str]`, *optional*):
765
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
766
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
767
+ The height in pixels of the generated image.
768
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
769
+ The width in pixels of the generated image.
770
+ num_inference_steps (`int`, *optional*, defaults to 50):
771
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
772
+ expense of slower inference.
773
+ timesteps (`List[int]`, *optional*):
774
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
775
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
776
+ passed will be used. Must be in descending order.
777
+ guidance_scale (`float`, *optional*, defaults to 7.5):
778
+ A higher guidance scale value encourages the model to generate images closely linked to the text
779
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
780
+ negative_prompt (`str` or `List[str]`, *optional*):
781
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
782
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
783
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
784
+ The number of images to generate per prompt.
785
+ eta (`float`, *optional*, defaults to 0.0):
786
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
787
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
788
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
789
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
790
+ generation deterministic.
791
+ latents (`torch.FloatTensor`, *optional*):
792
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
793
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
794
+ tensor is generated by sampling using the supplied random `generator`.
795
+ prompt_embeds (`torch.FloatTensor`, *optional*):
796
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
797
+ provided, text embeddings are generated from the `prompt` input argument.
798
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
799
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
800
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
801
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
802
+ ip_adapter_image_embeds (`List[torch.FloatTensor]`, *optional*):
803
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters.
804
+ Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should contain the negative image embedding
805
+ if `do_classifier_free_guidance` is set to `True`.
806
+ If not provided, embeddings are computed from the `ip_adapter_image` input argument.
807
+ output_type (`str`, *optional*, defaults to `"pil"`):
808
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
809
+ return_dict (`bool`, *optional*, defaults to `True`):
810
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
811
+ plain tuple.
812
+ cross_attention_kwargs (`dict`, *optional*):
813
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
814
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
815
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
816
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
817
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
818
+ using zero terminal SNR.
819
+ clip_skip (`int`, *optional*):
820
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
821
+ the output of the pre-final layer will be used for computing the prompt embeddings.
822
+ callback_on_step_end (`Callable`, *optional*):
823
+ A function that calls at the end of each denoising steps during the inference. The function is called
824
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
825
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
826
+ `callback_on_step_end_tensor_inputs`.
827
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
828
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
829
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
830
+ `._callback_tensor_inputs` attribute of your pipeline class.
831
+
832
+ Examples:
833
+
834
+ Returns:
835
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
836
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
837
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
838
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
839
+ "not-safe-for-work" (nsfw) content.
840
+ """
841
+
842
+ callback = kwargs.pop("callback", None)
843
+ callback_steps = kwargs.pop("callback_steps", None)
844
+
845
+ if callback is not None:
846
+ deprecate(
847
+ "callback",
848
+ "1.0.0",
849
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
850
+ )
851
+ if callback_steps is not None:
852
+ deprecate(
853
+ "callback_steps",
854
+ "1.0.0",
855
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
856
+ )
857
+
858
+ # 0. Default height and width to unet
859
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
860
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
861
+ # to deal with lora scaling and other possible forward hooks
862
+
863
+ # 1. Check inputs. Raise error if not correct
864
+ self.check_inputs(
865
+ prompt,
866
+ height,
867
+ width,
868
+ callback_steps,
869
+ negative_prompt,
870
+ prompt_embeds,
871
+ negative_prompt_embeds,
872
+ ip_adapter_image,
873
+ ip_adapter_image_embeds,
874
+ callback_on_step_end_tensor_inputs,
875
+ )
876
+
877
+ self._guidance_scale = guidance_scale
878
+ self._guidance_rescale = guidance_rescale
879
+ self._clip_skip = clip_skip
880
+ self._cross_attention_kwargs = cross_attention_kwargs
881
+ self._interrupt = False
882
+
883
+ # 2. Define call parameters
884
+ if prompt is not None and isinstance(prompt, str):
885
+ batch_size = 1
886
+ elif prompt is not None and isinstance(prompt, list):
887
+ batch_size = len(prompt)
888
+ else:
889
+ batch_size = prompt_embeds.shape[0]
890
+
891
+ device = self._execution_device
892
+
893
+ # 3. Encode input prompt
894
+ lora_scale = (
895
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
896
+ )
897
+
898
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
899
+ prompt,
900
+ device,
901
+ num_images_per_prompt,
902
+ self.do_classifier_free_guidance,
903
+ negative_prompt,
904
+ prompt_embeds=prompt_embeds,
905
+ negative_prompt_embeds=negative_prompt_embeds,
906
+ lora_scale=lora_scale,
907
+ clip_skip=self.clip_skip,
908
+ )
909
+
910
+ # For classifier free guidance, we need to do two forward passes.
911
+ # Here we concatenate the unconditional and text embeddings into a single batch
912
+ # to avoid doing two forward passes
913
+ if self.do_classifier_free_guidance:
914
+ prompt_embeds = torch.cat([prompt_embeds, negative_prompt_embeds])
915
+
916
+ # 4. Prepare timesteps
917
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
918
+
919
+ # 5. Prepare latent variables
920
+ num_channels_latents = self.unet.config.in_channels
921
+ latents = self.prepare_latents(
922
+ batch_size * num_images_per_prompt,
923
+ num_channels_latents,
924
+ height,
925
+ width,
926
+ prompt_embeds.dtype,
927
+ device,
928
+ generator,
929
+ latents,
930
+ ) # [2, 4, 64, 64]: img_latents, mask_latents
931
+
932
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
933
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
934
+
935
+ # 6.1 Add image embeds for IP-Adapter
936
+ added_cond_kwargs = (
937
+ None
938
+ )
939
+
940
+ # 6.2 Optionally get Guidance Scale Embedding
941
+ timestep_cond = None
942
+ if self.unet.config.time_cond_proj_dim is not None:
943
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
944
+ timestep_cond = self.get_guidance_scale_embedding(
945
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
946
+ ).to(device=device, dtype=latents.dtype)
947
+
948
+ # 7. Denoising loop
949
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
950
+ self._num_timesteps = len(timesteps)
951
+
952
+ img_latents, mask_latents = latents.chunk(2)
953
+
954
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
955
+ for i, t in enumerate(timesteps):
956
+ if self.interrupt:
957
+ continue
958
+
959
+ # expand the latents if we are doing classifier free guidance
960
+ img_latent_model_input = torch.cat([img_latents] * 2) if self.do_classifier_free_guidance else img_latents
961
+ mask_latent_model_input = torch.cat([mask_latents] * 2) if self.do_classifier_free_guidance else mask_latents
962
+ latent_model_input = torch.cat([img_latent_model_input, mask_latent_model_input], dim=0)
963
+
964
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
965
+
966
+ # predict the noise residual
967
+ # print(latent_model_input.shape, t)
968
+ noise_pred = self.unet(
969
+ latent_model_input,
970
+ t,
971
+ encoder_hidden_states=prompt_embeds,
972
+ timestep_cond=timestep_cond,
973
+ cross_attention_kwargs=self.cross_attention_kwargs,
974
+ added_cond_kwargs=added_cond_kwargs,
975
+ return_dict=False,
976
+ )[0]
977
+
978
+ # perform guidance
979
+ if self.do_classifier_free_guidance:
980
+ img_noise_pred_text, img_noise_pred_uncond, mask_noise_pred_text, mask_noise_pred_uncond = noise_pred.chunk(4, dim=0)
981
+ img_noise_pred = img_noise_pred_uncond + self.guidance_scale * (img_noise_pred_text - img_noise_pred_uncond)
982
+ mask_noise_pred = mask_noise_pred_uncond + self.guidance_scale * (mask_noise_pred_text - mask_noise_pred_uncond)
983
+
984
+ # compute the previous noisy sample x_t -> x_t-1
985
+ img_latents = self.scheduler.step(img_noise_pred, t, img_latents, **extra_step_kwargs, return_dict=False)[0]
986
+ mask_latents = self.scheduler.step(mask_noise_pred, t, mask_latents, **extra_step_kwargs, return_dict=False)[0]
987
+
988
+ # call the callback, if provided
989
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
990
+ progress_bar.update()
991
+
992
+ if not output_type == "latent":
993
+ latents = torch.cat([img_latents, mask_latents], dim=0)
994
+ latents = latents.to(torch.float16)
995
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
996
+ 0
997
+ ]
998
+ # image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
999
+ else:
1000
+ image = latents
1001
+ has_nsfw_concept = None
1002
+
1003
+ # if has_nsfw_concept is None:
1004
+ do_denormalize = [True] * image.shape[0]
1005
+
1006
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1007
+
1008
+ # Offload all models
1009
+ self.maybe_free_model_hooks()
1010
+
1011
+ if not return_dict:
1012
+ return (image, None)
1013
+
1014
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=None)
StableDiffusion/Our_Processor.py ADDED
@@ -0,0 +1,994 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
28
+
29
+ PipelineImageInput = Union[
30
+ PIL.Image.Image,
31
+ np.ndarray,
32
+ torch.FloatTensor,
33
+ List[PIL.Image.Image],
34
+ List[np.ndarray],
35
+ List[torch.FloatTensor],
36
+ ]
37
+
38
+ PipelineDepthInput = PipelineImageInput
39
+
40
+
41
+ class VaeImageProcessor(ConfigMixin):
42
+ """
43
+ Image processor for VAE.
44
+
45
+ Args:
46
+ do_resize (`bool`, *optional*, defaults to `True`):
47
+ Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
48
+ `height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
49
+ vae_scale_factor (`int`, *optional*, defaults to `8`):
50
+ VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
51
+ resample (`str`, *optional*, defaults to `lanczos`):
52
+ Resampling filter to use when resizing the image.
53
+ do_normalize (`bool`, *optional*, defaults to `True`):
54
+ Whether to normalize the image to [-1,1].
55
+ do_binarize (`bool`, *optional*, defaults to `False`):
56
+ Whether to binarize the image to 0/1.
57
+ do_convert_rgb (`bool`, *optional*, defaults to be `False`):
58
+ Whether to convert the images to RGB format.
59
+ do_convert_grayscale (`bool`, *optional*, defaults to be `False`):
60
+ Whether to convert the images to grayscale format.
61
+ """
62
+
63
+ config_name = CONFIG_NAME
64
+
65
+ @register_to_config
66
+ def __init__(
67
+ self,
68
+ do_resize: bool = True,
69
+ vae_scale_factor: int = 8,
70
+ resample: str = "lanczos",
71
+ do_normalize: bool = True,
72
+ do_binarize: bool = False,
73
+ do_convert_rgb: bool = False,
74
+ do_convert_grayscale: bool = False,
75
+ ):
76
+ super().__init__()
77
+ if do_convert_rgb and do_convert_grayscale:
78
+ raise ValueError(
79
+ "`do_convert_rgb` and `do_convert_grayscale` can not both be set to `True`,"
80
+ " if you intended to convert the image into RGB format, please set `do_convert_grayscale = False`.",
81
+ " if you intended to convert the image into grayscale format, please set `do_convert_rgb = False`",
82
+ )
83
+ self.config.do_convert_rgb = False
84
+
85
+ @staticmethod
86
+ def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
87
+ """
88
+ Convert a numpy image or a batch of images to a PIL image.
89
+ """
90
+ if images.ndim == 3:
91
+ images = images[None, ...]
92
+ images = (images * 255).round().astype("uint8")
93
+ if images.shape[-1] == 1:
94
+ # special case for grayscale (single channel) images
95
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
96
+ else:
97
+ pil_images = [Image.fromarray(image) for image in images]
98
+
99
+ return pil_images
100
+
101
+ @staticmethod
102
+ def pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
103
+ """
104
+ Convert a PIL image or a list of PIL images to NumPy arrays.
105
+ """
106
+ if not isinstance(images, list):
107
+ images = [images]
108
+ images = [np.array(image).astype(np.float32) / 255.0 for image in images]
109
+ images = np.stack(images, axis=0)
110
+
111
+ return images
112
+
113
+ @staticmethod
114
+ def numpy_to_pt(images: np.ndarray) -> torch.FloatTensor:
115
+ """
116
+ Convert a NumPy image to a PyTorch tensor.
117
+ """
118
+ if images.ndim == 3:
119
+ images = images[..., None]
120
+
121
+ images = torch.from_numpy(images.transpose(0, 3, 1, 2))
122
+ return images
123
+
124
+ @staticmethod
125
+ def pt_to_numpy(images: torch.FloatTensor) -> np.ndarray:
126
+ """
127
+ Convert a PyTorch tensor to a NumPy image.
128
+ """
129
+ images = images.cpu().permute(0, 2, 3, 1).float().numpy()
130
+ return images
131
+
132
+ @staticmethod
133
+ def normalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
134
+ """
135
+ Normalize an image array to [-1,1].
136
+ """
137
+ return 2.0 * images - 1.0
138
+
139
+ @staticmethod
140
+ def denormalize(x_hat):
141
+
142
+ mean = torch.tensor([0.5, 0.5, 0.5]).to(x_hat.device)
143
+ std = torch.tensor([0.5, 0.5, 0.5]).to(x_hat.device)
144
+ x = x_hat * std.view(3, 1, 1) + mean.view(3, 1, 1)
145
+ x = x * 255.0
146
+ x = torch.clamp(x, 0, 255).cpu().numpy().astype(np.uint8).transpose(1, 2, 0)
147
+
148
+ return x
149
+
150
+ @staticmethod
151
+ def convert_to_rgb(image: PIL.Image.Image) -> PIL.Image.Image:
152
+ """
153
+ Converts a PIL image to RGB format.
154
+ """
155
+ image = image.convert("RGB")
156
+
157
+ return image
158
+
159
+ @staticmethod
160
+ def convert_to_grayscale(image: PIL.Image.Image) -> PIL.Image.Image:
161
+ """
162
+ Converts a PIL image to grayscale format.
163
+ """
164
+ image = image.convert("L")
165
+
166
+ return image
167
+
168
+ @staticmethod
169
+ def blur(image: PIL.Image.Image, blur_factor: int = 4) -> PIL.Image.Image:
170
+ """
171
+ Applies Gaussian blur to an image.
172
+ """
173
+ image = image.filter(ImageFilter.GaussianBlur(blur_factor))
174
+
175
+ return image
176
+
177
+ @staticmethod
178
+ def get_crop_region(mask_image: PIL.Image.Image, width: int, height: int, pad=0):
179
+ """
180
+ Finds a rectangular region that contains all masked ares in an image, and expands region to match the aspect ratio of the original image;
181
+ for example, if user drew mask in a 128x32 region, and the dimensions for processing are 512x512, the region will be expanded to 128x128.
182
+
183
+ Args:
184
+ mask_image (PIL.Image.Image): Mask image.
185
+ width (int): Width of the image to be processed.
186
+ height (int): Height of the image to be processed.
187
+ pad (int, optional): Padding to be added to the crop region. Defaults to 0.
188
+
189
+ Returns:
190
+ tuple: (x1, y1, x2, y2) represent a rectangular region that contains all masked ares in an image and matches the original aspect ratio.
191
+ """
192
+
193
+ mask_image = mask_image.convert("L")
194
+ mask = np.array(mask_image)
195
+
196
+ # 1. find a rectangular region that contains all masked ares in an image
197
+ h, w = mask.shape
198
+ crop_left = 0
199
+ for i in range(w):
200
+ if not (mask[:, i] == 0).all():
201
+ break
202
+ crop_left += 1
203
+
204
+ crop_right = 0
205
+ for i in reversed(range(w)):
206
+ if not (mask[:, i] == 0).all():
207
+ break
208
+ crop_right += 1
209
+
210
+ crop_top = 0
211
+ for i in range(h):
212
+ if not (mask[i] == 0).all():
213
+ break
214
+ crop_top += 1
215
+
216
+ crop_bottom = 0
217
+ for i in reversed(range(h)):
218
+ if not (mask[i] == 0).all():
219
+ break
220
+ crop_bottom += 1
221
+
222
+ # 2. add padding to the crop region
223
+ x1, y1, x2, y2 = (
224
+ int(max(crop_left - pad, 0)),
225
+ int(max(crop_top - pad, 0)),
226
+ int(min(w - crop_right + pad, w)),
227
+ int(min(h - crop_bottom + pad, h)),
228
+ )
229
+
230
+ # 3. expands crop region to match the aspect ratio of the image to be processed
231
+ ratio_crop_region = (x2 - x1) / (y2 - y1)
232
+ ratio_processing = width / height
233
+
234
+ if ratio_crop_region > ratio_processing:
235
+ desired_height = (x2 - x1) / ratio_processing
236
+ desired_height_diff = int(desired_height - (y2 - y1))
237
+ y1 -= desired_height_diff // 2
238
+ y2 += desired_height_diff - desired_height_diff // 2
239
+ if y2 >= mask_image.height:
240
+ diff = y2 - mask_image.height
241
+ y2 -= diff
242
+ y1 -= diff
243
+ if y1 < 0:
244
+ y2 -= y1
245
+ y1 -= y1
246
+ if y2 >= mask_image.height:
247
+ y2 = mask_image.height
248
+ else:
249
+ desired_width = (y2 - y1) * ratio_processing
250
+ desired_width_diff = int(desired_width - (x2 - x1))
251
+ x1 -= desired_width_diff // 2
252
+ x2 += desired_width_diff - desired_width_diff // 2
253
+ if x2 >= mask_image.width:
254
+ diff = x2 - mask_image.width
255
+ x2 -= diff
256
+ x1 -= diff
257
+ if x1 < 0:
258
+ x2 -= x1
259
+ x1 -= x1
260
+ if x2 >= mask_image.width:
261
+ x2 = mask_image.width
262
+
263
+ return x1, y1, x2, y2
264
+
265
+ def _resize_and_fill(
266
+ self,
267
+ image: PIL.Image.Image,
268
+ width: int,
269
+ height: int,
270
+ ) -> PIL.Image.Image:
271
+ """
272
+ 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.
273
+
274
+ Args:
275
+ image: The image to resize.
276
+ width: The width to resize the image to.
277
+ height: The height to resize the image to.
278
+ """
279
+
280
+ ratio = width / height
281
+ src_ratio = image.width / image.height
282
+
283
+ src_w = width if ratio < src_ratio else image.width * height // image.height
284
+ src_h = height if ratio >= src_ratio else image.height * width // image.width
285
+
286
+ resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION["lanczos"])
287
+ res = Image.new("RGB", (width, height))
288
+ res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
289
+
290
+ if ratio < src_ratio:
291
+ fill_height = height // 2 - src_h // 2
292
+ if fill_height > 0:
293
+ res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0))
294
+ res.paste(
295
+ resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)),
296
+ box=(0, fill_height + src_h),
297
+ )
298
+ elif ratio > src_ratio:
299
+ fill_width = width // 2 - src_w // 2
300
+ if fill_width > 0:
301
+ res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0))
302
+ res.paste(
303
+ resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)),
304
+ box=(fill_width + src_w, 0),
305
+ )
306
+
307
+ return res
308
+
309
+ def _resize_and_crop(
310
+ self,
311
+ image: PIL.Image.Image,
312
+ width: int,
313
+ height: int,
314
+ ) -> PIL.Image.Image:
315
+ """
316
+ 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.
317
+
318
+ Args:
319
+ image: The image to resize.
320
+ width: The width to resize the image to.
321
+ height: The height to resize the image to.
322
+ """
323
+ ratio = width / height
324
+ src_ratio = image.width / image.height
325
+
326
+ src_w = width if ratio > src_ratio else image.width * height // image.height
327
+ src_h = height if ratio <= src_ratio else image.height * width // image.width
328
+
329
+ resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION["lanczos"])
330
+ res = Image.new("RGB", (width, height))
331
+ res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
332
+ return res
333
+
334
+ def resize(
335
+ self,
336
+ image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
337
+ height: int,
338
+ width: int,
339
+ resize_mode: str = "default", # "default", "fill", "crop"
340
+ ) -> Union[PIL.Image.Image, np.ndarray, torch.Tensor]:
341
+ """
342
+ Resize image.
343
+
344
+ Args:
345
+ image (`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
346
+ The image input, can be a PIL image, numpy array or pytorch tensor.
347
+ height (`int`):
348
+ The height to resize to.
349
+ width (`int`):
350
+ The width to resize to.
351
+ resize_mode (`str`, *optional*, defaults to `default`):
352
+ The resize mode to use, can be one of `default` or `fill`. If `default`, will resize the image to fit
353
+ within the specified width and height, and it may not maintaining the original aspect ratio.
354
+ If `fill`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
355
+ within the dimensions, filling empty with data from image.
356
+ If `crop`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
357
+ within the dimensions, cropping the excess.
358
+ Note that resize_mode `fill` and `crop` are only supported for PIL image input.
359
+
360
+ Returns:
361
+ `PIL.Image.Image`, `np.ndarray` or `torch.Tensor`:
362
+ The resized image.
363
+ """
364
+ if resize_mode != "default" and not isinstance(image, PIL.Image.Image):
365
+ raise ValueError(f"Only PIL image input is supported for resize_mode {resize_mode}")
366
+ if isinstance(image, PIL.Image.Image):
367
+ if resize_mode == "default":
368
+ image = image.resize((width, height), resample=PIL_INTERPOLATION[self.config.resample])
369
+ elif resize_mode == "fill":
370
+ image = self._resize_and_fill(image, width, height)
371
+ elif resize_mode == "crop":
372
+ image = self._resize_and_crop(image, width, height)
373
+ else:
374
+ raise ValueError(f"resize_mode {resize_mode} is not supported")
375
+
376
+ elif isinstance(image, torch.Tensor):
377
+ image = torch.nn.functional.interpolate(
378
+ image,
379
+ size=(height, width),
380
+ )
381
+ elif isinstance(image, np.ndarray):
382
+ image = self.numpy_to_pt(image)
383
+ image = torch.nn.functional.interpolate(
384
+ image,
385
+ size=(height, width),
386
+ )
387
+ image = self.pt_to_numpy(image)
388
+ return image
389
+
390
+ def binarize(self, image: PIL.Image.Image) -> PIL.Image.Image:
391
+ """
392
+ Create a mask.
393
+
394
+ Args:
395
+ image (`PIL.Image.Image`):
396
+ The image input, should be a PIL image.
397
+
398
+ Returns:
399
+ `PIL.Image.Image`:
400
+ The binarized image. Values less than 0.5 are set to 0, values greater than 0.5 are set to 1.
401
+ """
402
+ image[image < 0.5] = 0
403
+ image[image >= 0.5] = 1
404
+
405
+ return image
406
+
407
+ def get_default_height_width(
408
+ self,
409
+ image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
410
+ height: Optional[int] = None,
411
+ width: Optional[int] = None,
412
+ ) -> Tuple[int, int]:
413
+ """
414
+ This function return the height and width that are downscaled to the next integer multiple of
415
+ `vae_scale_factor`.
416
+
417
+ Args:
418
+ image(`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
419
+ The image input, can be a PIL image, numpy array or pytorch tensor. if it is a numpy array, should have
420
+ shape `[batch, height, width]` or `[batch, height, width, channel]` if it is a pytorch tensor, should
421
+ have shape `[batch, channel, height, width]`.
422
+ height (`int`, *optional*, defaults to `None`):
423
+ The height in preprocessed image. If `None`, will use the height of `image` input.
424
+ width (`int`, *optional*`, defaults to `None`):
425
+ The width in preprocessed. If `None`, will use the width of the `image` input.
426
+ """
427
+
428
+ if height is None:
429
+ if isinstance(image, PIL.Image.Image):
430
+ height = image.height
431
+ elif isinstance(image, torch.Tensor):
432
+ height = image.shape[2]
433
+ else:
434
+ height = image.shape[1]
435
+
436
+ if width is None:
437
+ if isinstance(image, PIL.Image.Image):
438
+ width = image.width
439
+ elif isinstance(image, torch.Tensor):
440
+ width = image.shape[3]
441
+ else:
442
+ width = image.shape[2]
443
+
444
+ width, height = (
445
+ x - x % self.config.vae_scale_factor for x in (width, height)
446
+ ) # resize to integer multiple of vae_scale_factor
447
+
448
+ return height, width
449
+
450
+ def preprocess(
451
+ self,
452
+ image: PipelineImageInput,
453
+ height: Optional[int] = None,
454
+ width: Optional[int] = None,
455
+ resize_mode: str = "default", # "default", "fill", "crop"
456
+ crops_coords: Optional[Tuple[int, int, int, int]] = None,
457
+ ) -> torch.Tensor:
458
+ """
459
+ Preprocess the image input.
460
+
461
+ Args:
462
+ image (`pipeline_image_input`):
463
+ The image input, accepted formats are PIL images, NumPy arrays, PyTorch tensors; Also accept list of supported formats.
464
+ height (`int`, *optional*, defaults to `None`):
465
+ The height in preprocessed image. If `None`, will use the `get_default_height_width()` to get default height.
466
+ width (`int`, *optional*`, defaults to `None`):
467
+ The width in preprocessed. If `None`, will use get_default_height_width()` to get the default width.
468
+ resize_mode (`str`, *optional*, defaults to `default`):
469
+ The resize mode, can be one of `default` or `fill`. If `default`, will resize the image to fit
470
+ within the specified width and height, and it may not maintaining the original aspect ratio.
471
+ If `fill`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
472
+ within the dimensions, filling empty with data from image.
473
+ If `crop`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
474
+ within the dimensions, cropping the excess.
475
+ Note that resize_mode `fill` and `crop` are only supported for PIL image input.
476
+ crops_coords (`List[Tuple[int, int, int, int]]`, *optional*, defaults to `None`):
477
+ The crop coordinates for each image in the batch. If `None`, will not crop the image.
478
+ """
479
+ supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
480
+
481
+ # Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
482
+ if self.config.do_convert_grayscale and isinstance(image, (torch.Tensor, np.ndarray)) and image.ndim == 3:
483
+ if isinstance(image, torch.Tensor):
484
+ # if image is a pytorch tensor could have 2 possible shapes:
485
+ # 1. batch x height x width: we should insert the channel dimension at position 1
486
+ # 2. channel x height x width: we should insert batch dimension at position 0,
487
+ # however, since both channel and batch dimension has same size 1, it is same to insert at position 1
488
+ # for simplicity, we insert a dimension of size 1 at position 1 for both cases
489
+ image = image.unsqueeze(1)
490
+ else:
491
+ # if it is a numpy array, it could have 2 possible shapes:
492
+ # 1. batch x height x width: insert channel dimension on last position
493
+ # 2. height x width x channel: insert batch dimension on first position
494
+ if image.shape[-1] == 1:
495
+ image = np.expand_dims(image, axis=0)
496
+ else:
497
+ image = np.expand_dims(image, axis=-1)
498
+
499
+ if isinstance(image, supported_formats):
500
+ image = [image]
501
+ elif not (isinstance(image, list) and all(isinstance(i, supported_formats) for i in image)):
502
+ raise ValueError(
503
+ f"Input is in incorrect format: {[type(i) for i in image]}. Currently, we only support {', '.join(supported_formats)}"
504
+ )
505
+
506
+ if isinstance(image[0], PIL.Image.Image):
507
+ if crops_coords is not None:
508
+ image = [i.crop(crops_coords) for i in image]
509
+ if self.config.do_resize:
510
+ height, width = self.get_default_height_width(image[0], height, width)
511
+ image = [self.resize(i, height, width, resize_mode=resize_mode) for i in image]
512
+ if self.config.do_convert_rgb:
513
+ image = [self.convert_to_rgb(i) for i in image]
514
+ elif self.config.do_convert_grayscale:
515
+ image = [self.convert_to_grayscale(i) for i in image]
516
+ image = self.pil_to_numpy(image) # to np
517
+ image = self.numpy_to_pt(image) # to pt
518
+
519
+ elif isinstance(image[0], np.ndarray):
520
+ image = np.concatenate(image, axis=0) if image[0].ndim == 4 else np.stack(image, axis=0)
521
+
522
+ image = self.numpy_to_pt(image)
523
+
524
+ height, width = self.get_default_height_width(image, height, width)
525
+ if self.config.do_resize:
526
+ image = self.resize(image, height, width)
527
+
528
+ elif isinstance(image[0], torch.Tensor):
529
+ image = torch.cat(image, axis=0) if image[0].ndim == 4 else torch.stack(image, axis=0)
530
+
531
+ if self.config.do_convert_grayscale and image.ndim == 3:
532
+ image = image.unsqueeze(1)
533
+
534
+ channel = image.shape[1]
535
+ # don't need any preprocess if the image is latents
536
+ if channel == 4:
537
+ return image
538
+
539
+ height, width = self.get_default_height_width(image, height, width)
540
+ if self.config.do_resize:
541
+ image = self.resize(image, height, width)
542
+
543
+ # expected range [0,1], normalize to [-1,1]
544
+ do_normalize = self.config.do_normalize
545
+ if do_normalize and image.min() < 0:
546
+ warnings.warn(
547
+ "Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
548
+ f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]",
549
+ FutureWarning,
550
+ )
551
+ do_normalize = False
552
+
553
+ if do_normalize:
554
+ image = self.normalize(image)
555
+
556
+ if self.config.do_binarize:
557
+ image = self.binarize(image)
558
+
559
+ return image
560
+
561
+ def postprocess(
562
+ self,
563
+ image: torch.FloatTensor,
564
+ output_type: str = "pil",
565
+ do_denormalize: Optional[List[bool]] = None,
566
+ ) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
567
+ """
568
+ Postprocess the image output from tensor to `output_type`.
569
+
570
+ Args:
571
+ image (`torch.FloatTensor`):
572
+ The image input, should be a pytorch tensor with shape `B x C x H x W`.
573
+ output_type (`str`, *optional*, defaults to `pil`):
574
+ The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
575
+ do_denormalize (`List[bool]`, *optional*, defaults to `None`):
576
+ Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
577
+ `VaeImageProcessor` config.
578
+
579
+ Returns:
580
+ `PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
581
+ The postprocessed image.
582
+ """
583
+ if not isinstance(image, torch.Tensor):
584
+ raise ValueError(
585
+ f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
586
+ )
587
+ if output_type not in ["latent", "pt", "np", "pil"]:
588
+ deprecation_message = (
589
+ 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: "
590
+ "`pil`, `np`, `pt`, `latent`"
591
+ )
592
+ deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
593
+ output_type = "np"
594
+
595
+ if output_type == "latent":
596
+ return image
597
+
598
+ if do_denormalize is None:
599
+ do_denormalize = [self.config.do_normalize] * image.shape[0]
600
+
601
+ image = np.stack(
602
+ [self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
603
+ )
604
+
605
+ if output_type == "pt":
606
+ return image
607
+
608
+ # image = self.pt_to_numpy(image)
609
+
610
+ if output_type == "np":
611
+ return image
612
+
613
+ if output_type == "pil":
614
+ return self.numpy_to_pil(image)
615
+
616
+ def apply_overlay(
617
+ self,
618
+ mask: PIL.Image.Image,
619
+ init_image: PIL.Image.Image,
620
+ image: PIL.Image.Image,
621
+ crop_coords: Optional[Tuple[int, int, int, int]] = None,
622
+ ) -> PIL.Image.Image:
623
+ """
624
+ overlay the inpaint output to the original image
625
+ """
626
+
627
+ width, height = image.width, image.height
628
+
629
+ init_image = self.resize(init_image, width=width, height=height)
630
+ mask = self.resize(mask, width=width, height=height)
631
+
632
+ init_image_masked = PIL.Image.new("RGBa", (width, height))
633
+ init_image_masked.paste(init_image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(mask.convert("L")))
634
+ init_image_masked = init_image_masked.convert("RGBA")
635
+
636
+ if crop_coords is not None:
637
+ x, y, x2, y2 = crop_coords
638
+ w = x2 - x
639
+ h = y2 - y
640
+ base_image = PIL.Image.new("RGBA", (width, height))
641
+ image = self.resize(image, height=h, width=w, resize_mode="crop")
642
+ base_image.paste(image, (x, y))
643
+ image = base_image.convert("RGB")
644
+
645
+ image = image.convert("RGBA")
646
+ image.alpha_composite(init_image_masked)
647
+ image = image.convert("RGB")
648
+
649
+ return image
650
+
651
+
652
+ class VaeImageProcessorLDM3D(VaeImageProcessor):
653
+ """
654
+ Image processor for VAE LDM3D.
655
+
656
+ Args:
657
+ do_resize (`bool`, *optional*, defaults to `True`):
658
+ Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
659
+ vae_scale_factor (`int`, *optional*, defaults to `8`):
660
+ VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
661
+ resample (`str`, *optional*, defaults to `lanczos`):
662
+ Resampling filter to use when resizing the image.
663
+ do_normalize (`bool`, *optional*, defaults to `True`):
664
+ Whether to normalize the image to [-1,1].
665
+ """
666
+
667
+ config_name = CONFIG_NAME
668
+
669
+ @register_to_config
670
+ def __init__(
671
+ self,
672
+ do_resize: bool = True,
673
+ vae_scale_factor: int = 8,
674
+ resample: str = "lanczos",
675
+ do_normalize: bool = True,
676
+ ):
677
+ super().__init__()
678
+
679
+ @staticmethod
680
+ def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
681
+ """
682
+ Convert a NumPy image or a batch of images to a PIL image.
683
+ """
684
+ if images.ndim == 3:
685
+ images = images[None, ...]
686
+ # images = (images * 255).round().astype("uint8")
687
+ if images.shape[-1] == 1:
688
+ # special case for grayscale (single channel) images
689
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
690
+ else:
691
+ pil_images = [Image.fromarray(image[:, :, :3]) for image in images]
692
+
693
+ return pil_images
694
+
695
+ @staticmethod
696
+ def depth_pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
697
+ """
698
+ Convert a PIL image or a list of PIL images to NumPy arrays.
699
+ """
700
+ if not isinstance(images, list):
701
+ images = [images]
702
+
703
+ images = [np.array(image).astype(np.float32) / (2**16 - 1) for image in images]
704
+ images = np.stack(images, axis=0)
705
+ return images
706
+
707
+ @staticmethod
708
+ def rgblike_to_depthmap(image: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
709
+ """
710
+ Args:
711
+ image: RGB-like depth image
712
+
713
+ Returns: depth map
714
+
715
+ """
716
+ return image[:, :, 1] * 2**8 + image[:, :, 2]
717
+
718
+ def numpy_to_depth(self, images: np.ndarray) -> List[PIL.Image.Image]:
719
+ """
720
+ Convert a NumPy depth image or a batch of images to a PIL image.
721
+ """
722
+ if images.ndim == 3:
723
+ images = images[None, ...]
724
+ images_depth = images[:, :, :, 3:]
725
+ if images.shape[-1] == 6:
726
+ images_depth = (images_depth * 255).round().astype("uint8")
727
+ pil_images = [
728
+ Image.fromarray(self.rgblike_to_depthmap(image_depth), mode="I;16") for image_depth in images_depth
729
+ ]
730
+ elif images.shape[-1] == 4:
731
+ images_depth = (images_depth * 65535.0).astype(np.uint16)
732
+ pil_images = [Image.fromarray(image_depth, mode="I;16") for image_depth in images_depth]
733
+ else:
734
+ raise Exception("Not supported")
735
+
736
+ return pil_images
737
+
738
+ def postprocess(
739
+ self,
740
+ image: torch.FloatTensor,
741
+ output_type: str = "pil",
742
+ do_denormalize: Optional[List[bool]] = None,
743
+ ) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
744
+ """
745
+ Postprocess the image output from tensor to `output_type`.
746
+
747
+ Args:
748
+ image (`torch.FloatTensor`):
749
+ The image input, should be a pytorch tensor with shape `B x C x H x W`.
750
+ output_type (`str`, *optional*, defaults to `pil`):
751
+ The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
752
+ do_denormalize (`List[bool]`, *optional*, defaults to `None`):
753
+ Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
754
+ `VaeImageProcessor` config.
755
+
756
+ Returns:
757
+ `PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
758
+ The postprocessed image.
759
+ """
760
+ if not isinstance(image, torch.Tensor):
761
+ raise ValueError(
762
+ f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
763
+ )
764
+ if output_type not in ["latent", "pt", "np", "pil"]:
765
+ deprecation_message = (
766
+ 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: "
767
+ "`pil`, `np`, `pt`, `latent`"
768
+ )
769
+ deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
770
+ output_type = "np"
771
+
772
+ if do_denormalize is None:
773
+ do_denormalize = [self.config.do_normalize] * image.shape[0]
774
+
775
+ image = torch.stack(
776
+ [self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
777
+ )
778
+
779
+ image = self.pt_to_numpy(image)
780
+
781
+ if output_type == "np":
782
+ if image.shape[-1] == 6:
783
+ image_depth = np.stack([self.rgblike_to_depthmap(im[:, :, 3:]) for im in image], axis=0)
784
+ else:
785
+ image_depth = image[:, :, :, 3:]
786
+ return image[:, :, :, :3], image_depth
787
+
788
+ if output_type == "pil":
789
+ return self.numpy_to_pil(image), self.numpy_to_depth(image)
790
+ else:
791
+ raise Exception(f"This type {output_type} is not supported")
792
+
793
+ def preprocess(
794
+ self,
795
+ rgb: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
796
+ depth: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
797
+ height: Optional[int] = None,
798
+ width: Optional[int] = None,
799
+ target_res: Optional[int] = None,
800
+ ) -> torch.Tensor:
801
+ """
802
+ Preprocess the image input. Accepted formats are PIL images, NumPy arrays or PyTorch tensors.
803
+ """
804
+ supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
805
+
806
+ # Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
807
+ if self.config.do_convert_grayscale and isinstance(rgb, (torch.Tensor, np.ndarray)) and rgb.ndim == 3:
808
+ raise Exception("This is not yet supported")
809
+
810
+ if isinstance(rgb, supported_formats):
811
+ rgb = [rgb]
812
+ depth = [depth]
813
+ elif not (isinstance(rgb, list) and all(isinstance(i, supported_formats) for i in rgb)):
814
+ raise ValueError(
815
+ f"Input is in incorrect format: {[type(i) for i in rgb]}. Currently, we only support {', '.join(supported_formats)}"
816
+ )
817
+
818
+ if isinstance(rgb[0], PIL.Image.Image):
819
+ if self.config.do_convert_rgb:
820
+ raise Exception("This is not yet supported")
821
+ # rgb = [self.convert_to_rgb(i) for i in rgb]
822
+ # depth = [self.convert_to_depth(i) for i in depth] #TODO define convert_to_depth
823
+ if self.config.do_resize or target_res:
824
+ height, width = self.get_default_height_width(rgb[0], height, width) if not target_res else target_res
825
+ rgb = [self.resize(i, height, width) for i in rgb]
826
+ depth = [self.resize(i, height, width) for i in depth]
827
+ rgb = self.pil_to_numpy(rgb) # to np
828
+ rgb = self.numpy_to_pt(rgb) # to pt
829
+
830
+ depth = self.depth_pil_to_numpy(depth) # to np
831
+ depth = self.numpy_to_pt(depth) # to pt
832
+
833
+ elif isinstance(rgb[0], np.ndarray):
834
+ rgb = np.concatenate(rgb, axis=0) if rgb[0].ndim == 4 else np.stack(rgb, axis=0)
835
+ rgb = self.numpy_to_pt(rgb)
836
+ height, width = self.get_default_height_width(rgb, height, width)
837
+ if self.config.do_resize:
838
+ rgb = self.resize(rgb, height, width)
839
+
840
+ depth = np.concatenate(depth, axis=0) if rgb[0].ndim == 4 else np.stack(depth, axis=0)
841
+ depth = self.numpy_to_pt(depth)
842
+ height, width = self.get_default_height_width(depth, height, width)
843
+ if self.config.do_resize:
844
+ depth = self.resize(depth, height, width)
845
+
846
+ elif isinstance(rgb[0], torch.Tensor):
847
+ raise Exception("This is not yet supported")
848
+ # rgb = torch.cat(rgb, axis=0) if rgb[0].ndim == 4 else torch.stack(rgb, axis=0)
849
+
850
+ # if self.config.do_convert_grayscale and rgb.ndim == 3:
851
+ # rgb = rgb.unsqueeze(1)
852
+
853
+ # channel = rgb.shape[1]
854
+
855
+ # height, width = self.get_default_height_width(rgb, height, width)
856
+ # if self.config.do_resize:
857
+ # rgb = self.resize(rgb, height, width)
858
+
859
+ # depth = torch.cat(depth, axis=0) if depth[0].ndim == 4 else torch.stack(depth, axis=0)
860
+
861
+ # if self.config.do_convert_grayscale and depth.ndim == 3:
862
+ # depth = depth.unsqueeze(1)
863
+
864
+ # channel = depth.shape[1]
865
+ # # don't need any preprocess if the image is latents
866
+ # if depth == 4:
867
+ # return rgb, depth
868
+
869
+ # height, width = self.get_default_height_width(depth, height, width)
870
+ # if self.config.do_resize:
871
+ # depth = self.resize(depth, height, width)
872
+ # expected range [0,1], normalize to [-1,1]
873
+ do_normalize = self.config.do_normalize
874
+ if rgb.min() < 0 and do_normalize:
875
+ warnings.warn(
876
+ "Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
877
+ f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{rgb.min()},{rgb.max()}]",
878
+ FutureWarning,
879
+ )
880
+ do_normalize = False
881
+
882
+ if do_normalize:
883
+ rgb = self.normalize(rgb)
884
+ depth = self.normalize(depth)
885
+
886
+ if self.config.do_binarize:
887
+ rgb = self.binarize(rgb)
888
+ depth = self.binarize(depth)
889
+
890
+ return rgb, depth
891
+
892
+
893
+ class IPAdapterMaskProcessor(VaeImageProcessor):
894
+ """
895
+ Image processor for IP Adapter image masks.
896
+
897
+ Args:
898
+ do_resize (`bool`, *optional*, defaults to `True`):
899
+ Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
900
+ vae_scale_factor (`int`, *optional*, defaults to `8`):
901
+ VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
902
+ resample (`str`, *optional*, defaults to `lanczos`):
903
+ Resampling filter to use when resizing the image.
904
+ do_normalize (`bool`, *optional*, defaults to `False`):
905
+ Whether to normalize the image to [-1,1].
906
+ do_binarize (`bool`, *optional*, defaults to `True`):
907
+ Whether to binarize the image to 0/1.
908
+ do_convert_grayscale (`bool`, *optional*, defaults to be `True`):
909
+ Whether to convert the images to grayscale format.
910
+
911
+ """
912
+
913
+ config_name = CONFIG_NAME
914
+
915
+ @register_to_config
916
+ def __init__(
917
+ self,
918
+ do_resize: bool = True,
919
+ vae_scale_factor: int = 8,
920
+ resample: str = "lanczos",
921
+ do_normalize: bool = False,
922
+ do_binarize: bool = True,
923
+ do_convert_grayscale: bool = True,
924
+ ):
925
+ super().__init__(
926
+ do_resize=do_resize,
927
+ vae_scale_factor=vae_scale_factor,
928
+ resample=resample,
929
+ do_normalize=do_normalize,
930
+ do_binarize=do_binarize,
931
+ do_convert_grayscale=do_convert_grayscale,
932
+ )
933
+
934
+ @staticmethod
935
+ def downsample(mask: torch.FloatTensor, batch_size: int, num_queries: int, value_embed_dim: int):
936
+ """
937
+ Downsamples the provided mask tensor to match the expected dimensions for scaled dot-product attention.
938
+ If the aspect ratio of the mask does not match the aspect ratio of the output image, a warning is issued.
939
+
940
+ Args:
941
+ mask (`torch.FloatTensor`):
942
+ The input mask tensor generated with `IPAdapterMaskProcessor.preprocess()`.
943
+ batch_size (`int`):
944
+ The batch size.
945
+ num_queries (`int`):
946
+ The number of queries.
947
+ value_embed_dim (`int`):
948
+ The dimensionality of the value embeddings.
949
+
950
+ Returns:
951
+ `torch.FloatTensor`:
952
+ The downsampled mask tensor.
953
+
954
+ """
955
+ o_h = mask.shape[1]
956
+ o_w = mask.shape[2]
957
+ ratio = o_w / o_h
958
+ mask_h = int(math.sqrt(num_queries / ratio))
959
+ mask_h = int(mask_h) + int((num_queries % int(mask_h)) != 0)
960
+ mask_w = num_queries // mask_h
961
+
962
+ mask_downsample = F.interpolate(mask.unsqueeze(0), size=(mask_h, mask_w), mode="bicubic").squeeze(0)
963
+
964
+ # Repeat batch_size times
965
+ if mask_downsample.shape[0] < batch_size:
966
+ mask_downsample = mask_downsample.repeat(batch_size, 1, 1)
967
+
968
+ mask_downsample = mask_downsample.view(mask_downsample.shape[0], -1)
969
+
970
+ downsampled_area = mask_h * mask_w
971
+ # If the output image and the mask do not have the same aspect ratio, tensor shapes will not match
972
+ # Pad tensor if downsampled_mask.shape[1] is smaller than num_queries
973
+ if downsampled_area < num_queries:
974
+ warnings.warn(
975
+ "The aspect ratio of the mask does not match the aspect ratio of the output image. "
976
+ "Please update your masks or adjust the output size for optimal performance.",
977
+ UserWarning,
978
+ )
979
+ mask_downsample = F.pad(mask_downsample, (0, num_queries - mask_downsample.shape[1]), value=0.0)
980
+ # Discard last embeddings if downsampled_mask.shape[1] is bigger than num_queries
981
+ if downsampled_area > num_queries:
982
+ warnings.warn(
983
+ "The aspect ratio of the mask does not match the aspect ratio of the output image. "
984
+ "Please update your masks or adjust the output size for optimal performance.",
985
+ UserWarning,
986
+ )
987
+ mask_downsample = mask_downsample[:, :num_queries]
988
+
989
+ # Repeat last dimension to match SDPA output shape
990
+ mask_downsample = mask_downsample.view(mask_downsample.shape[0], mask_downsample.shape[1], 1).repeat(
991
+ 1, 1, value_embed_dim
992
+ )
993
+
994
+ return mask_downsample
StableDiffusion/Our_Transformer.py ADDED
@@ -0,0 +1,458 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, Optional
16
+
17
+ import torch
18
+ import torch.nn.functional as F
19
+ from torch import nn
20
+
21
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
22
+ from diffusers.utils import BaseOutput, deprecate, is_torch_version, logging
23
+ from .Our_AttnBlock import BasicTransformerBlock
24
+ from diffusers.models.embeddings import ImagePositionalEmbeddings, PatchEmbed, PixArtAlphaTextProjection
25
+ from diffusers.models.modeling_utils import ModelMixin
26
+ from diffusers.models.normalization import AdaLayerNormSingle
27
+
28
+
29
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
30
+
31
+
32
+ @dataclass
33
+ class Transformer2DModelOutput(BaseOutput):
34
+ """
35
+ The output of [`Transformer2DModel`].
36
+
37
+ Args:
38
+ sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DModel`] is discrete):
39
+ The hidden states output conditioned on the `encoder_hidden_states` input. If discrete, returns probability
40
+ distributions for the unnoised latent pixels.
41
+ """
42
+
43
+ sample: torch.FloatTensor
44
+
45
+
46
+ class Transformer2DModel(ModelMixin, ConfigMixin):
47
+ """
48
+ A 2D Transformer model for image-like data.
49
+
50
+ Parameters:
51
+ num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
52
+ attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
53
+ in_channels (`int`, *optional*):
54
+ The number of channels in the input and output (specify if the input is **continuous**).
55
+ num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
56
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
57
+ cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
58
+ sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**).
59
+ This is fixed during training since it is used to learn a number of position embeddings.
60
+ num_vector_embeds (`int`, *optional*):
61
+ The number of classes of the vector embeddings of the latent pixels (specify if the input is **discrete**).
62
+ Includes the class for the masked latent pixel.
63
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to use in feed-forward.
64
+ num_embeds_ada_norm ( `int`, *optional*):
65
+ The number of diffusion steps used during training. Pass if at least one of the norm_layers is
66
+ `AdaLayerNorm`. This is fixed during training since it is used to learn a number of embeddings that are
67
+ added to the hidden states.
68
+
69
+ During inference, you can denoise for up to but not more steps than `num_embeds_ada_norm`.
70
+ attention_bias (`bool`, *optional*):
71
+ Configure if the `TransformerBlocks` attention should contain a bias parameter.
72
+ """
73
+
74
+ _supports_gradient_checkpointing = True
75
+
76
+ @register_to_config
77
+ def __init__(
78
+ self,
79
+ num_attention_heads: int = 16,
80
+ attention_head_dim: int = 88,
81
+ in_channels: Optional[int] = None,
82
+ out_channels: Optional[int] = None,
83
+ num_layers: int = 1,
84
+ dropout: float = 0.0,
85
+ norm_num_groups: int = 32,
86
+ cross_attention_dim: Optional[int] = None,
87
+ attention_bias: bool = False,
88
+ sample_size: Optional[int] = None,
89
+ num_vector_embeds: Optional[int] = None,
90
+ patch_size: Optional[int] = None,
91
+ activation_fn: str = "geglu",
92
+ num_embeds_ada_norm: Optional[int] = None,
93
+ use_linear_projection: bool = False,
94
+ only_cross_attention: bool = False,
95
+ double_self_attention: bool = False,
96
+ upcast_attention: bool = False,
97
+ norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single', 'ada_norm_continuous', 'layer_norm_i2vgen'
98
+ norm_elementwise_affine: bool = True,
99
+ norm_eps: float = 1e-5,
100
+ attention_type: str = "default",
101
+ caption_channels: int = None,
102
+ interpolation_scale: float = None,
103
+ dual_attention: bool = True,
104
+ ):
105
+ super().__init__()
106
+ if patch_size is not None:
107
+ if norm_type not in ["ada_norm", "ada_norm_zero", "ada_norm_single"]:
108
+ raise NotImplementedError(
109
+ f"Forward pass is not implemented when `patch_size` is not None and `norm_type` is '{norm_type}'."
110
+ )
111
+ elif norm_type in ["ada_norm", "ada_norm_zero"] and num_embeds_ada_norm is None:
112
+ raise ValueError(
113
+ f"When using a `patch_size` and this `norm_type` ({norm_type}), `num_embeds_ada_norm` cannot be None."
114
+ )
115
+
116
+ self.use_linear_projection = use_linear_projection
117
+ self.num_attention_heads = num_attention_heads
118
+ self.attention_head_dim = attention_head_dim
119
+ inner_dim = num_attention_heads * attention_head_dim
120
+
121
+ conv_cls = nn.Conv2d
122
+ linear_cls = nn.Linear
123
+
124
+ # 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)`
125
+ # Define whether input is continuous or discrete depending on configuration
126
+ self.is_input_continuous = (in_channels is not None) and (patch_size is None)
127
+ self.is_input_vectorized = num_vector_embeds is not None
128
+ self.is_input_patches = in_channels is not None and patch_size is not None
129
+
130
+ if norm_type == "layer_norm" and num_embeds_ada_norm is not None:
131
+ deprecation_message = (
132
+ f"The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or"
133
+ " incorrectly set to `'layer_norm'`.Make sure to set `norm_type` to `'ada_norm'` in the config."
134
+ " Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect"
135
+ " results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it"
136
+ " would be very nice if you could open a Pull request for the `transformer/config.json` file"
137
+ )
138
+ deprecate("norm_type!=num_embeds_ada_norm", "1.0.0", deprecation_message, standard_warn=False)
139
+ norm_type = "ada_norm"
140
+
141
+ if self.is_input_continuous and self.is_input_vectorized:
142
+ raise ValueError(
143
+ f"Cannot define both `in_channels`: {in_channels} and `num_vector_embeds`: {num_vector_embeds}. Make"
144
+ " sure that either `in_channels` or `num_vector_embeds` is None."
145
+ )
146
+ elif self.is_input_vectorized and self.is_input_patches:
147
+ raise ValueError(
148
+ f"Cannot define both `num_vector_embeds`: {num_vector_embeds} and `patch_size`: {patch_size}. Make"
149
+ " sure that either `num_vector_embeds` or `num_patches` is None."
150
+ )
151
+ elif not self.is_input_continuous and not self.is_input_vectorized and not self.is_input_patches:
152
+ raise ValueError(
153
+ f"Has to define `in_channels`: {in_channels}, `num_vector_embeds`: {num_vector_embeds}, or patch_size:"
154
+ f" {patch_size}. Make sure that `in_channels`, `num_vector_embeds` or `num_patches` is not None."
155
+ )
156
+
157
+ # 2. Define input layers
158
+ if self.is_input_continuous:
159
+ self.in_channels = in_channels
160
+
161
+ self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True)
162
+ if use_linear_projection:
163
+ self.proj_in = linear_cls(in_channels, inner_dim)
164
+ else:
165
+ self.proj_in = conv_cls(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
166
+ elif self.is_input_vectorized:
167
+ assert sample_size is not None, "Transformer2DModel over discrete input must provide sample_size"
168
+ assert num_vector_embeds is not None, "Transformer2DModel over discrete input must provide num_embed"
169
+
170
+ self.height = sample_size
171
+ self.width = sample_size
172
+ self.num_vector_embeds = num_vector_embeds
173
+ self.num_latent_pixels = self.height * self.width
174
+
175
+ self.latent_image_embedding = ImagePositionalEmbeddings(
176
+ num_embed=num_vector_embeds, embed_dim=inner_dim, height=self.height, width=self.width
177
+ )
178
+ elif self.is_input_patches:
179
+ assert sample_size is not None, "Transformer2DModel over patched input must provide sample_size"
180
+
181
+ self.height = sample_size
182
+ self.width = sample_size
183
+
184
+ self.patch_size = patch_size
185
+ interpolation_scale = (
186
+ interpolation_scale if interpolation_scale is not None else max(self.config.sample_size // 64, 1)
187
+ )
188
+ self.pos_embed = PatchEmbed(
189
+ height=sample_size,
190
+ width=sample_size,
191
+ patch_size=patch_size,
192
+ in_channels=in_channels,
193
+ embed_dim=inner_dim,
194
+ interpolation_scale=interpolation_scale,
195
+ )
196
+
197
+ # 3. Define transformers blocks
198
+ self.transformer_blocks = nn.ModuleList(
199
+ [
200
+ BasicTransformerBlock(
201
+ inner_dim,
202
+ num_attention_heads,
203
+ attention_head_dim,
204
+ dropout=dropout,
205
+ cross_attention_dim=cross_attention_dim,
206
+ activation_fn=activation_fn,
207
+ num_embeds_ada_norm=num_embeds_ada_norm,
208
+ attention_bias=attention_bias,
209
+ only_cross_attention=only_cross_attention,
210
+ double_self_attention=double_self_attention,
211
+ upcast_attention=upcast_attention,
212
+ norm_type=norm_type,
213
+ norm_elementwise_affine=norm_elementwise_affine,
214
+ norm_eps=norm_eps,
215
+ attention_type=attention_type,
216
+ dual_attention=dual_attention
217
+ )
218
+ for d in range(num_layers)
219
+ ]
220
+ )
221
+
222
+ # 4. Define output layers
223
+ self.out_channels = in_channels if out_channels is None else out_channels
224
+ if self.is_input_continuous:
225
+ # TODO: should use out_channels for continuous projections
226
+ if use_linear_projection:
227
+ self.proj_out = linear_cls(inner_dim, in_channels)
228
+ else:
229
+ self.proj_out = conv_cls(inner_dim, in_channels, kernel_size=1, stride=1, padding=0)
230
+ elif self.is_input_vectorized:
231
+ self.norm_out = nn.LayerNorm(inner_dim)
232
+ self.out = nn.Linear(inner_dim, self.num_vector_embeds - 1)
233
+ elif self.is_input_patches and norm_type != "ada_norm_single":
234
+ self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)
235
+ self.proj_out_1 = nn.Linear(inner_dim, 2 * inner_dim)
236
+ self.proj_out_2 = nn.Linear(inner_dim, patch_size * patch_size * self.out_channels)
237
+ elif self.is_input_patches and norm_type == "ada_norm_single":
238
+ self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)
239
+ self.scale_shift_table = nn.Parameter(torch.randn(2, inner_dim) / inner_dim**0.5)
240
+ self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * self.out_channels)
241
+
242
+ # 5. PixArt-Alpha blocks.
243
+ self.adaln_single = None
244
+ self.use_additional_conditions = False
245
+ if norm_type == "ada_norm_single":
246
+ self.use_additional_conditions = self.config.sample_size == 128
247
+ # TODO(Sayak, PVP) clean this, for now we use sample size to determine whether to use
248
+ # additional conditions until we find better name
249
+ self.adaln_single = AdaLayerNormSingle(inner_dim, use_additional_conditions=self.use_additional_conditions)
250
+
251
+ self.caption_projection = None
252
+ if caption_channels is not None:
253
+ self.caption_projection = PixArtAlphaTextProjection(in_features=caption_channels, hidden_size=inner_dim)
254
+
255
+ self.gradient_checkpointing = False
256
+
257
+ def _set_gradient_checkpointing(self, module, value=False):
258
+ if hasattr(module, "gradient_checkpointing"):
259
+ module.gradient_checkpointing = value
260
+
261
+ def forward(
262
+ self,
263
+ hidden_states: torch.Tensor,
264
+ encoder_hidden_states: Optional[torch.Tensor] = None,
265
+ timestep: Optional[torch.LongTensor] = None,
266
+ added_cond_kwargs: Dict[str, torch.Tensor] = None,
267
+ class_labels: Optional[torch.LongTensor] = None,
268
+ cross_attention_kwargs: Dict[str, Any] = None,
269
+ attention_mask: Optional[torch.Tensor] = None,
270
+ encoder_attention_mask: Optional[torch.Tensor] = None,
271
+ return_dict: bool = True,
272
+ ):
273
+ """
274
+ The [`Transformer2DModel`] forward method.
275
+
276
+ Args:
277
+ hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous):
278
+ Input `hidden_states`.
279
+ encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
280
+ Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
281
+ self-attention.
282
+ timestep ( `torch.LongTensor`, *optional*):
283
+ Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
284
+ class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
285
+ Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in
286
+ `AdaLayerZeroNorm`.
287
+ cross_attention_kwargs ( `Dict[str, Any]`, *optional*):
288
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
289
+ `self.processor` in
290
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
291
+ attention_mask ( `torch.Tensor`, *optional*):
292
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
293
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
294
+ negative values to the attention scores corresponding to "discard" tokens.
295
+ encoder_attention_mask ( `torch.Tensor`, *optional*):
296
+ Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:
297
+
298
+ * Mask `(batch, sequence_length)` True = keep, False = discard.
299
+ * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard.
300
+
301
+ If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format
302
+ above. This bias will be added to the cross-attention scores.
303
+ return_dict (`bool`, *optional*, defaults to `True`):
304
+ Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
305
+ tuple.
306
+
307
+ Returns:
308
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
309
+ `tuple` where the first element is the sample tensor.
310
+ """
311
+ if cross_attention_kwargs is not None:
312
+ if cross_attention_kwargs.get("scale", None) is not None:
313
+ logger.warning("Passing `scale` to `cross_attention_kwargs` is depcrecated. `scale` will be ignored.")
314
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
315
+ # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
316
+ # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
317
+ # expects mask of shape:
318
+ # [batch, key_tokens]
319
+ # adds singleton query_tokens dimension:
320
+ # [batch, 1, key_tokens]
321
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
322
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
323
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
324
+ if attention_mask is not None and attention_mask.ndim == 2:
325
+ # assume that mask is expressed as:
326
+ # (1 = keep, 0 = discard)
327
+ # convert mask into a bias that can be added to attention scores:
328
+ # (keep = +0, discard = -10000.0)
329
+ attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
330
+ attention_mask = attention_mask.unsqueeze(1)
331
+
332
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
333
+ if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
334
+ encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0
335
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
336
+
337
+ # 1. Input
338
+ if self.is_input_continuous:
339
+ batch, _, height, width = hidden_states.shape
340
+ residual = hidden_states
341
+
342
+ hidden_states = self.norm(hidden_states)
343
+ if not self.use_linear_projection:
344
+ hidden_states = self.proj_in(hidden_states)
345
+ inner_dim = hidden_states.shape[1]
346
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)
347
+ else:
348
+ inner_dim = hidden_states.shape[1]
349
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)
350
+ hidden_states = self.proj_in(hidden_states)
351
+
352
+ elif self.is_input_vectorized:
353
+ hidden_states = self.latent_image_embedding(hidden_states)
354
+ elif self.is_input_patches:
355
+ height, width = hidden_states.shape[-2] // self.patch_size, hidden_states.shape[-1] // self.patch_size
356
+ hidden_states = self.pos_embed(hidden_states)
357
+
358
+ if self.adaln_single is not None:
359
+ if self.use_additional_conditions and added_cond_kwargs is None:
360
+ raise ValueError(
361
+ "`added_cond_kwargs` cannot be None when using additional conditions for `adaln_single`."
362
+ )
363
+ batch_size = hidden_states.shape[0]
364
+ timestep, embedded_timestep = self.adaln_single(
365
+ timestep, added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_states.dtype
366
+ )
367
+
368
+ # 2. Blocks
369
+ if self.caption_projection is not None:
370
+ batch_size = hidden_states.shape[0]
371
+ encoder_hidden_states = self.caption_projection(encoder_hidden_states)
372
+ encoder_hidden_states = encoder_hidden_states.view(batch_size, -1, hidden_states.shape[-1])
373
+
374
+ for block in self.transformer_blocks:
375
+ if self.training and self.gradient_checkpointing:
376
+
377
+ def create_custom_forward(module, return_dict=None):
378
+ def custom_forward(*inputs):
379
+ if return_dict is not None:
380
+ return module(*inputs, return_dict=return_dict)
381
+ else:
382
+ return module(*inputs)
383
+
384
+ return custom_forward
385
+
386
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
387
+ hidden_states = torch.utils.checkpoint.checkpoint(
388
+ create_custom_forward(block),
389
+ hidden_states,
390
+ attention_mask,
391
+ encoder_hidden_states,
392
+ encoder_attention_mask,
393
+ timestep,
394
+ cross_attention_kwargs,
395
+ class_labels,
396
+ **ckpt_kwargs,
397
+ )
398
+ else:
399
+ hidden_states = block(
400
+ hidden_states,
401
+ attention_mask=attention_mask,
402
+ encoder_hidden_states=encoder_hidden_states,
403
+ encoder_attention_mask=encoder_attention_mask,
404
+ timestep=timestep,
405
+ cross_attention_kwargs=cross_attention_kwargs,
406
+ class_labels=class_labels,
407
+ )
408
+
409
+ # 3. Output
410
+ if self.is_input_continuous:
411
+ if not self.use_linear_projection:
412
+ hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()
413
+ hidden_states = self.proj_out(hidden_states)
414
+ else:
415
+ hidden_states = self.proj_out(hidden_states)
416
+ hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()
417
+
418
+ output = hidden_states + residual
419
+ elif self.is_input_vectorized:
420
+ hidden_states = self.norm_out(hidden_states)
421
+ logits = self.out(hidden_states)
422
+ # (batch, self.num_vector_embeds - 1, self.num_latent_pixels)
423
+ logits = logits.permute(0, 2, 1)
424
+
425
+ # log(p(x_0))
426
+ output = F.log_softmax(logits.double(), dim=1).float()
427
+
428
+ if self.is_input_patches:
429
+ if self.config.norm_type != "ada_norm_single":
430
+ conditioning = self.transformer_blocks[0].norm1.emb(
431
+ timestep, class_labels, hidden_dtype=hidden_states.dtype
432
+ )
433
+ shift, scale = self.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
434
+ hidden_states = self.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
435
+ hidden_states = self.proj_out_2(hidden_states)
436
+ elif self.config.norm_type == "ada_norm_single":
437
+ shift, scale = (self.scale_shift_table[None] + embedded_timestep[:, None]).chunk(2, dim=1)
438
+ hidden_states = self.norm_out(hidden_states)
439
+ # Modulation
440
+ hidden_states = hidden_states * (1 + scale) + shift
441
+ hidden_states = self.proj_out(hidden_states)
442
+ hidden_states = hidden_states.squeeze(1)
443
+
444
+ # unpatchify
445
+ if self.adaln_single is None:
446
+ height = width = int(hidden_states.shape[1] ** 0.5)
447
+ hidden_states = hidden_states.reshape(
448
+ shape=(-1, height, width, self.patch_size, self.patch_size, self.out_channels)
449
+ )
450
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
451
+ output = hidden_states.reshape(
452
+ shape=(-1, self.out_channels, height * self.patch_size, width * self.patch_size)
453
+ )
454
+
455
+ if not return_dict:
456
+ return (output,)
457
+
458
+ return Transformer2DModelOutput(sample=output)
StableDiffusion/Our_UNet.py ADDED
@@ -0,0 +1,1314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from dataclasses import dataclass
15
+ from typing import Any, Dict, List, Optional, Tuple, Union
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.utils.checkpoint
20
+
21
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
22
+ from diffusers.loaders import PeftAdapterMixin, UNet2DConditionLoadersMixin
23
+ from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, logging, scale_lora_layers, unscale_lora_layers
24
+ from diffusers.models.activations import get_activation
25
+ from diffusers.models.attention_processor import (
26
+ ADDED_KV_ATTENTION_PROCESSORS,
27
+ CROSS_ATTENTION_PROCESSORS,
28
+ Attention,
29
+ AttentionProcessor,
30
+ AttnAddedKVProcessor,
31
+ AttnProcessor,
32
+ )
33
+ from diffusers.models.embeddings import (
34
+ GaussianFourierProjection,
35
+ GLIGENTextBoundingboxProjection,
36
+ ImageHintTimeEmbedding,
37
+ ImageProjection,
38
+ ImageTimeEmbedding,
39
+ TextImageProjection,
40
+ TextImageTimeEmbedding,
41
+ TextTimeEmbedding,
42
+ TimestepEmbedding,
43
+ Timesteps,
44
+ )
45
+ from diffusers.models.modeling_utils import ModelMixin
46
+ from .Our_block import (
47
+ get_down_block,
48
+ get_mid_block,
49
+ get_up_block,
50
+ )
51
+
52
+
53
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
54
+
55
+
56
+ @dataclass
57
+ class UNet2DConditionOutput(BaseOutput):
58
+ """
59
+ The output of [`UNet2DConditionModel`].
60
+
61
+ Args:
62
+ sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
63
+ The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.
64
+ """
65
+
66
+ sample: torch.FloatTensor = None
67
+
68
+
69
+ class UNet2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin, PeftAdapterMixin):
70
+ r"""
71
+ A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample
72
+ shaped output.
73
+
74
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
75
+ for all models (such as downloading or saving).
76
+
77
+ Parameters:
78
+ sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
79
+ Height and width of input/output sample.
80
+ in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample.
81
+ out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.
82
+ center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
83
+ flip_sin_to_cos (`bool`, *optional*, defaults to `True`):
84
+ Whether to flip the sin to cos in the time embedding.
85
+ freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
86
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
87
+ The tuple of downsample blocks to use.
88
+ mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
89
+ Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or
90
+ `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped.
91
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`):
92
+ The tuple of upsample blocks to use.
93
+ only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):
94
+ Whether to include self-attention in the basic transformer blocks, see
95
+ [`~models.attention.BasicTransformerBlock`].
96
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
97
+ The tuple of output channels for each block.
98
+ layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
99
+ downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
100
+ mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
101
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
102
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
103
+ norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
104
+ If `None`, normalization and activation layers is skipped in post-processing.
105
+ norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
106
+ cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):
107
+ The dimension of the cross attention features.
108
+ transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):
109
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
110
+ [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
111
+ [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
112
+ reverse_transformer_layers_per_block : (`Tuple[Tuple]`, *optional*, defaults to None):
113
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`], in the upsampling
114
+ blocks of the U-Net. Only relevant if `transformer_layers_per_block` is of type `Tuple[Tuple]` and for
115
+ [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
116
+ [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
117
+ encoder_hid_dim (`int`, *optional*, defaults to None):
118
+ If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
119
+ dimension to `cross_attention_dim`.
120
+ encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
121
+ If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
122
+ embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
123
+ attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
124
+ num_attention_heads (`int`, *optional*):
125
+ The number of attention heads. If not defined, defaults to `attention_head_dim`
126
+ resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
127
+ for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
128
+ class_embed_type (`str`, *optional*, defaults to `None`):
129
+ The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
130
+ `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
131
+ addition_embed_type (`str`, *optional*, defaults to `None`):
132
+ Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
133
+ "text". "text" will use the `TextTimeEmbedding` layer.
134
+ addition_time_embed_dim: (`int`, *optional*, defaults to `None`):
135
+ Dimension for the timestep embeddings.
136
+ num_class_embeds (`int`, *optional*, defaults to `None`):
137
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
138
+ class conditioning with `class_embed_type` equal to `None`.
139
+ time_embedding_type (`str`, *optional*, defaults to `positional`):
140
+ The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.
141
+ time_embedding_dim (`int`, *optional*, defaults to `None`):
142
+ An optional override for the dimension of the projected time embedding.
143
+ time_embedding_act_fn (`str`, *optional*, defaults to `None`):
144
+ Optional activation function to use only once on the time embeddings before they are passed to the rest of
145
+ the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`.
146
+ timestep_post_act (`str`, *optional*, defaults to `None`):
147
+ The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.
148
+ time_cond_proj_dim (`int`, *optional*, defaults to `None`):
149
+ The dimension of `cond_proj` layer in the timestep embedding.
150
+ conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer.
151
+ conv_out_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_out` layer.
152
+ projection_class_embeddings_input_dim (`int`, *optional*): The dimension of the `class_labels` input when
153
+ `class_embed_type="projection"`. Required when `class_embed_type="projection"`.
154
+ class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time
155
+ embeddings with the class embeddings.
156
+ mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`):
157
+ Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If
158
+ `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the
159
+ `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False`
160
+ otherwise.
161
+ """
162
+
163
+ _supports_gradient_checkpointing = True
164
+
165
+ @register_to_config
166
+ def __init__(
167
+ self,
168
+ sample_size: Optional[int] = None,
169
+ in_channels: int = 4,
170
+ out_channels: int = 4,
171
+ center_input_sample: bool = False,
172
+ flip_sin_to_cos: bool = True,
173
+ freq_shift: int = 0,
174
+ down_block_types: Tuple[str] = (
175
+ "CrossAttnDownBlock2D",
176
+ "CrossAttnDownBlock2D",
177
+ "CrossAttnDownBlock2D",
178
+ "DownBlock2D",
179
+ ),
180
+ mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
181
+ up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
182
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
183
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
184
+ layers_per_block: Union[int, Tuple[int]] = 2,
185
+ downsample_padding: int = 1,
186
+ mid_block_scale_factor: float = 1,
187
+ dropout: float = 0.0,
188
+ act_fn: str = "silu",
189
+ norm_num_groups: Optional[int] = 32,
190
+ norm_eps: float = 1e-5,
191
+ cross_attention_dim: Union[int, Tuple[int]] = 1280,
192
+ transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
193
+ reverse_transformer_layers_per_block: Optional[Tuple[Tuple[int]]] = None,
194
+ encoder_hid_dim: Optional[int] = None,
195
+ encoder_hid_dim_type: Optional[str] = None,
196
+ attention_head_dim: Union[int, Tuple[int]] = 8,
197
+ num_attention_heads: Optional[Union[int, Tuple[int]]] = None,
198
+ dual_cross_attention: bool = False,
199
+ use_linear_projection: bool = False,
200
+ class_embed_type: Optional[str] = None,
201
+ addition_embed_type: Optional[str] = None,
202
+ addition_time_embed_dim: Optional[int] = None,
203
+ num_class_embeds: Optional[int] = None,
204
+ upcast_attention: bool = False,
205
+ resnet_time_scale_shift: str = "default",
206
+ resnet_skip_time_act: bool = False,
207
+ resnet_out_scale_factor: float = 1.0,
208
+ time_embedding_type: str = "positional",
209
+ time_embedding_dim: Optional[int] = None,
210
+ time_embedding_act_fn: Optional[str] = None,
211
+ timestep_post_act: Optional[str] = None,
212
+ time_cond_proj_dim: Optional[int] = None,
213
+ conv_in_kernel: int = 3,
214
+ conv_out_kernel: int = 3,
215
+ projection_class_embeddings_input_dim: Optional[int] = None,
216
+ attention_type: str = "default",
217
+ class_embeddings_concat: bool = False,
218
+ mid_block_only_cross_attention: Optional[bool] = None,
219
+ cross_attention_norm: Optional[str] = None,
220
+ addition_embed_type_num_heads: int = 64,
221
+ ):
222
+ super().__init__()
223
+
224
+ self.sample_size = sample_size
225
+
226
+ if num_attention_heads is not None:
227
+ raise ValueError(
228
+ "At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19."
229
+ )
230
+
231
+ # If `num_attention_heads` is not defined (which is the case for most models)
232
+ # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
233
+ # The reason for this behavior is to correct for incorrectly named variables that were introduced
234
+ # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
235
+ # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
236
+ # which is why we correct for the naming here.
237
+ num_attention_heads = num_attention_heads or attention_head_dim
238
+
239
+ # Check inputs
240
+ self._check_config(
241
+ down_block_types=down_block_types,
242
+ up_block_types=up_block_types,
243
+ only_cross_attention=only_cross_attention,
244
+ block_out_channels=block_out_channels,
245
+ layers_per_block=layers_per_block,
246
+ cross_attention_dim=cross_attention_dim,
247
+ transformer_layers_per_block=transformer_layers_per_block,
248
+ reverse_transformer_layers_per_block=reverse_transformer_layers_per_block,
249
+ attention_head_dim=attention_head_dim,
250
+ num_attention_heads=num_attention_heads,
251
+ )
252
+
253
+ # input
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, timestep_input_dim = self._set_time_proj(
261
+ time_embedding_type,
262
+ block_out_channels=block_out_channels,
263
+ flip_sin_to_cos=flip_sin_to_cos,
264
+ freq_shift=freq_shift,
265
+ time_embedding_dim=time_embedding_dim,
266
+ )
267
+
268
+ self.time_embedding = TimestepEmbedding(
269
+ timestep_input_dim,
270
+ time_embed_dim,
271
+ act_fn=act_fn,
272
+ post_act_fn=timestep_post_act,
273
+ cond_proj_dim=time_cond_proj_dim,
274
+ )
275
+
276
+ self._set_encoder_hid_proj(
277
+ encoder_hid_dim_type,
278
+ cross_attention_dim=cross_attention_dim,
279
+ encoder_hid_dim=encoder_hid_dim,
280
+ )
281
+
282
+ # class embedding
283
+ self._set_class_embedding(
284
+ class_embed_type,
285
+ act_fn=act_fn,
286
+ num_class_embeds=num_class_embeds,
287
+ projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,
288
+ time_embed_dim=time_embed_dim,
289
+ timestep_input_dim=timestep_input_dim,
290
+ )
291
+
292
+ self._set_add_embedding(
293
+ addition_embed_type,
294
+ addition_embed_type_num_heads=addition_embed_type_num_heads,
295
+ addition_time_embed_dim=addition_time_embed_dim,
296
+ cross_attention_dim=cross_attention_dim,
297
+ encoder_hid_dim=encoder_hid_dim,
298
+ flip_sin_to_cos=flip_sin_to_cos,
299
+ freq_shift=freq_shift,
300
+ projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,
301
+ time_embed_dim=time_embed_dim,
302
+ )
303
+
304
+ if time_embedding_act_fn is None:
305
+ self.time_embed_act = None
306
+ else:
307
+ self.time_embed_act = get_activation(time_embedding_act_fn)
308
+
309
+ self.down_blocks = nn.ModuleList([])
310
+ self.up_blocks = nn.ModuleList([])
311
+
312
+ if isinstance(only_cross_attention, bool):
313
+ if mid_block_only_cross_attention is None:
314
+ mid_block_only_cross_attention = only_cross_attention
315
+
316
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
317
+
318
+ if mid_block_only_cross_attention is None:
319
+ mid_block_only_cross_attention = False
320
+
321
+ if isinstance(num_attention_heads, int):
322
+ num_attention_heads = (num_attention_heads,) * len(down_block_types)
323
+
324
+ if isinstance(attention_head_dim, int):
325
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
326
+
327
+ if isinstance(cross_attention_dim, int):
328
+ cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
329
+
330
+ if isinstance(layers_per_block, int):
331
+ layers_per_block = [layers_per_block] * len(down_block_types)
332
+
333
+ print(f'layers:{layers_per_block}')
334
+
335
+ if isinstance(transformer_layers_per_block, int):
336
+ transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
337
+
338
+ if class_embeddings_concat:
339
+ # The time embeddings are concatenated with the class embeddings. The dimension of the
340
+ # time embeddings passed to the down, middle, and up blocks is twice the dimension of the
341
+ # regular time embeddings
342
+ blocks_time_embed_dim = time_embed_dim * 2
343
+ else:
344
+ blocks_time_embed_dim = time_embed_dim
345
+
346
+ # down
347
+ output_channel = block_out_channels[0]
348
+ for i, down_block_type in enumerate(down_block_types):
349
+ input_channel = output_channel
350
+ output_channel = block_out_channels[i]
351
+ is_final_block = i == len(block_out_channels) - 1
352
+
353
+ down_block = get_down_block(
354
+ down_block_type,
355
+ num_layers=layers_per_block[i],
356
+ transformer_layers_per_block=transformer_layers_per_block[i],
357
+ in_channels=input_channel,
358
+ out_channels=output_channel,
359
+ temb_channels=blocks_time_embed_dim,
360
+ add_downsample=not is_final_block,
361
+ resnet_eps=norm_eps,
362
+ resnet_act_fn=act_fn,
363
+ resnet_groups=norm_num_groups,
364
+ cross_attention_dim=cross_attention_dim[i],
365
+ num_attention_heads=num_attention_heads[i],
366
+ downsample_padding=downsample_padding,
367
+ dual_cross_attention=dual_cross_attention,
368
+ use_linear_projection=use_linear_projection,
369
+ only_cross_attention=only_cross_attention[i],
370
+ upcast_attention=upcast_attention,
371
+ resnet_time_scale_shift=resnet_time_scale_shift,
372
+ attention_type=attention_type,
373
+ resnet_skip_time_act=resnet_skip_time_act,
374
+ resnet_out_scale_factor=resnet_out_scale_factor,
375
+ cross_attention_norm=cross_attention_norm,
376
+ attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
377
+ dropout=dropout,
378
+ )
379
+ self.down_blocks.append(down_block)
380
+
381
+ # mid
382
+ self.mid_block = get_mid_block(
383
+ mid_block_type,
384
+ temb_channels=blocks_time_embed_dim,
385
+ in_channels=block_out_channels[-1],
386
+ resnet_eps=norm_eps,
387
+ resnet_act_fn=act_fn,
388
+ resnet_groups=norm_num_groups,
389
+ output_scale_factor=mid_block_scale_factor,
390
+ transformer_layers_per_block=transformer_layers_per_block[-1],
391
+ num_attention_heads=num_attention_heads[-1],
392
+ cross_attention_dim=cross_attention_dim[-1],
393
+ dual_cross_attention=dual_cross_attention,
394
+ use_linear_projection=use_linear_projection,
395
+ mid_block_only_cross_attention=mid_block_only_cross_attention,
396
+ upcast_attention=upcast_attention,
397
+ resnet_time_scale_shift=resnet_time_scale_shift,
398
+ attention_type=attention_type,
399
+ resnet_skip_time_act=resnet_skip_time_act,
400
+ cross_attention_norm=cross_attention_norm,
401
+ attention_head_dim=attention_head_dim[-1],
402
+ dropout=dropout,
403
+ )
404
+
405
+ # count how many layers upsample the images
406
+ self.num_upsamplers = 0
407
+
408
+ # up
409
+ reversed_block_out_channels = list(reversed(block_out_channels))
410
+ reversed_num_attention_heads = list(reversed(num_attention_heads))
411
+ reversed_layers_per_block = list(reversed(layers_per_block))
412
+ reversed_cross_attention_dim = list(reversed(cross_attention_dim))
413
+ reversed_transformer_layers_per_block = (
414
+ list(reversed(transformer_layers_per_block))
415
+ if reverse_transformer_layers_per_block is None
416
+ else reverse_transformer_layers_per_block
417
+ )
418
+ only_cross_attention = list(reversed(only_cross_attention))
419
+
420
+ output_channel = reversed_block_out_channels[0]
421
+ for i, up_block_type in enumerate(up_block_types):
422
+ is_final_block = i == len(block_out_channels) - 1
423
+
424
+ prev_output_channel = output_channel
425
+ output_channel = reversed_block_out_channels[i]
426
+ input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
427
+
428
+ # add upsample block for all BUT final layer
429
+ if not is_final_block:
430
+ add_upsample = True
431
+ self.num_upsamplers += 1
432
+ else:
433
+ add_upsample = False
434
+
435
+ up_block = get_up_block(
436
+ up_block_type,
437
+ num_layers=reversed_layers_per_block[i] + 1,
438
+ transformer_layers_per_block=reversed_transformer_layers_per_block[i],
439
+ in_channels=input_channel,
440
+ out_channels=output_channel,
441
+ prev_output_channel=prev_output_channel,
442
+ temb_channels=blocks_time_embed_dim,
443
+ add_upsample=add_upsample,
444
+ resnet_eps=norm_eps,
445
+ resnet_act_fn=act_fn,
446
+ resolution_idx=i,
447
+ resnet_groups=norm_num_groups,
448
+ cross_attention_dim=reversed_cross_attention_dim[i],
449
+ num_attention_heads=reversed_num_attention_heads[i],
450
+ dual_cross_attention=dual_cross_attention,
451
+ use_linear_projection=use_linear_projection,
452
+ only_cross_attention=only_cross_attention[i],
453
+ upcast_attention=upcast_attention,
454
+ resnet_time_scale_shift=resnet_time_scale_shift,
455
+ attention_type=attention_type,
456
+ resnet_skip_time_act=resnet_skip_time_act,
457
+ resnet_out_scale_factor=resnet_out_scale_factor,
458
+ cross_attention_norm=cross_attention_norm,
459
+ attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
460
+ dropout=dropout,
461
+ )
462
+ self.up_blocks.append(up_block)
463
+ prev_output_channel = output_channel
464
+
465
+ # out
466
+ if norm_num_groups is not None:
467
+ self.conv_norm_out = nn.GroupNorm(
468
+ num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
469
+ )
470
+
471
+ self.conv_act = get_activation(act_fn)
472
+
473
+ else:
474
+ self.conv_norm_out = None
475
+ self.conv_act = None
476
+
477
+ conv_out_padding = (conv_out_kernel - 1) // 2
478
+ self.conv_out = nn.Conv2d(
479
+ block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding
480
+ )
481
+
482
+ self._set_pos_net_if_use_gligen(attention_type=attention_type, cross_attention_dim=cross_attention_dim)
483
+
484
+ def _check_config(
485
+ self,
486
+ down_block_types: Tuple[str],
487
+ up_block_types: Tuple[str],
488
+ only_cross_attention: Union[bool, Tuple[bool]],
489
+ block_out_channels: Tuple[int],
490
+ layers_per_block: Union[int, Tuple[int]],
491
+ cross_attention_dim: Union[int, Tuple[int]],
492
+ transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple[int]]],
493
+ reverse_transformer_layers_per_block: bool,
494
+ attention_head_dim: int,
495
+ num_attention_heads: Optional[Union[int, Tuple[int]]],
496
+ ):
497
+ if len(down_block_types) != len(up_block_types):
498
+ raise ValueError(
499
+ f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}."
500
+ )
501
+
502
+ if len(block_out_channels) != len(down_block_types):
503
+ raise ValueError(
504
+ 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}."
505
+ )
506
+
507
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
508
+ raise ValueError(
509
+ 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}."
510
+ )
511
+
512
+ if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
513
+ raise ValueError(
514
+ 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}."
515
+ )
516
+
517
+ if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
518
+ raise ValueError(
519
+ f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
520
+ )
521
+
522
+ if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types):
523
+ raise ValueError(
524
+ f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}."
525
+ )
526
+
527
+ if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types):
528
+ raise ValueError(
529
+ f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}."
530
+ )
531
+ if isinstance(transformer_layers_per_block, list) and reverse_transformer_layers_per_block is None:
532
+ for layer_number_per_block in transformer_layers_per_block:
533
+ if isinstance(layer_number_per_block, list):
534
+ raise ValueError("Must provide 'reverse_transformer_layers_per_block` if using asymmetrical UNet.")
535
+
536
+ def _set_time_proj(
537
+ self,
538
+ time_embedding_type: str,
539
+ block_out_channels: int,
540
+ flip_sin_to_cos: bool,
541
+ freq_shift: float,
542
+ time_embedding_dim: int,
543
+ ) -> Tuple[int, int]:
544
+ if time_embedding_type == "fourier":
545
+ time_embed_dim = time_embedding_dim or block_out_channels[0] * 2
546
+ if time_embed_dim % 2 != 0:
547
+ raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.")
548
+ self.time_proj = GaussianFourierProjection(
549
+ time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos
550
+ )
551
+ timestep_input_dim = time_embed_dim
552
+ elif time_embedding_type == "positional":
553
+ time_embed_dim = time_embedding_dim or block_out_channels[0] * 4
554
+
555
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
556
+ timestep_input_dim = block_out_channels[0]
557
+ else:
558
+ raise ValueError(
559
+ f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`."
560
+ )
561
+
562
+ return time_embed_dim, timestep_input_dim
563
+
564
+ def _set_encoder_hid_proj(
565
+ self,
566
+ encoder_hid_dim_type: Optional[str],
567
+ cross_attention_dim: Union[int, Tuple[int]],
568
+ encoder_hid_dim: Optional[int],
569
+ ):
570
+ if encoder_hid_dim_type is None and encoder_hid_dim is not None:
571
+ encoder_hid_dim_type = "text_proj"
572
+ self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
573
+ logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.")
574
+
575
+ if encoder_hid_dim is None and encoder_hid_dim_type is not None:
576
+ raise ValueError(
577
+ f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
578
+ )
579
+
580
+ if encoder_hid_dim_type == "text_proj":
581
+ self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
582
+ elif encoder_hid_dim_type == "text_image_proj":
583
+ # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
584
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
585
+ # case when `addition_embed_type == "text_image_proj"` (Kadinsky 2.1)`
586
+ self.encoder_hid_proj = TextImageProjection(
587
+ text_embed_dim=encoder_hid_dim,
588
+ image_embed_dim=cross_attention_dim,
589
+ cross_attention_dim=cross_attention_dim,
590
+ )
591
+ elif encoder_hid_dim_type == "image_proj":
592
+ # Kandinsky 2.2
593
+ self.encoder_hid_proj = ImageProjection(
594
+ image_embed_dim=encoder_hid_dim,
595
+ cross_attention_dim=cross_attention_dim,
596
+ )
597
+ elif encoder_hid_dim_type is not None:
598
+ raise ValueError(
599
+ f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'."
600
+ )
601
+ else:
602
+ self.encoder_hid_proj = None
603
+
604
+ def _set_class_embedding(
605
+ self,
606
+ class_embed_type: Optional[str],
607
+ act_fn: str,
608
+ num_class_embeds: Optional[int],
609
+ projection_class_embeddings_input_dim: Optional[int],
610
+ time_embed_dim: int,
611
+ timestep_input_dim: int,
612
+ ):
613
+ if class_embed_type is None and num_class_embeds is not None:
614
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
615
+ elif class_embed_type == "timestep":
616
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn)
617
+ elif class_embed_type == "identity":
618
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
619
+ elif class_embed_type == "projection":
620
+ if projection_class_embeddings_input_dim is None:
621
+ raise ValueError(
622
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
623
+ )
624
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
625
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
626
+ # 2. it projects from an arbitrary input dimension.
627
+ #
628
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
629
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
630
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
631
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
632
+ elif class_embed_type == "simple_projection":
633
+ if projection_class_embeddings_input_dim is None:
634
+ raise ValueError(
635
+ "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set"
636
+ )
637
+ self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim)
638
+ else:
639
+ self.class_embedding = None
640
+
641
+ def _set_add_embedding(
642
+ self,
643
+ addition_embed_type: str,
644
+ addition_embed_type_num_heads: int,
645
+ addition_time_embed_dim: Optional[int],
646
+ flip_sin_to_cos: bool,
647
+ freq_shift: float,
648
+ cross_attention_dim: Optional[int],
649
+ encoder_hid_dim: Optional[int],
650
+ projection_class_embeddings_input_dim: Optional[int],
651
+ time_embed_dim: int,
652
+ ):
653
+ if addition_embed_type == "text":
654
+ if encoder_hid_dim is not None:
655
+ text_time_embedding_from_dim = encoder_hid_dim
656
+ else:
657
+ text_time_embedding_from_dim = cross_attention_dim
658
+
659
+ self.add_embedding = TextTimeEmbedding(
660
+ text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads
661
+ )
662
+ elif addition_embed_type == "text_image":
663
+ # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
664
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
665
+ # case when `addition_embed_type == "text_image"` (Kadinsky 2.1)`
666
+ self.add_embedding = TextImageTimeEmbedding(
667
+ text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim
668
+ )
669
+ elif addition_embed_type == "text_time":
670
+ self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)
671
+ self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
672
+ elif addition_embed_type == "image":
673
+ # Kandinsky 2.2
674
+ self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
675
+ elif addition_embed_type == "image_hint":
676
+ # Kandinsky 2.2 ControlNet
677
+ self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
678
+ elif addition_embed_type is not None:
679
+ raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.")
680
+
681
+ def _set_pos_net_if_use_gligen(self, attention_type: str, cross_attention_dim: int):
682
+ if attention_type in ["gated", "gated-text-image"]:
683
+ positive_len = 768
684
+ if isinstance(cross_attention_dim, int):
685
+ positive_len = cross_attention_dim
686
+ elif isinstance(cross_attention_dim, tuple) or isinstance(cross_attention_dim, list):
687
+ positive_len = cross_attention_dim[0]
688
+
689
+ feature_type = "text-only" if attention_type == "gated" else "text-image"
690
+ self.position_net = GLIGENTextBoundingboxProjection(
691
+ positive_len=positive_len, out_dim=cross_attention_dim, feature_type=feature_type
692
+ )
693
+
694
+ @property
695
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
696
+ r"""
697
+ Returns:
698
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
699
+ indexed by its weight name.
700
+ """
701
+ # set recursively
702
+ processors = {}
703
+
704
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
705
+ if hasattr(module, "get_processor"):
706
+ processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
707
+
708
+ for sub_name, child in module.named_children():
709
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
710
+
711
+ return processors
712
+
713
+ for name, module in self.named_children():
714
+ fn_recursive_add_processors(name, module, processors)
715
+
716
+ return processors
717
+
718
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
719
+ r"""
720
+ Sets the attention processor to use to compute attention.
721
+
722
+ Parameters:
723
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
724
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
725
+ for **all** `Attention` layers.
726
+
727
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
728
+ processor. This is strongly recommended when setting trainable attention processors.
729
+
730
+ """
731
+ count = len(self.attn_processors.keys())
732
+
733
+ if isinstance(processor, dict) and len(processor) != count:
734
+ raise ValueError(
735
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
736
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
737
+ )
738
+
739
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
740
+ if hasattr(module, "set_processor"):
741
+ if not isinstance(processor, dict):
742
+ module.set_processor(processor)
743
+ else:
744
+ module.set_processor(processor.pop(f"{name}.processor"))
745
+
746
+ for sub_name, child in module.named_children():
747
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
748
+
749
+ for name, module in self.named_children():
750
+ fn_recursive_attn_processor(name, module, processor)
751
+
752
+ def set_default_attn_processor(self):
753
+ """
754
+ Disables custom attention processors and sets the default attention implementation.
755
+ """
756
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
757
+ processor = AttnAddedKVProcessor()
758
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
759
+ processor = AttnProcessor()
760
+ else:
761
+ raise ValueError(
762
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
763
+ )
764
+
765
+ self.set_attn_processor(processor)
766
+
767
+ def set_attention_slice(self, slice_size: Union[str, int, List[int]] = "auto"):
768
+ r"""
769
+ Enable sliced attention computation.
770
+
771
+ When this option is enabled, the attention module splits the input tensor in slices to compute attention in
772
+ several steps. This is useful for saving some memory in exchange for a small decrease in speed.
773
+
774
+ Args:
775
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
776
+ When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
777
+ `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
778
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
779
+ must be a multiple of `slice_size`.
780
+ """
781
+ sliceable_head_dims = []
782
+
783
+ def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
784
+ if hasattr(module, "set_attention_slice"):
785
+ sliceable_head_dims.append(module.sliceable_head_dim)
786
+
787
+ for child in module.children():
788
+ fn_recursive_retrieve_sliceable_dims(child)
789
+
790
+ # retrieve number of attention layers
791
+ for module in self.children():
792
+ fn_recursive_retrieve_sliceable_dims(module)
793
+
794
+ num_sliceable_layers = len(sliceable_head_dims)
795
+
796
+ if slice_size == "auto":
797
+ # half the attention head size is usually a good trade-off between
798
+ # speed and memory
799
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
800
+ elif slice_size == "max":
801
+ # make smallest slice possible
802
+ slice_size = num_sliceable_layers * [1]
803
+
804
+ slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
805
+
806
+ if len(slice_size) != len(sliceable_head_dims):
807
+ raise ValueError(
808
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
809
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
810
+ )
811
+
812
+ for i in range(len(slice_size)):
813
+ size = slice_size[i]
814
+ dim = sliceable_head_dims[i]
815
+ if size is not None and size > dim:
816
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
817
+
818
+ # Recursively walk through all the children.
819
+ # Any children which exposes the set_attention_slice method
820
+ # gets the message
821
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
822
+ if hasattr(module, "set_attention_slice"):
823
+ module.set_attention_slice(slice_size.pop())
824
+
825
+ for child in module.children():
826
+ fn_recursive_set_attention_slice(child, slice_size)
827
+
828
+ reversed_slice_size = list(reversed(slice_size))
829
+ for module in self.children():
830
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
831
+
832
+ def _set_gradient_checkpointing(self, module, value=False):
833
+ if hasattr(module, "gradient_checkpointing"):
834
+ module.gradient_checkpointing = value
835
+
836
+ def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
837
+ r"""Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497.
838
+
839
+ The suffixes after the scaling factors represent the stage blocks where they are being applied.
840
+
841
+ Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that
842
+ are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
843
+
844
+ Args:
845
+ s1 (`float`):
846
+ Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
847
+ mitigate the "oversmoothing effect" in the enhanced denoising process.
848
+ s2 (`float`):
849
+ Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
850
+ mitigate the "oversmoothing effect" in the enhanced denoising process.
851
+ b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
852
+ b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
853
+ """
854
+ for i, upsample_block in enumerate(self.up_blocks):
855
+ setattr(upsample_block, "s1", s1)
856
+ setattr(upsample_block, "s2", s2)
857
+ setattr(upsample_block, "b1", b1)
858
+ setattr(upsample_block, "b2", b2)
859
+
860
+ def disable_freeu(self):
861
+ """Disables the FreeU mechanism."""
862
+ freeu_keys = {"s1", "s2", "b1", "b2"}
863
+ for i, upsample_block in enumerate(self.up_blocks):
864
+ for k in freeu_keys:
865
+ if hasattr(upsample_block, k) or getattr(upsample_block, k, None) is not None:
866
+ setattr(upsample_block, k, None)
867
+
868
+ def fuse_qkv_projections(self):
869
+ """
870
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query,
871
+ key, value) are fused. For cross-attention modules, key and value projection matrices are fused.
872
+
873
+ <Tip warning={true}>
874
+
875
+ This API is 🧪 experimental.
876
+
877
+ </Tip>
878
+ """
879
+ self.original_attn_processors = None
880
+
881
+ for _, attn_processor in self.attn_processors.items():
882
+ if "Added" in str(attn_processor.__class__.__name__):
883
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
884
+
885
+ self.original_attn_processors = self.attn_processors
886
+
887
+ for module in self.modules():
888
+ if isinstance(module, Attention):
889
+ module.fuse_projections(fuse=True)
890
+
891
+ def unfuse_qkv_projections(self):
892
+ """Disables the fused QKV projection if enabled.
893
+
894
+ <Tip warning={true}>
895
+
896
+ This API is 🧪 experimental.
897
+
898
+ </Tip>
899
+
900
+ """
901
+ if self.original_attn_processors is not None:
902
+ self.set_attn_processor(self.original_attn_processors)
903
+
904
+ def unload_lora(self):
905
+ """Unloads LoRA weights."""
906
+ deprecate(
907
+ "unload_lora",
908
+ "0.28.0",
909
+ "Calling `unload_lora()` is deprecated and will be removed in a future version. Please install `peft` and then call `disable_adapters().",
910
+ )
911
+ for module in self.modules():
912
+ if hasattr(module, "set_lora_layer"):
913
+ module.set_lora_layer(None)
914
+
915
+ def get_time_embed(
916
+ self, sample: torch.Tensor, timestep: Union[torch.Tensor, float, int]
917
+ ) -> Optional[torch.Tensor]:
918
+ timesteps = timestep
919
+ if not torch.is_tensor(timesteps):
920
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
921
+ # This would be a good case for the `match` statement (Python 3.10+)
922
+ is_mps = sample.device.type == "mps"
923
+ if isinstance(timestep, float):
924
+ dtype = torch.float32 if is_mps else torch.float64
925
+ else:
926
+ dtype = torch.int32 if is_mps else torch.int64
927
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
928
+ elif len(timesteps.shape) == 0:
929
+ timesteps = timesteps[None].to(sample.device)
930
+
931
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
932
+ timesteps = timesteps.expand(sample.shape[0])
933
+
934
+ t_emb = self.time_proj(timesteps)
935
+ # `Timesteps` does not contain any weights and will always return f32 tensors
936
+ # but time_embedding might actually be running in fp16. so we need to cast here.
937
+ # there might be better ways to encapsulate this.
938
+ t_emb = t_emb.to(dtype=sample.dtype)
939
+ return t_emb
940
+
941
+ def get_class_embed(self, sample: torch.Tensor, class_labels: Optional[torch.Tensor]) -> Optional[torch.Tensor]:
942
+ class_emb = None
943
+ if self.class_embedding is not None:
944
+ if class_labels is None:
945
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
946
+
947
+ if self.config.class_embed_type == "timestep":
948
+ class_labels = self.time_proj(class_labels)
949
+
950
+ # `Timesteps` does not contain any weights and will always return f32 tensors
951
+ # there might be better ways to encapsulate this.
952
+ class_labels = class_labels.to(dtype=sample.dtype)
953
+
954
+ class_emb = self.class_embedding(class_labels).to(dtype=sample.dtype)
955
+ return class_emb
956
+
957
+ def get_aug_embed(
958
+ self, emb: torch.Tensor, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
959
+ ) -> Optional[torch.Tensor]:
960
+ aug_emb = None
961
+ if self.config.addition_embed_type == "text":
962
+ aug_emb = self.add_embedding(encoder_hidden_states)
963
+ elif self.config.addition_embed_type == "text_image":
964
+ # Kandinsky 2.1 - style
965
+ if "image_embeds" not in added_cond_kwargs:
966
+ raise ValueError(
967
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`"
968
+ )
969
+
970
+ image_embs = added_cond_kwargs.get("image_embeds")
971
+ text_embs = added_cond_kwargs.get("text_embeds", encoder_hidden_states)
972
+ aug_emb = self.add_embedding(text_embs, image_embs)
973
+ elif self.config.addition_embed_type == "text_time":
974
+ # SDXL - style
975
+ if "text_embeds" not in added_cond_kwargs:
976
+ raise ValueError(
977
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `text_embeds` to be passed in `added_cond_kwargs`"
978
+ )
979
+ text_embeds = added_cond_kwargs.get("text_embeds")
980
+ if "time_ids" not in added_cond_kwargs:
981
+ raise ValueError(
982
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `time_ids` to be passed in `added_cond_kwargs`"
983
+ )
984
+ time_ids = added_cond_kwargs.get("time_ids")
985
+ time_embeds = self.add_time_proj(time_ids.flatten())
986
+ time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
987
+ add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
988
+ add_embeds = add_embeds.to(emb.dtype)
989
+ aug_emb = self.add_embedding(add_embeds)
990
+ elif self.config.addition_embed_type == "image":
991
+ # Kandinsky 2.2 - style
992
+ if "image_embeds" not in added_cond_kwargs:
993
+ raise ValueError(
994
+ f"{self.__class__} has the config param `addition_embed_type` set to 'image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`"
995
+ )
996
+ image_embs = added_cond_kwargs.get("image_embeds")
997
+ aug_emb = self.add_embedding(image_embs)
998
+ elif self.config.addition_embed_type == "image_hint":
999
+ # Kandinsky 2.2 - style
1000
+ if "image_embeds" not in added_cond_kwargs or "hint" not in added_cond_kwargs:
1001
+ raise ValueError(
1002
+ f"{self.__class__} has the config param `addition_embed_type` set to 'image_hint' which requires the keyword arguments `image_embeds` and `hint` to be passed in `added_cond_kwargs`"
1003
+ )
1004
+ image_embs = added_cond_kwargs.get("image_embeds")
1005
+ hint = added_cond_kwargs.get("hint")
1006
+ aug_emb = self.add_embedding(image_embs, hint)
1007
+ return aug_emb
1008
+
1009
+ def process_encoder_hidden_states(
1010
+ self, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
1011
+ ) -> torch.Tensor:
1012
+ if self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_proj":
1013
+ encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states)
1014
+ elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_image_proj":
1015
+ # Kadinsky 2.1 - style
1016
+ if "image_embeds" not in added_cond_kwargs:
1017
+ raise ValueError(
1018
+ f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'text_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
1019
+ )
1020
+
1021
+ image_embeds = added_cond_kwargs.get("image_embeds")
1022
+ encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states, image_embeds)
1023
+ elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "image_proj":
1024
+ # Kandinsky 2.2 - style
1025
+ if "image_embeds" not in added_cond_kwargs:
1026
+ raise ValueError(
1027
+ f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
1028
+ )
1029
+ image_embeds = added_cond_kwargs.get("image_embeds")
1030
+ encoder_hidden_states = self.encoder_hid_proj(image_embeds)
1031
+ elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "ip_image_proj":
1032
+ if "image_embeds" not in added_cond_kwargs:
1033
+ raise ValueError(
1034
+ f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'ip_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
1035
+ )
1036
+ image_embeds = added_cond_kwargs.get("image_embeds")
1037
+ image_embeds = self.encoder_hid_proj(image_embeds)
1038
+ encoder_hidden_states = (encoder_hidden_states, image_embeds)
1039
+ return encoder_hidden_states
1040
+
1041
+ def forward(
1042
+ self,
1043
+ sample: torch.FloatTensor,
1044
+ timestep: Union[torch.Tensor, float, int],
1045
+ encoder_hidden_states: torch.Tensor,
1046
+ class_labels: Optional[torch.Tensor] = None,
1047
+ timestep_cond: Optional[torch.Tensor] = None,
1048
+ attention_mask: Optional[torch.Tensor] = None,
1049
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1050
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
1051
+ down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
1052
+ mid_block_additional_residual: Optional[torch.Tensor] = None,
1053
+ down_intrablock_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
1054
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1055
+ return_dict: bool = True,
1056
+ ) -> Union[UNet2DConditionOutput, Tuple]:
1057
+ r"""
1058
+ The [`UNet2DConditionModel`] forward method.
1059
+
1060
+ Args:
1061
+ sample (`torch.FloatTensor`):
1062
+ The noisy input tensor with the following shape `(batch, channel, height, width)`.
1063
+ timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
1064
+ encoder_hidden_states (`torch.FloatTensor`):
1065
+ The encoder hidden states with shape `(batch, sequence_length, feature_dim)`.
1066
+ class_labels (`torch.Tensor`, *optional*, defaults to `None`):
1067
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
1068
+ timestep_cond: (`torch.Tensor`, *optional*, defaults to `None`):
1069
+ Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed
1070
+ through the `self.time_embedding` layer to obtain the timestep embeddings.
1071
+ attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
1072
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
1073
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
1074
+ negative values to the attention scores corresponding to "discard" tokens.
1075
+ cross_attention_kwargs (`dict`, *optional*):
1076
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1077
+ `self.processor` in
1078
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1079
+ added_cond_kwargs: (`dict`, *optional*):
1080
+ A kwargs dictionary containing additional embeddings that if specified are added to the embeddings that
1081
+ are passed along to the UNet blocks.
1082
+ down_block_additional_residuals: (`tuple` of `torch.Tensor`, *optional*):
1083
+ A tuple of tensors that if specified are added to the residuals of down unet blocks.
1084
+ mid_block_additional_residual: (`torch.Tensor`, *optional*):
1085
+ A tensor that if specified is added to the residual of the middle unet block.
1086
+ down_intrablock_additional_residuals (`tuple` of `torch.Tensor`, *optional*):
1087
+ additional residuals to be added within UNet down blocks, for example from T2I-Adapter side model(s)
1088
+ encoder_attention_mask (`torch.Tensor`):
1089
+ A cross-attention mask of shape `(batch, sequence_length)` is applied to `encoder_hidden_states`. If
1090
+ `True` the mask is kept, otherwise if `False` it is discarded. Mask will be converted into a bias,
1091
+ which adds large negative values to the attention scores corresponding to "discard" tokens.
1092
+ return_dict (`bool`, *optional*, defaults to `True`):
1093
+ Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
1094
+ tuple.
1095
+
1096
+ Returns:
1097
+ [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
1098
+ If `return_dict` is True, an [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] is returned, otherwise
1099
+ a `tuple` is returned where the first element is the sample tensor.
1100
+ """
1101
+ # By default samples have to be AT least a multiple of the overall upsampling factor.
1102
+ # The overall upsampling factor is equal to 2 ** (# num of upsampling layers).
1103
+ # However, the upsampling interpolation output size can be forced to fit any upsampling size
1104
+ # on the fly if necessary.
1105
+ default_overall_up_factor = 2**self.num_upsamplers
1106
+
1107
+ # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
1108
+ forward_upsample_size = False
1109
+ upsample_size = None
1110
+
1111
+ for dim in sample.shape[-2:]:
1112
+ if dim % default_overall_up_factor != 0:
1113
+ # Forward upsample size to force interpolation output size.
1114
+ forward_upsample_size = True
1115
+ break
1116
+
1117
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension
1118
+ # expects mask of shape:
1119
+ # [batch, key_tokens]
1120
+ # adds singleton query_tokens dimension:
1121
+ # [batch, 1, key_tokens]
1122
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
1123
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
1124
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
1125
+ if attention_mask is not None:
1126
+ # assume that mask is expressed as:
1127
+ # (1 = keep, 0 = discard)
1128
+ # convert mask into a bias that can be added to attention scores:
1129
+ # (keep = +0, discard = -10000.0)
1130
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
1131
+ attention_mask = attention_mask.unsqueeze(1)
1132
+
1133
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
1134
+ if encoder_attention_mask is not None:
1135
+ encoder_attention_mask = (1 - encoder_attention_mask.to(sample.dtype)) * -10000.0
1136
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
1137
+
1138
+ # 0. center input if necessary
1139
+ if self.config.center_input_sample:
1140
+ sample = 2 * sample - 1.0
1141
+
1142
+ # 1. time
1143
+ t_emb = self.get_time_embed(sample=sample, timestep=timestep)
1144
+ emb = self.time_embedding(t_emb, timestep_cond)
1145
+ aug_emb = None
1146
+
1147
+ class_emb = self.get_class_embed(sample=sample, class_labels=class_labels)
1148
+ if class_emb is not None:
1149
+ if self.config.class_embeddings_concat:
1150
+ emb = torch.cat([emb, class_emb], dim=-1)
1151
+ else:
1152
+ emb = emb + class_emb
1153
+
1154
+ aug_emb = self.get_aug_embed(
1155
+ emb=emb, encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
1156
+ )
1157
+ if self.config.addition_embed_type == "image_hint":
1158
+ aug_emb, hint = aug_emb
1159
+ sample = torch.cat([sample, hint], dim=1)
1160
+
1161
+ emb = emb + aug_emb if aug_emb is not None else emb
1162
+
1163
+ if self.time_embed_act is not None:
1164
+ emb = self.time_embed_act(emb)
1165
+
1166
+ encoder_hidden_states = self.process_encoder_hidden_states(
1167
+ encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
1168
+ )
1169
+
1170
+ # 2. pre-process
1171
+ sample = self.conv_in(sample)
1172
+
1173
+ # 2.5 GLIGEN position net
1174
+ if cross_attention_kwargs is not None and cross_attention_kwargs.get("gligen", None) is not None:
1175
+ cross_attention_kwargs = cross_attention_kwargs.copy()
1176
+ gligen_args = cross_attention_kwargs.pop("gligen")
1177
+ cross_attention_kwargs["gligen"] = {"objs": self.position_net(**gligen_args)}
1178
+
1179
+ # 3. down
1180
+ # we're popping the `scale` instead of getting it because otherwise `scale` will be propagated
1181
+ # to the internal blocks and will raise deprecation warnings. this will be confusing for our users.
1182
+ if cross_attention_kwargs is not None:
1183
+ cross_attention_kwargs = cross_attention_kwargs.copy()
1184
+ lora_scale = cross_attention_kwargs.pop("scale", 1.0)
1185
+ else:
1186
+ lora_scale = 1.0
1187
+
1188
+ if USE_PEFT_BACKEND:
1189
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
1190
+ scale_lora_layers(self, lora_scale)
1191
+
1192
+ is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None
1193
+ # using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets
1194
+ is_adapter = down_intrablock_additional_residuals is not None
1195
+ # maintain backward compatibility for legacy usage, where
1196
+ # T2I-Adapter and ControlNet both use down_block_additional_residuals arg
1197
+ # but can only use one or the other
1198
+ if not is_adapter and mid_block_additional_residual is None and down_block_additional_residuals is not None:
1199
+ deprecate(
1200
+ "T2I should not use down_block_additional_residuals",
1201
+ "1.3.0",
1202
+ "Passing intrablock residual connections with `down_block_additional_residuals` is deprecated \
1203
+ and will be removed in diffusers 1.3.0. `down_block_additional_residuals` should only be used \
1204
+ for ControlNet. Please make sure use `down_intrablock_additional_residuals` instead. ",
1205
+ standard_warn=False,
1206
+ )
1207
+ down_intrablock_additional_residuals = down_block_additional_residuals
1208
+ is_adapter = True
1209
+
1210
+ down_block_res_samples = (sample,)
1211
+ for downsample_block in self.down_blocks:
1212
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
1213
+ # For t2i-adapter CrossAttnDownBlock2D
1214
+ additional_residuals = {}
1215
+ if is_adapter and len(down_intrablock_additional_residuals) > 0:
1216
+ additional_residuals["additional_residuals"] = down_intrablock_additional_residuals.pop(0)
1217
+
1218
+ sample, res_samples = downsample_block(
1219
+ hidden_states=sample,
1220
+ temb=emb,
1221
+ encoder_hidden_states=encoder_hidden_states,
1222
+ attention_mask=attention_mask,
1223
+ cross_attention_kwargs=cross_attention_kwargs,
1224
+ encoder_attention_mask=encoder_attention_mask,
1225
+ **additional_residuals,
1226
+ )
1227
+ else:
1228
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
1229
+ if is_adapter and len(down_intrablock_additional_residuals) > 0:
1230
+ sample += down_intrablock_additional_residuals.pop(0)
1231
+
1232
+ down_block_res_samples += res_samples
1233
+
1234
+ if is_controlnet:
1235
+ new_down_block_res_samples = ()
1236
+
1237
+ for down_block_res_sample, down_block_additional_residual in zip(
1238
+ down_block_res_samples, down_block_additional_residuals
1239
+ ):
1240
+ down_block_res_sample = down_block_res_sample + down_block_additional_residual
1241
+ new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)
1242
+
1243
+ down_block_res_samples = new_down_block_res_samples
1244
+
1245
+ # 4. mid
1246
+ if self.mid_block is not None:
1247
+ if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
1248
+ sample = self.mid_block(
1249
+ sample,
1250
+ emb,
1251
+ encoder_hidden_states=encoder_hidden_states,
1252
+ attention_mask=attention_mask,
1253
+ cross_attention_kwargs=cross_attention_kwargs,
1254
+ encoder_attention_mask=encoder_attention_mask,
1255
+ )
1256
+ else:
1257
+ sample = self.mid_block(sample, emb)
1258
+
1259
+ # To support T2I-Adapter-XL
1260
+ if (
1261
+ is_adapter
1262
+ and len(down_intrablock_additional_residuals) > 0
1263
+ and sample.shape == down_intrablock_additional_residuals[0].shape
1264
+ ):
1265
+ sample += down_intrablock_additional_residuals.pop(0)
1266
+
1267
+ if is_controlnet:
1268
+ sample = sample + mid_block_additional_residual
1269
+
1270
+ # 5. up
1271
+ for i, upsample_block in enumerate(self.up_blocks):
1272
+ is_final_block = i == len(self.up_blocks) - 1
1273
+
1274
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
1275
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
1276
+
1277
+ # if we have not reached the final block and need to forward the
1278
+ # upsample size, we do it here
1279
+ if not is_final_block and forward_upsample_size:
1280
+ upsample_size = down_block_res_samples[-1].shape[2:]
1281
+
1282
+ if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
1283
+ sample = upsample_block(
1284
+ hidden_states=sample,
1285
+ temb=emb,
1286
+ res_hidden_states_tuple=res_samples,
1287
+ encoder_hidden_states=encoder_hidden_states,
1288
+ cross_attention_kwargs=cross_attention_kwargs,
1289
+ upsample_size=upsample_size,
1290
+ attention_mask=attention_mask,
1291
+ encoder_attention_mask=encoder_attention_mask,
1292
+ )
1293
+ else:
1294
+ sample = upsample_block(
1295
+ hidden_states=sample,
1296
+ temb=emb,
1297
+ res_hidden_states_tuple=res_samples,
1298
+ upsample_size=upsample_size,
1299
+ )
1300
+
1301
+ # 6. post-process
1302
+ if self.conv_norm_out:
1303
+ sample = self.conv_norm_out(sample)
1304
+ sample = self.conv_act(sample)
1305
+ sample = self.conv_out(sample)
1306
+
1307
+ if USE_PEFT_BACKEND:
1308
+ # remove `lora_scale` from each PEFT layer
1309
+ unscale_lora_layers(self, lora_scale)
1310
+
1311
+ if not return_dict:
1312
+ return (sample,)
1313
+
1314
+ return UNet2DConditionOutput(sample=sample)
StableDiffusion/Our_block.py ADDED
The diff for this file is too large to render. See raw diff
 
StableDiffusion/__pycache__/Our_Attention.cpython-310.pyc ADDED
Binary file (60 kB). View file
 
StableDiffusion/__pycache__/Our_Attention.cpython-38.pyc ADDED
Binary file (60.7 kB). View file
 
StableDiffusion/__pycache__/Our_AttnBlock.cpython-310.pyc ADDED
Binary file (16.9 kB). View file
 
StableDiffusion/__pycache__/Our_AttnBlock.cpython-38.pyc ADDED
Binary file (16.6 kB). View file
 
StableDiffusion/__pycache__/Our_Pipe.cpython-310.pyc ADDED
Binary file (34.1 kB). View file
 
StableDiffusion/__pycache__/Our_Processor.cpython-310.pyc ADDED
Binary file (30.4 kB). View file
 
StableDiffusion/__pycache__/Our_Transformer.cpython-310.pyc ADDED
Binary file (14.7 kB). View file
 
StableDiffusion/__pycache__/Our_Transformer.cpython-38.pyc ADDED
Binary file (14.5 kB). View file
 
StableDiffusion/__pycache__/Our_UNet.cpython-310.pyc ADDED
Binary file (41 kB). View file
 
StableDiffusion/__pycache__/Our_UNet.cpython-38.pyc ADDED
Binary file (40.4 kB). View file
 
StableDiffusion/__pycache__/Our_block.cpython-310.pyc ADDED
Binary file (65.9 kB). View file
 
StableDiffusion/__pycache__/Our_block.cpython-38.pyc ADDED
Binary file (63.1 kB). View file