AdithyaSK HF Staff commited on
Commit
b4100d4
·
verified ·
1 Parent(s): fd9e5a9

Stage Harbor release files 60001-60500

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/unidiffuser/modeling_uvit.py +1197 -0
  2. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +1462 -0
  3. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/visualcloze/__init__.py +52 -0
  4. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_combined.py +440 -0
  5. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py +977 -0
  6. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/visualcloze/visualcloze_utils.py +251 -0
  7. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wan/__init__.py +54 -0
  8. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wan/image_processor.py +185 -0
  9. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wan/pipeline_output.py +20 -0
  10. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wan/pipeline_wan.py +656 -0
  11. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wan/pipeline_wan_animate.py +1204 -0
  12. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wan/pipeline_wan_i2v.py +824 -0
  13. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wan/pipeline_wan_vace.py +1045 -0
  14. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wan/pipeline_wan_video2video.py +725 -0
  15. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wuerstchen/__init__.py +56 -0
  16. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +172 -0
  17. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +76 -0
  18. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py +254 -0
  19. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +174 -0
  20. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +449 -0
  21. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +307 -0
  22. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +528 -0
  23. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/py.typed +0 -0
  24. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/__init__.py +18 -0
  25. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/auto.py +150 -0
  26. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/base.py +245 -0
  27. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/bitsandbytes/__init__.py +2 -0
  28. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py +577 -0
  29. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/bitsandbytes/utils.py +319 -0
  30. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/gguf/__init__.py +1 -0
  31. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/gguf/gguf_quantizer.py +169 -0
  32. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/gguf/utils.py +606 -0
  33. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/modelopt/__init__.py +1 -0
  34. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/modelopt/modelopt_quantizer.py +190 -0
  35. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/pipe_quant_config.py +205 -0
  36. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/quantization_config.py +1038 -0
  37. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/quanto/__init__.py +1 -0
  38. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/quanto/quanto_quantizer.py +181 -0
  39. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/quanto/utils.py +60 -0
  40. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/torchao/__init__.py +15 -0
  41. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/torchao/torchao_quantizer.py +417 -0
  42. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/README.md +3 -0
  43. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/__init__.py +224 -0
  44. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/deprecated/__init__.py +50 -0
  45. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/deprecated/scheduling_karras_ve.py +240 -0
  46. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/deprecated/scheduling_sde_vp.py +109 -0
  47. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/scheduling_amused.py +275 -0
  48. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/scheduling_consistency_decoder.py +181 -0
  49. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/scheduling_consistency_models.py +479 -0
  50. tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +601 -0
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/unidiffuser/modeling_uvit.py ADDED
@@ -0,0 +1,1197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Optional, Union
3
+
4
+ import torch
5
+ from torch import nn
6
+
7
+ from ...configuration_utils import ConfigMixin, register_to_config
8
+ from ...models import ModelMixin
9
+ from ...models.attention import FeedForward
10
+ from ...models.attention_processor import Attention
11
+ from ...models.embeddings import TimestepEmbedding, Timesteps, get_2d_sincos_pos_embed
12
+ from ...models.modeling_outputs import Transformer2DModelOutput
13
+ from ...models.normalization import AdaLayerNorm
14
+ from ...utils import logging
15
+
16
+
17
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
18
+
19
+
20
+ def _no_grad_trunc_normal_(tensor, mean, std, a, b):
21
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
22
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
23
+ def norm_cdf(x):
24
+ # Computes standard normal cumulative distribution function
25
+ return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
26
+
27
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
28
+ logger.warning(
29
+ "mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
30
+ "The distribution of values may be incorrect."
31
+ )
32
+
33
+ with torch.no_grad():
34
+ # Values are generated by using a truncated uniform distribution and
35
+ # then using the inverse CDF for the normal distribution.
36
+ # Get upper and lower cdf values
37
+ l = norm_cdf((a - mean) / std)
38
+ u = norm_cdf((b - mean) / std)
39
+
40
+ # Uniformly fill tensor with values from [l, u], then translate to
41
+ # [2l-1, 2u-1].
42
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
43
+
44
+ # Use inverse cdf transform for normal distribution to get truncated
45
+ # standard normal
46
+ tensor.erfinv_()
47
+
48
+ # Transform to proper mean, std
49
+ tensor.mul_(std * math.sqrt(2.0))
50
+ tensor.add_(mean)
51
+
52
+ # Clamp to ensure it's in the proper range
53
+ tensor.clamp_(min=a, max=b)
54
+ return tensor
55
+
56
+
57
+ def trunc_normal_(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0):
58
+ # type: (torch.Tensor, float, float, float, float) -> torch.Tensor
59
+ r"""Fills the input Tensor with values drawn from a truncated
60
+ normal distribution. The values are effectively drawn from the normal distribution :math:`\mathcal{N}(\text{mean},
61
+ \text{std}^2)` with values outside :math:`[a, b]` redrawn until they are within the bounds. The method used for
62
+ generating the random values works best when :math:`a \leq \text{mean} \leq b`.
63
+
64
+ Args:
65
+ tensor: an n-dimensional `torch.Tensor`
66
+ mean: the mean of the normal distribution
67
+ std: the standard deviation of the normal distribution
68
+ a: the minimum cutoff value
69
+ b: the maximum cutoff value
70
+ Examples:
71
+ >>> w = torch.empty(3, 5) >>> nn.init.trunc_normal_(w)
72
+ """
73
+ return _no_grad_trunc_normal_(tensor, mean, std, a, b)
74
+
75
+
76
+ class PatchEmbed(nn.Module):
77
+ """2D Image to Patch Embedding"""
78
+
79
+ def __init__(
80
+ self,
81
+ height=224,
82
+ width=224,
83
+ patch_size=16,
84
+ in_channels=3,
85
+ embed_dim=768,
86
+ layer_norm=False,
87
+ flatten=True,
88
+ bias=True,
89
+ use_pos_embed=True,
90
+ ):
91
+ super().__init__()
92
+
93
+ num_patches = (height // patch_size) * (width // patch_size)
94
+ self.flatten = flatten
95
+ self.layer_norm = layer_norm
96
+
97
+ self.proj = nn.Conv2d(
98
+ in_channels, embed_dim, kernel_size=(patch_size, patch_size), stride=patch_size, bias=bias
99
+ )
100
+ if layer_norm:
101
+ self.norm = nn.LayerNorm(embed_dim, elementwise_affine=False, eps=1e-6)
102
+ else:
103
+ self.norm = None
104
+
105
+ self.use_pos_embed = use_pos_embed
106
+ if self.use_pos_embed:
107
+ pos_embed = get_2d_sincos_pos_embed(embed_dim, int(num_patches**0.5), output_type="pt")
108
+ self.register_buffer("pos_embed", pos_embed.float().unsqueeze(0), persistent=False)
109
+
110
+ def forward(self, latent):
111
+ latent = self.proj(latent)
112
+ if self.flatten:
113
+ latent = latent.flatten(2).transpose(1, 2) # BCHW -> BNC
114
+ if self.layer_norm:
115
+ latent = self.norm(latent)
116
+ if self.use_pos_embed:
117
+ return latent + self.pos_embed
118
+ else:
119
+ return latent
120
+
121
+
122
+ class SkipBlock(nn.Module):
123
+ def __init__(self, dim: int):
124
+ super().__init__()
125
+
126
+ self.skip_linear = nn.Linear(2 * dim, dim)
127
+
128
+ # Use torch.nn.LayerNorm for now, following the original code
129
+ self.norm = nn.LayerNorm(dim)
130
+
131
+ def forward(self, x, skip):
132
+ x = self.skip_linear(torch.cat([x, skip], dim=-1))
133
+ x = self.norm(x)
134
+
135
+ return x
136
+
137
+
138
+ # Modified to support both pre-LayerNorm and post-LayerNorm configurations
139
+ # Don't support AdaLayerNormZero for now
140
+ # Modified from diffusers.models.attention.BasicTransformerBlock
141
+ class UTransformerBlock(nn.Module):
142
+ r"""
143
+ A modification of BasicTransformerBlock which supports pre-LayerNorm and post-LayerNorm configurations.
144
+
145
+ Parameters:
146
+ dim (`int`): The number of channels in the input and output.
147
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
148
+ attention_head_dim (`int`): The number of channels in each head.
149
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
150
+ cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
151
+ activation_fn (`str`, *optional*, defaults to `"geglu"`):
152
+ Activation function to be used in feed-forward.
153
+ num_embeds_ada_norm (:obj: `int`, *optional*):
154
+ The number of diffusion steps used during training. See `Transformer2DModel`.
155
+ attention_bias (:obj: `bool`, *optional*, defaults to `False`):
156
+ Configure if the attentions should contain a bias parameter.
157
+ only_cross_attention (`bool`, *optional*):
158
+ Whether to use only cross-attention layers. In this case two cross attention layers are used.
159
+ double_self_attention (`bool`, *optional*):
160
+ Whether to use two self-attention layers. In this case no cross attention layers are used.
161
+ upcast_attention (`bool`, *optional*):
162
+ Whether to upcast the query and key to float32 when performing the attention calculation.
163
+ norm_elementwise_affine (`bool`, *optional*):
164
+ Whether to use learnable per-element affine parameters during layer normalization.
165
+ norm_type (`str`, defaults to `"layer_norm"`):
166
+ The layer norm implementation to use.
167
+ pre_layer_norm (`bool`, *optional*):
168
+ Whether to perform layer normalization before the attention and feedforward operations ("pre-LayerNorm"),
169
+ as opposed to after ("post-LayerNorm"). Note that `BasicTransformerBlock` uses pre-LayerNorm, e.g.
170
+ `pre_layer_norm = True`.
171
+ final_dropout (`bool`, *optional*):
172
+ Whether to use a final Dropout layer after the feedforward network.
173
+ """
174
+
175
+ def __init__(
176
+ self,
177
+ dim: int,
178
+ num_attention_heads: int,
179
+ attention_head_dim: int,
180
+ dropout=0.0,
181
+ cross_attention_dim: Optional[int] = None,
182
+ activation_fn: str = "geglu",
183
+ num_embeds_ada_norm: Optional[int] = None,
184
+ attention_bias: bool = False,
185
+ only_cross_attention: bool = False,
186
+ double_self_attention: bool = False,
187
+ upcast_attention: bool = False,
188
+ norm_elementwise_affine: bool = True,
189
+ norm_type: str = "layer_norm",
190
+ pre_layer_norm: bool = True,
191
+ final_dropout: bool = False,
192
+ ):
193
+ super().__init__()
194
+ self.only_cross_attention = only_cross_attention
195
+
196
+ self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
197
+
198
+ self.pre_layer_norm = pre_layer_norm
199
+
200
+ if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
201
+ raise ValueError(
202
+ f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
203
+ f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
204
+ )
205
+
206
+ # 1. Self-Attn
207
+ self.attn1 = Attention(
208
+ query_dim=dim,
209
+ heads=num_attention_heads,
210
+ dim_head=attention_head_dim,
211
+ dropout=dropout,
212
+ bias=attention_bias,
213
+ cross_attention_dim=cross_attention_dim if only_cross_attention else None,
214
+ upcast_attention=upcast_attention,
215
+ )
216
+
217
+ # 2. Cross-Attn
218
+ if cross_attention_dim is not None or double_self_attention:
219
+ self.attn2 = Attention(
220
+ query_dim=dim,
221
+ cross_attention_dim=cross_attention_dim if not double_self_attention else None,
222
+ heads=num_attention_heads,
223
+ dim_head=attention_head_dim,
224
+ dropout=dropout,
225
+ bias=attention_bias,
226
+ upcast_attention=upcast_attention,
227
+ ) # is self-attn if encoder_hidden_states is none
228
+ else:
229
+ self.attn2 = None
230
+
231
+ if self.use_ada_layer_norm:
232
+ self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
233
+ else:
234
+ self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
235
+
236
+ if cross_attention_dim is not None or double_self_attention:
237
+ # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
238
+ # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
239
+ # the second cross attention block.
240
+ self.norm2 = (
241
+ AdaLayerNorm(dim, num_embeds_ada_norm)
242
+ if self.use_ada_layer_norm
243
+ else nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
244
+ )
245
+ else:
246
+ self.norm2 = None
247
+
248
+ # 3. Feed-forward
249
+ self.norm3 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
250
+ self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn, final_dropout=final_dropout)
251
+
252
+ def forward(
253
+ self,
254
+ hidden_states,
255
+ attention_mask=None,
256
+ encoder_hidden_states=None,
257
+ encoder_attention_mask=None,
258
+ timestep=None,
259
+ cross_attention_kwargs=None,
260
+ class_labels=None,
261
+ ):
262
+ # Pre-LayerNorm
263
+ if self.pre_layer_norm:
264
+ if self.use_ada_layer_norm:
265
+ norm_hidden_states = self.norm1(hidden_states, timestep)
266
+ else:
267
+ norm_hidden_states = self.norm1(hidden_states)
268
+ else:
269
+ norm_hidden_states = hidden_states
270
+
271
+ # 1. Self-Attention
272
+ cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
273
+ attn_output = self.attn1(
274
+ norm_hidden_states,
275
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
276
+ attention_mask=attention_mask,
277
+ **cross_attention_kwargs,
278
+ )
279
+
280
+ # Post-LayerNorm
281
+ if not self.pre_layer_norm:
282
+ if self.use_ada_layer_norm:
283
+ attn_output = self.norm1(attn_output, timestep)
284
+ else:
285
+ attn_output = self.norm1(attn_output)
286
+
287
+ hidden_states = attn_output + hidden_states
288
+
289
+ if self.attn2 is not None:
290
+ # Pre-LayerNorm
291
+ if self.pre_layer_norm:
292
+ norm_hidden_states = (
293
+ self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)
294
+ )
295
+ else:
296
+ norm_hidden_states = hidden_states
297
+ # TODO (Birch-San): Here we should prepare the encoder_attention mask correctly
298
+ # prepare attention mask here
299
+
300
+ # 2. Cross-Attention
301
+ attn_output = self.attn2(
302
+ norm_hidden_states,
303
+ encoder_hidden_states=encoder_hidden_states,
304
+ attention_mask=encoder_attention_mask,
305
+ **cross_attention_kwargs,
306
+ )
307
+
308
+ # Post-LayerNorm
309
+ if not self.pre_layer_norm:
310
+ attn_output = self.norm2(attn_output, timestep) if self.use_ada_layer_norm else self.norm2(attn_output)
311
+
312
+ hidden_states = attn_output + hidden_states
313
+
314
+ # 3. Feed-forward
315
+ # Pre-LayerNorm
316
+ if self.pre_layer_norm:
317
+ norm_hidden_states = self.norm3(hidden_states)
318
+ else:
319
+ norm_hidden_states = hidden_states
320
+
321
+ ff_output = self.ff(norm_hidden_states)
322
+
323
+ # Post-LayerNorm
324
+ if not self.pre_layer_norm:
325
+ ff_output = self.norm3(ff_output)
326
+
327
+ hidden_states = ff_output + hidden_states
328
+
329
+ return hidden_states
330
+
331
+
332
+ # Like UTransformerBlock except with LayerNorms on the residual backbone of the block
333
+ # Modified from diffusers.models.attention.BasicTransformerBlock
334
+ class UniDiffuserBlock(nn.Module):
335
+ r"""
336
+ A modification of BasicTransformerBlock which supports pre-LayerNorm and post-LayerNorm configurations and puts the
337
+ LayerNorms on the residual backbone of the block. This matches the transformer block in the [original UniDiffuser
338
+ implementation](https://github.com/thu-ml/unidiffuser/blob/main/libs/uvit_multi_post_ln_v1.py#L104).
339
+
340
+ Parameters:
341
+ dim (`int`): The number of channels in the input and output.
342
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
343
+ attention_head_dim (`int`): The number of channels in each head.
344
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
345
+ cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
346
+ activation_fn (`str`, *optional*, defaults to `"geglu"`):
347
+ Activation function to be used in feed-forward.
348
+ num_embeds_ada_norm (:obj: `int`, *optional*):
349
+ The number of diffusion steps used during training. See `Transformer2DModel`.
350
+ attention_bias (:obj: `bool`, *optional*, defaults to `False`):
351
+ Configure if the attentions should contain a bias parameter.
352
+ only_cross_attention (`bool`, *optional*):
353
+ Whether to use only cross-attention layers. In this case two cross attention layers are used.
354
+ double_self_attention (`bool`, *optional*):
355
+ Whether to use two self-attention layers. In this case no cross attention layers are used.
356
+ upcast_attention (`bool`, *optional*):
357
+ Whether to upcast the query and key to float() when performing the attention calculation.
358
+ norm_elementwise_affine (`bool`, *optional*):
359
+ Whether to use learnable per-element affine parameters during layer normalization.
360
+ norm_type (`str`, defaults to `"layer_norm"`):
361
+ The layer norm implementation to use.
362
+ pre_layer_norm (`bool`, *optional*):
363
+ Whether to perform layer normalization before the attention and feedforward operations ("pre-LayerNorm"),
364
+ as opposed to after ("post-LayerNorm"). The original UniDiffuser implementation is post-LayerNorm
365
+ (`pre_layer_norm = False`).
366
+ final_dropout (`bool`, *optional*):
367
+ Whether to use a final Dropout layer after the feedforward network.
368
+ """
369
+
370
+ def __init__(
371
+ self,
372
+ dim: int,
373
+ num_attention_heads: int,
374
+ attention_head_dim: int,
375
+ dropout=0.0,
376
+ cross_attention_dim: Optional[int] = None,
377
+ activation_fn: str = "geglu",
378
+ num_embeds_ada_norm: Optional[int] = None,
379
+ attention_bias: bool = False,
380
+ only_cross_attention: bool = False,
381
+ double_self_attention: bool = False,
382
+ upcast_attention: bool = False,
383
+ norm_elementwise_affine: bool = True,
384
+ norm_type: str = "layer_norm",
385
+ pre_layer_norm: bool = False,
386
+ final_dropout: bool = True,
387
+ ):
388
+ super().__init__()
389
+ self.only_cross_attention = only_cross_attention
390
+
391
+ self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
392
+
393
+ self.pre_layer_norm = pre_layer_norm
394
+
395
+ if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
396
+ raise ValueError(
397
+ f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
398
+ f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
399
+ )
400
+
401
+ # 1. Self-Attn
402
+ self.attn1 = Attention(
403
+ query_dim=dim,
404
+ heads=num_attention_heads,
405
+ dim_head=attention_head_dim,
406
+ dropout=dropout,
407
+ bias=attention_bias,
408
+ cross_attention_dim=cross_attention_dim if only_cross_attention else None,
409
+ upcast_attention=upcast_attention,
410
+ )
411
+
412
+ # 2. Cross-Attn
413
+ if cross_attention_dim is not None or double_self_attention:
414
+ self.attn2 = Attention(
415
+ query_dim=dim,
416
+ cross_attention_dim=cross_attention_dim if not double_self_attention else None,
417
+ heads=num_attention_heads,
418
+ dim_head=attention_head_dim,
419
+ dropout=dropout,
420
+ bias=attention_bias,
421
+ upcast_attention=upcast_attention,
422
+ ) # is self-attn if encoder_hidden_states is none
423
+ else:
424
+ self.attn2 = None
425
+
426
+ if self.use_ada_layer_norm:
427
+ self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
428
+ else:
429
+ self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
430
+
431
+ if cross_attention_dim is not None or double_self_attention:
432
+ # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
433
+ # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
434
+ # the second cross attention block.
435
+ self.norm2 = (
436
+ AdaLayerNorm(dim, num_embeds_ada_norm)
437
+ if self.use_ada_layer_norm
438
+ else nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
439
+ )
440
+ else:
441
+ self.norm2 = None
442
+
443
+ # 3. Feed-forward
444
+ self.norm3 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
445
+ self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn, final_dropout=final_dropout)
446
+
447
+ def forward(
448
+ self,
449
+ hidden_states,
450
+ attention_mask=None,
451
+ encoder_hidden_states=None,
452
+ encoder_attention_mask=None,
453
+ timestep=None,
454
+ cross_attention_kwargs=None,
455
+ class_labels=None,
456
+ ):
457
+ # Following the diffusers transformer block implementation, put the LayerNorm on the
458
+ # residual backbone
459
+ # Pre-LayerNorm
460
+ if self.pre_layer_norm:
461
+ if self.use_ada_layer_norm:
462
+ hidden_states = self.norm1(hidden_states, timestep)
463
+ else:
464
+ hidden_states = self.norm1(hidden_states)
465
+
466
+ # 1. Self-Attention
467
+ cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
468
+ attn_output = self.attn1(
469
+ hidden_states,
470
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
471
+ attention_mask=attention_mask,
472
+ **cross_attention_kwargs,
473
+ )
474
+
475
+ hidden_states = attn_output + hidden_states
476
+
477
+ # Following the diffusers transformer block implementation, put the LayerNorm on the
478
+ # residual backbone
479
+ # Post-LayerNorm
480
+ if not self.pre_layer_norm:
481
+ if self.use_ada_layer_norm:
482
+ hidden_states = self.norm1(hidden_states, timestep)
483
+ else:
484
+ hidden_states = self.norm1(hidden_states)
485
+
486
+ if self.attn2 is not None:
487
+ # Pre-LayerNorm
488
+ if self.pre_layer_norm:
489
+ hidden_states = (
490
+ self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)
491
+ )
492
+ # TODO (Birch-San): Here we should prepare the encoder_attention mask correctly
493
+ # prepare attention mask here
494
+
495
+ # 2. Cross-Attention
496
+ attn_output = self.attn2(
497
+ hidden_states,
498
+ encoder_hidden_states=encoder_hidden_states,
499
+ attention_mask=encoder_attention_mask,
500
+ **cross_attention_kwargs,
501
+ )
502
+
503
+ hidden_states = attn_output + hidden_states
504
+
505
+ # Post-LayerNorm
506
+ if not self.pre_layer_norm:
507
+ hidden_states = (
508
+ self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)
509
+ )
510
+
511
+ # 3. Feed-forward
512
+ # Pre-LayerNorm
513
+ if self.pre_layer_norm:
514
+ hidden_states = self.norm3(hidden_states)
515
+
516
+ ff_output = self.ff(hidden_states)
517
+
518
+ hidden_states = ff_output + hidden_states
519
+
520
+ # Post-LayerNorm
521
+ if not self.pre_layer_norm:
522
+ hidden_states = self.norm3(hidden_states)
523
+
524
+ return hidden_states
525
+
526
+
527
+ # Modified from diffusers.models.transformer_2d.Transformer2DModel
528
+ # Modify the transformer block structure to be U-Net like following U-ViT
529
+ # Only supports patch-style input and torch.nn.LayerNorm currently
530
+ # https://github.com/baofff/U-ViT
531
+ class UTransformer2DModel(ModelMixin, ConfigMixin):
532
+ """
533
+ Transformer model based on the [U-ViT](https://github.com/baofff/U-ViT) architecture for image-like data. Compared
534
+ to [`Transformer2DModel`], this model has skip connections between transformer blocks in a "U"-shaped fashion,
535
+ similar to a U-Net. Supports only continuous (actual embeddings) inputs, which are embedded via a [`PatchEmbed`]
536
+ layer and then reshaped to (b, t, d).
537
+
538
+ Parameters:
539
+ num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
540
+ attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
541
+ in_channels (`int`, *optional*):
542
+ Pass if the input is continuous. The number of channels in the input.
543
+ out_channels (`int`, *optional*):
544
+ The number of output channels; if `None`, defaults to `in_channels`.
545
+ num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
546
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
547
+ norm_num_groups (`int`, *optional*, defaults to `32`):
548
+ The number of groups to use when performing Group Normalization.
549
+ cross_attention_dim (`int`, *optional*): The number of encoder_hidden_states dimensions to use.
550
+ attention_bias (`bool`, *optional*):
551
+ Configure if the TransformerBlocks' attention should contain a bias parameter.
552
+ sample_size (`int`, *optional*): Pass if the input is discrete. The width of the latent images.
553
+ Note that this is fixed at training time as it is used for learning a number of position embeddings. See
554
+ `ImagePositionalEmbeddings`.
555
+ num_vector_embeds (`int`, *optional*):
556
+ Pass if the input is discrete. The number of classes of the vector embeddings of the latent pixels.
557
+ Includes the class for the masked latent pixel.
558
+ patch_size (`int`, *optional*, defaults to 2):
559
+ The patch size to use in the patch embedding.
560
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
561
+ num_embeds_ada_norm ( `int`, *optional*): Pass if at least one of the norm_layers is `AdaLayerNorm`.
562
+ The number of diffusion steps used during training. Note that this is fixed at training time as it is used
563
+ to learn a number of embeddings that are added to the hidden states. During inference, you can denoise for
564
+ up to but not more than steps than `num_embeds_ada_norm`.
565
+ use_linear_projection (int, *optional*): TODO: Not used
566
+ only_cross_attention (`bool`, *optional*):
567
+ Whether to use only cross-attention layers. In this case two cross attention layers are used in each
568
+ transformer block.
569
+ upcast_attention (`bool`, *optional*):
570
+ Whether to upcast the query and key to float() when performing the attention calculation.
571
+ norm_type (`str`, *optional*, defaults to `"layer_norm"`):
572
+ The Layer Normalization implementation to use. Defaults to `torch.nn.LayerNorm`.
573
+ block_type (`str`, *optional*, defaults to `"unidiffuser"`):
574
+ The transformer block implementation to use. If `"unidiffuser"`, has the LayerNorms on the residual
575
+ backbone of each transformer block; otherwise has them in the attention/feedforward branches (the standard
576
+ behavior in `diffusers`.)
577
+ pre_layer_norm (`bool`, *optional*):
578
+ Whether to perform layer normalization before the attention and feedforward operations ("pre-LayerNorm"),
579
+ as opposed to after ("post-LayerNorm"). The original UniDiffuser implementation is post-LayerNorm
580
+ (`pre_layer_norm = False`).
581
+ norm_elementwise_affine (`bool`, *optional*):
582
+ Whether to use learnable per-element affine parameters during layer normalization.
583
+ use_patch_pos_embed (`bool`, *optional*):
584
+ Whether to use position embeddings inside the patch embedding layer (`PatchEmbed`).
585
+ final_dropout (`bool`, *optional*):
586
+ Whether to use a final Dropout layer after the feedforward network.
587
+ """
588
+
589
+ @register_to_config
590
+ def __init__(
591
+ self,
592
+ num_attention_heads: int = 16,
593
+ attention_head_dim: int = 88,
594
+ in_channels: Optional[int] = None,
595
+ out_channels: Optional[int] = None,
596
+ num_layers: int = 1,
597
+ dropout: float = 0.0,
598
+ norm_num_groups: int = 32,
599
+ cross_attention_dim: Optional[int] = None,
600
+ attention_bias: bool = False,
601
+ sample_size: Optional[int] = None,
602
+ num_vector_embeds: Optional[int] = None,
603
+ patch_size: Optional[int] = 2,
604
+ activation_fn: str = "geglu",
605
+ num_embeds_ada_norm: Optional[int] = None,
606
+ use_linear_projection: bool = False,
607
+ only_cross_attention: bool = False,
608
+ upcast_attention: bool = False,
609
+ norm_type: str = "layer_norm",
610
+ block_type: str = "unidiffuser",
611
+ pre_layer_norm: bool = False,
612
+ norm_elementwise_affine: bool = True,
613
+ use_patch_pos_embed=False,
614
+ ff_final_dropout: bool = False,
615
+ ):
616
+ super().__init__()
617
+ self.use_linear_projection = use_linear_projection
618
+ self.num_attention_heads = num_attention_heads
619
+ self.attention_head_dim = attention_head_dim
620
+ inner_dim = num_attention_heads * attention_head_dim
621
+
622
+ # 1. Input
623
+ # Only support patch input of shape (batch_size, num_channels, height, width) for now
624
+ assert in_channels is not None and patch_size is not None, "Patch input requires in_channels and patch_size."
625
+
626
+ assert sample_size is not None, "UTransformer2DModel over patched input must provide sample_size"
627
+
628
+ # 2. Define input layers
629
+ self.height = sample_size
630
+ self.width = sample_size
631
+
632
+ self.patch_size = patch_size
633
+ self.pos_embed = PatchEmbed(
634
+ height=sample_size,
635
+ width=sample_size,
636
+ patch_size=patch_size,
637
+ in_channels=in_channels,
638
+ embed_dim=inner_dim,
639
+ use_pos_embed=use_patch_pos_embed,
640
+ )
641
+
642
+ # 3. Define transformers blocks
643
+ # Modify this to have in_blocks ("downsample" blocks, even though we don't actually downsample), a mid_block,
644
+ # and out_blocks ("upsample" blocks). Like a U-Net, there are skip connections from in_blocks to out_blocks in
645
+ # a "U"-shaped fashion (e.g. first in_block to last out_block, etc.).
646
+ # Quick hack to make the transformer block type configurable
647
+ if block_type == "unidiffuser":
648
+ block_cls = UniDiffuserBlock
649
+ else:
650
+ block_cls = UTransformerBlock
651
+ self.transformer_in_blocks = nn.ModuleList(
652
+ [
653
+ block_cls(
654
+ inner_dim,
655
+ num_attention_heads,
656
+ attention_head_dim,
657
+ dropout=dropout,
658
+ cross_attention_dim=cross_attention_dim,
659
+ activation_fn=activation_fn,
660
+ num_embeds_ada_norm=num_embeds_ada_norm,
661
+ attention_bias=attention_bias,
662
+ only_cross_attention=only_cross_attention,
663
+ upcast_attention=upcast_attention,
664
+ norm_type=norm_type,
665
+ pre_layer_norm=pre_layer_norm,
666
+ norm_elementwise_affine=norm_elementwise_affine,
667
+ final_dropout=ff_final_dropout,
668
+ )
669
+ for d in range(num_layers // 2)
670
+ ]
671
+ )
672
+
673
+ self.transformer_mid_block = block_cls(
674
+ inner_dim,
675
+ num_attention_heads,
676
+ attention_head_dim,
677
+ dropout=dropout,
678
+ cross_attention_dim=cross_attention_dim,
679
+ activation_fn=activation_fn,
680
+ num_embeds_ada_norm=num_embeds_ada_norm,
681
+ attention_bias=attention_bias,
682
+ only_cross_attention=only_cross_attention,
683
+ upcast_attention=upcast_attention,
684
+ norm_type=norm_type,
685
+ pre_layer_norm=pre_layer_norm,
686
+ norm_elementwise_affine=norm_elementwise_affine,
687
+ final_dropout=ff_final_dropout,
688
+ )
689
+
690
+ # For each skip connection, we use a SkipBlock (concatenation + Linear + LayerNorm) to process the inputs
691
+ # before each transformer out_block.
692
+ self.transformer_out_blocks = nn.ModuleList(
693
+ [
694
+ nn.ModuleDict(
695
+ {
696
+ "skip": SkipBlock(
697
+ inner_dim,
698
+ ),
699
+ "block": block_cls(
700
+ inner_dim,
701
+ num_attention_heads,
702
+ attention_head_dim,
703
+ dropout=dropout,
704
+ cross_attention_dim=cross_attention_dim,
705
+ activation_fn=activation_fn,
706
+ num_embeds_ada_norm=num_embeds_ada_norm,
707
+ attention_bias=attention_bias,
708
+ only_cross_attention=only_cross_attention,
709
+ upcast_attention=upcast_attention,
710
+ norm_type=norm_type,
711
+ pre_layer_norm=pre_layer_norm,
712
+ norm_elementwise_affine=norm_elementwise_affine,
713
+ final_dropout=ff_final_dropout,
714
+ ),
715
+ }
716
+ )
717
+ for d in range(num_layers // 2)
718
+ ]
719
+ )
720
+
721
+ # 4. Define output layers
722
+ self.out_channels = in_channels if out_channels is None else out_channels
723
+
724
+ # Following the UniDiffuser U-ViT implementation, we process the transformer output with
725
+ # a LayerNorm layer with per-element affine params
726
+ self.norm_out = nn.LayerNorm(inner_dim)
727
+
728
+ def forward(
729
+ self,
730
+ hidden_states,
731
+ encoder_hidden_states=None,
732
+ timestep=None,
733
+ class_labels=None,
734
+ cross_attention_kwargs=None,
735
+ return_dict: bool = True,
736
+ hidden_states_is_embedding: bool = False,
737
+ unpatchify: bool = True,
738
+ ):
739
+ """
740
+ Args:
741
+ hidden_states ( When discrete, `torch.LongTensor` of shape `(batch size, num latent pixels)`.
742
+ When continuous, `torch.Tensor` of shape `(batch size, channel, height, width)`): Input hidden_states
743
+ encoder_hidden_states ( `torch.LongTensor` of shape `(batch size, encoder_hidden_states dim)`, *optional*):
744
+ Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
745
+ self-attention.
746
+ timestep ( `torch.long`, *optional*):
747
+ Optional timestep to be applied as an embedding in AdaLayerNorm's. Used to indicate denoising step.
748
+ class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
749
+ Optional class labels to be applied as an embedding in AdaLayerZeroNorm. Used to indicate class labels
750
+ conditioning.
751
+ cross_attention_kwargs (*optional*):
752
+ Keyword arguments to supply to the cross attention layers, if used.
753
+ return_dict (`bool`, *optional*, defaults to `True`):
754
+ Whether or not to return a [`models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
755
+ tuple.
756
+ hidden_states_is_embedding (`bool`, *optional*, defaults to `False`):
757
+ Whether or not hidden_states is an embedding directly usable by the transformer. In this case we will
758
+ ignore input handling (e.g. continuous, vectorized, etc.) and directly feed hidden_states into the
759
+ transformer blocks.
760
+ unpatchify (`bool`, *optional*, defaults to `True`):
761
+ Whether to unpatchify the transformer output.
762
+
763
+ Returns:
764
+ [`~models.transformer_2d.Transformer2DModelOutput`] or `tuple`:
765
+ [`~models.transformer_2d.Transformer2DModelOutput`] if `return_dict` is True, otherwise a `tuple`. When
766
+ returning a tuple, the first element is the sample tensor.
767
+ """
768
+ # 0. Check inputs
769
+
770
+ if not unpatchify and return_dict:
771
+ raise ValueError(
772
+ f"Cannot both define `unpatchify`: {unpatchify} and `return_dict`: {return_dict} since when"
773
+ f" `unpatchify` is {unpatchify} the returned output is of shape (batch_size, seq_len, hidden_dim)"
774
+ " rather than (batch_size, num_channels, height, width)."
775
+ )
776
+
777
+ # 1. Input
778
+ if not hidden_states_is_embedding:
779
+ hidden_states = self.pos_embed(hidden_states)
780
+
781
+ # 2. Blocks
782
+
783
+ # In ("downsample") blocks
784
+ skips = []
785
+ for in_block in self.transformer_in_blocks:
786
+ hidden_states = in_block(
787
+ hidden_states,
788
+ encoder_hidden_states=encoder_hidden_states,
789
+ timestep=timestep,
790
+ cross_attention_kwargs=cross_attention_kwargs,
791
+ class_labels=class_labels,
792
+ )
793
+ skips.append(hidden_states)
794
+
795
+ # Mid block
796
+ hidden_states = self.transformer_mid_block(hidden_states)
797
+
798
+ # Out ("upsample") blocks
799
+ for out_block in self.transformer_out_blocks:
800
+ hidden_states = out_block["skip"](hidden_states, skips.pop())
801
+ hidden_states = out_block["block"](
802
+ hidden_states,
803
+ encoder_hidden_states=encoder_hidden_states,
804
+ timestep=timestep,
805
+ cross_attention_kwargs=cross_attention_kwargs,
806
+ class_labels=class_labels,
807
+ )
808
+
809
+ # 3. Output
810
+ # Don't support AdaLayerNorm for now, so no conditioning/scale/shift logic
811
+ hidden_states = self.norm_out(hidden_states)
812
+ # hidden_states = self.proj_out(hidden_states)
813
+
814
+ if unpatchify:
815
+ # unpatchify
816
+ height = width = int(hidden_states.shape[1] ** 0.5)
817
+ hidden_states = hidden_states.reshape(
818
+ shape=(-1, height, width, self.patch_size, self.patch_size, self.out_channels)
819
+ )
820
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
821
+ output = hidden_states.reshape(
822
+ shape=(-1, self.out_channels, height * self.patch_size, width * self.patch_size)
823
+ )
824
+ else:
825
+ output = hidden_states
826
+
827
+ if not return_dict:
828
+ return (output,)
829
+
830
+ return Transformer2DModelOutput(sample=output)
831
+
832
+
833
+ class UniDiffuserModel(ModelMixin, ConfigMixin):
834
+ """
835
+ Transformer model for a image-text [UniDiffuser](https://huggingface.co/papers/2303.06555) model. This is a
836
+ modification of [`UTransformer2DModel`] with input and output heads for the VAE-embedded latent image, the
837
+ CLIP-embedded image, and the CLIP-embedded prompt (see paper for more details).
838
+
839
+ Parameters:
840
+ text_dim (`int`): The hidden dimension of the CLIP text model used to embed images.
841
+ clip_img_dim (`int`): The hidden dimension of the CLIP vision model used to embed prompts.
842
+ num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
843
+ attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
844
+ in_channels (`int`, *optional*):
845
+ Pass if the input is continuous. The number of channels in the input.
846
+ out_channels (`int`, *optional*):
847
+ The number of output channels; if `None`, defaults to `in_channels`.
848
+ num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
849
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
850
+ norm_num_groups (`int`, *optional*, defaults to `32`):
851
+ The number of groups to use when performing Group Normalization.
852
+ cross_attention_dim (`int`, *optional*): The number of encoder_hidden_states dimensions to use.
853
+ attention_bias (`bool`, *optional*):
854
+ Configure if the TransformerBlocks' attention should contain a bias parameter.
855
+ sample_size (`int`, *optional*): Pass if the input is discrete. The width of the latent images.
856
+ Note that this is fixed at training time as it is used for learning a number of position embeddings. See
857
+ `ImagePositionalEmbeddings`.
858
+ num_vector_embeds (`int`, *optional*):
859
+ Pass if the input is discrete. The number of classes of the vector embeddings of the latent pixels.
860
+ Includes the class for the masked latent pixel.
861
+ patch_size (`int`, *optional*, defaults to 2):
862
+ The patch size to use in the patch embedding.
863
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
864
+ num_embeds_ada_norm ( `int`, *optional*): Pass if at least one of the norm_layers is `AdaLayerNorm`.
865
+ The number of diffusion steps used during training. Note that this is fixed at training time as it is used
866
+ to learn a number of embeddings that are added to the hidden states. During inference, you can denoise for
867
+ up to but not more than steps than `num_embeds_ada_norm`.
868
+ use_linear_projection (int, *optional*): TODO: Not used
869
+ only_cross_attention (`bool`, *optional*):
870
+ Whether to use only cross-attention layers. In this case two cross attention layers are used in each
871
+ transformer block.
872
+ upcast_attention (`bool`, *optional*):
873
+ Whether to upcast the query and key to float32 when performing the attention calculation.
874
+ norm_type (`str`, *optional*, defaults to `"layer_norm"`):
875
+ The Layer Normalization implementation to use. Defaults to `torch.nn.LayerNorm`.
876
+ block_type (`str`, *optional*, defaults to `"unidiffuser"`):
877
+ The transformer block implementation to use. If `"unidiffuser"`, has the LayerNorms on the residual
878
+ backbone of each transformer block; otherwise has them in the attention/feedforward branches (the standard
879
+ behavior in `diffusers`.)
880
+ pre_layer_norm (`bool`, *optional*):
881
+ Whether to perform layer normalization before the attention and feedforward operations ("pre-LayerNorm"),
882
+ as opposed to after ("post-LayerNorm"). The original UniDiffuser implementation is post-LayerNorm
883
+ (`pre_layer_norm = False`).
884
+ norm_elementwise_affine (`bool`, *optional*):
885
+ Whether to use learnable per-element affine parameters during layer normalization.
886
+ use_patch_pos_embed (`bool`, *optional*):
887
+ Whether to use position embeddings inside the patch embedding layer (`PatchEmbed`).
888
+ ff_final_dropout (`bool`, *optional*):
889
+ Whether to use a final Dropout layer after the feedforward network.
890
+ use_data_type_embedding (`bool`, *optional*):
891
+ Whether to use a data type embedding. This is only relevant for UniDiffuser-v1 style models; UniDiffuser-v1
892
+ is continue-trained from UniDiffuser-v0 on non-publically-available data and accepts a `data_type`
893
+ argument, which can either be `1` to use the weights trained on non-publically-available data or `0`
894
+ otherwise. This argument is subsequently embedded by the data type embedding, if used.
895
+ """
896
+
897
+ @register_to_config
898
+ def __init__(
899
+ self,
900
+ text_dim: int = 768,
901
+ clip_img_dim: int = 512,
902
+ num_text_tokens: int = 77,
903
+ num_attention_heads: int = 16,
904
+ attention_head_dim: int = 88,
905
+ in_channels: Optional[int] = None,
906
+ out_channels: Optional[int] = None,
907
+ num_layers: int = 1,
908
+ dropout: float = 0.0,
909
+ norm_num_groups: int = 32,
910
+ cross_attention_dim: Optional[int] = None,
911
+ attention_bias: bool = False,
912
+ sample_size: Optional[int] = None,
913
+ num_vector_embeds: Optional[int] = None,
914
+ patch_size: Optional[int] = None,
915
+ activation_fn: str = "geglu",
916
+ num_embeds_ada_norm: Optional[int] = None,
917
+ use_linear_projection: bool = False,
918
+ only_cross_attention: bool = False,
919
+ upcast_attention: bool = False,
920
+ norm_type: str = "layer_norm",
921
+ block_type: str = "unidiffuser",
922
+ pre_layer_norm: bool = False,
923
+ use_timestep_embedding=False,
924
+ norm_elementwise_affine: bool = True,
925
+ use_patch_pos_embed=False,
926
+ ff_final_dropout: bool = True,
927
+ use_data_type_embedding: bool = False,
928
+ ):
929
+ super().__init__()
930
+
931
+ # 0. Handle dimensions
932
+ self.inner_dim = num_attention_heads * attention_head_dim
933
+
934
+ assert sample_size is not None, "UniDiffuserModel over patched input must provide sample_size"
935
+ self.sample_size = sample_size
936
+ self.in_channels = in_channels
937
+ self.out_channels = in_channels if out_channels is None else out_channels
938
+
939
+ self.patch_size = patch_size
940
+ # Assume image is square...
941
+ self.num_patches = (self.sample_size // patch_size) * (self.sample_size // patch_size)
942
+
943
+ # 1. Define input layers
944
+ # 1.1 Input layers for text and image input
945
+ # For now, only support patch input for VAE latent image input
946
+ self.vae_img_in = PatchEmbed(
947
+ height=sample_size,
948
+ width=sample_size,
949
+ patch_size=patch_size,
950
+ in_channels=in_channels,
951
+ embed_dim=self.inner_dim,
952
+ use_pos_embed=use_patch_pos_embed,
953
+ )
954
+ self.clip_img_in = nn.Linear(clip_img_dim, self.inner_dim)
955
+ self.text_in = nn.Linear(text_dim, self.inner_dim)
956
+
957
+ # 1.2. Timestep embeddings for t_img, t_text
958
+ self.timestep_img_proj = Timesteps(
959
+ self.inner_dim,
960
+ flip_sin_to_cos=True,
961
+ downscale_freq_shift=0,
962
+ )
963
+ self.timestep_img_embed = (
964
+ TimestepEmbedding(
965
+ self.inner_dim,
966
+ 4 * self.inner_dim,
967
+ out_dim=self.inner_dim,
968
+ )
969
+ if use_timestep_embedding
970
+ else nn.Identity()
971
+ )
972
+
973
+ self.timestep_text_proj = Timesteps(
974
+ self.inner_dim,
975
+ flip_sin_to_cos=True,
976
+ downscale_freq_shift=0,
977
+ )
978
+ self.timestep_text_embed = (
979
+ TimestepEmbedding(
980
+ self.inner_dim,
981
+ 4 * self.inner_dim,
982
+ out_dim=self.inner_dim,
983
+ )
984
+ if use_timestep_embedding
985
+ else nn.Identity()
986
+ )
987
+
988
+ # 1.3. Positional embedding
989
+ self.num_text_tokens = num_text_tokens
990
+ self.num_tokens = 1 + 1 + num_text_tokens + 1 + self.num_patches
991
+ self.pos_embed = nn.Parameter(torch.zeros(1, self.num_tokens, self.inner_dim))
992
+ self.pos_embed_drop = nn.Dropout(p=dropout)
993
+ trunc_normal_(self.pos_embed, std=0.02)
994
+
995
+ # 1.4. Handle data type token embeddings for UniDiffuser-V1, if necessary
996
+ self.use_data_type_embedding = use_data_type_embedding
997
+ if self.use_data_type_embedding:
998
+ self.data_type_token_embedding = nn.Embedding(2, self.inner_dim)
999
+ self.data_type_pos_embed_token = nn.Parameter(torch.zeros(1, 1, self.inner_dim))
1000
+
1001
+ # 2. Define transformer blocks
1002
+ self.transformer = UTransformer2DModel(
1003
+ num_attention_heads=num_attention_heads,
1004
+ attention_head_dim=attention_head_dim,
1005
+ in_channels=in_channels,
1006
+ out_channels=out_channels,
1007
+ num_layers=num_layers,
1008
+ dropout=dropout,
1009
+ norm_num_groups=norm_num_groups,
1010
+ cross_attention_dim=cross_attention_dim,
1011
+ attention_bias=attention_bias,
1012
+ sample_size=sample_size,
1013
+ num_vector_embeds=num_vector_embeds,
1014
+ patch_size=patch_size,
1015
+ activation_fn=activation_fn,
1016
+ num_embeds_ada_norm=num_embeds_ada_norm,
1017
+ use_linear_projection=use_linear_projection,
1018
+ only_cross_attention=only_cross_attention,
1019
+ upcast_attention=upcast_attention,
1020
+ norm_type=norm_type,
1021
+ block_type=block_type,
1022
+ pre_layer_norm=pre_layer_norm,
1023
+ norm_elementwise_affine=norm_elementwise_affine,
1024
+ use_patch_pos_embed=use_patch_pos_embed,
1025
+ ff_final_dropout=ff_final_dropout,
1026
+ )
1027
+
1028
+ # 3. Define output layers
1029
+ patch_dim = (patch_size**2) * out_channels
1030
+ self.vae_img_out = nn.Linear(self.inner_dim, patch_dim)
1031
+ self.clip_img_out = nn.Linear(self.inner_dim, clip_img_dim)
1032
+ self.text_out = nn.Linear(self.inner_dim, text_dim)
1033
+
1034
+ @torch.jit.ignore
1035
+ def no_weight_decay(self):
1036
+ return {"pos_embed"}
1037
+
1038
+ def forward(
1039
+ self,
1040
+ latent_image_embeds: torch.Tensor,
1041
+ image_embeds: torch.Tensor,
1042
+ prompt_embeds: torch.Tensor,
1043
+ timestep_img: Union[torch.Tensor, float, int],
1044
+ timestep_text: Union[torch.Tensor, float, int],
1045
+ data_type: Optional[Union[torch.Tensor, float, int]] = 1,
1046
+ encoder_hidden_states=None,
1047
+ cross_attention_kwargs=None,
1048
+ ):
1049
+ """
1050
+ Args:
1051
+ latent_image_embeds (`torch.Tensor` of shape `(batch size, latent channels, height, width)`):
1052
+ Latent image representation from the VAE encoder.
1053
+ image_embeds (`torch.Tensor` of shape `(batch size, 1, clip_img_dim)`):
1054
+ CLIP-embedded image representation (unsqueezed in the first dimension).
1055
+ prompt_embeds (`torch.Tensor` of shape `(batch size, seq_len, text_dim)`):
1056
+ CLIP-embedded text representation.
1057
+ timestep_img (`torch.long` or `float` or `int`):
1058
+ Current denoising step for the image.
1059
+ timestep_text (`torch.long` or `float` or `int`):
1060
+ Current denoising step for the text.
1061
+ data_type: (`torch.int` or `float` or `int`, *optional*, defaults to `1`):
1062
+ Only used in UniDiffuser-v1-style models. Can be either `1`, to use weights trained on nonpublic data,
1063
+ or `0` otherwise.
1064
+ encoder_hidden_states ( `torch.LongTensor` of shape `(batch size, encoder_hidden_states dim)`, *optional*):
1065
+ Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
1066
+ self-attention.
1067
+ cross_attention_kwargs (*optional*):
1068
+ Keyword arguments to supply to the cross attention layers, if used.
1069
+
1070
+
1071
+ Returns:
1072
+ `tuple`: Returns relevant parts of the model's noise prediction: the first element of the tuple is tbe VAE
1073
+ image embedding, the second element is the CLIP image embedding, and the third element is the CLIP text
1074
+ embedding.
1075
+ """
1076
+ batch_size = latent_image_embeds.shape[0]
1077
+
1078
+ # 1. Input
1079
+ # 1.1. Map inputs to shape (B, N, inner_dim)
1080
+ vae_hidden_states = self.vae_img_in(latent_image_embeds)
1081
+ clip_hidden_states = self.clip_img_in(image_embeds)
1082
+ text_hidden_states = self.text_in(prompt_embeds)
1083
+
1084
+ num_text_tokens, num_img_tokens = text_hidden_states.size(1), vae_hidden_states.size(1)
1085
+
1086
+ # 1.2. Encode image timesteps to single token (B, 1, inner_dim)
1087
+ if not torch.is_tensor(timestep_img):
1088
+ timestep_img = torch.tensor([timestep_img], dtype=torch.long, device=vae_hidden_states.device)
1089
+
1090
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
1091
+ timestep_img = timestep_img * torch.ones(batch_size, dtype=timestep_img.dtype, device=timestep_img.device)
1092
+
1093
+ timestep_img_token = self.timestep_img_proj(timestep_img)
1094
+ # t_img_token does not contain any weights and will always return f32 tensors
1095
+ # but time_embedding might be fp16, so we need to cast here.
1096
+ timestep_img_token = timestep_img_token.to(dtype=self.dtype)
1097
+ timestep_img_token = self.timestep_img_embed(timestep_img_token)
1098
+ timestep_img_token = timestep_img_token.unsqueeze(dim=1)
1099
+
1100
+ # 1.3. Encode text timesteps to single token (B, 1, inner_dim)
1101
+ if not torch.is_tensor(timestep_text):
1102
+ timestep_text = torch.tensor([timestep_text], dtype=torch.long, device=vae_hidden_states.device)
1103
+
1104
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
1105
+ timestep_text = timestep_text * torch.ones(batch_size, dtype=timestep_text.dtype, device=timestep_text.device)
1106
+
1107
+ timestep_text_token = self.timestep_text_proj(timestep_text)
1108
+ # t_text_token does not contain any weights and will always return f32 tensors
1109
+ # but time_embedding might be fp16, so we need to cast here.
1110
+ timestep_text_token = timestep_text_token.to(dtype=self.dtype)
1111
+ timestep_text_token = self.timestep_text_embed(timestep_text_token)
1112
+ timestep_text_token = timestep_text_token.unsqueeze(dim=1)
1113
+
1114
+ # 1.4. Concatenate all of the embeddings together.
1115
+ if self.use_data_type_embedding:
1116
+ assert data_type is not None, "data_type must be supplied if the model uses a data type embedding"
1117
+ if not torch.is_tensor(data_type):
1118
+ data_type = torch.tensor([data_type], dtype=torch.int, device=vae_hidden_states.device)
1119
+
1120
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
1121
+ data_type = data_type * torch.ones(batch_size, dtype=data_type.dtype, device=data_type.device)
1122
+
1123
+ data_type_token = self.data_type_token_embedding(data_type).unsqueeze(dim=1)
1124
+ hidden_states = torch.cat(
1125
+ [
1126
+ timestep_img_token,
1127
+ timestep_text_token,
1128
+ data_type_token,
1129
+ text_hidden_states,
1130
+ clip_hidden_states,
1131
+ vae_hidden_states,
1132
+ ],
1133
+ dim=1,
1134
+ )
1135
+ else:
1136
+ hidden_states = torch.cat(
1137
+ [timestep_img_token, timestep_text_token, text_hidden_states, clip_hidden_states, vae_hidden_states],
1138
+ dim=1,
1139
+ )
1140
+
1141
+ # 1.5. Prepare the positional embeddings and add to hidden states
1142
+ # Note: I think img_vae should always have the proper shape, so there's no need to interpolate
1143
+ # the position embeddings.
1144
+ if self.use_data_type_embedding:
1145
+ pos_embed = torch.cat(
1146
+ [self.pos_embed[:, : 1 + 1, :], self.data_type_pos_embed_token, self.pos_embed[:, 1 + 1 :, :]], dim=1
1147
+ )
1148
+ else:
1149
+ pos_embed = self.pos_embed
1150
+ hidden_states = hidden_states + pos_embed
1151
+ hidden_states = self.pos_embed_drop(hidden_states)
1152
+
1153
+ # 2. Blocks
1154
+ hidden_states = self.transformer(
1155
+ hidden_states,
1156
+ encoder_hidden_states=encoder_hidden_states,
1157
+ timestep=None,
1158
+ class_labels=None,
1159
+ cross_attention_kwargs=cross_attention_kwargs,
1160
+ return_dict=False,
1161
+ hidden_states_is_embedding=True,
1162
+ unpatchify=False,
1163
+ )[0]
1164
+
1165
+ # 3. Output
1166
+ # Split out the predicted noise representation.
1167
+ if self.use_data_type_embedding:
1168
+ (
1169
+ t_img_token_out,
1170
+ t_text_token_out,
1171
+ data_type_token_out,
1172
+ text_out,
1173
+ img_clip_out,
1174
+ img_vae_out,
1175
+ ) = hidden_states.split((1, 1, 1, num_text_tokens, 1, num_img_tokens), dim=1)
1176
+ else:
1177
+ t_img_token_out, t_text_token_out, text_out, img_clip_out, img_vae_out = hidden_states.split(
1178
+ (1, 1, num_text_tokens, 1, num_img_tokens), dim=1
1179
+ )
1180
+
1181
+ img_vae_out = self.vae_img_out(img_vae_out)
1182
+
1183
+ # unpatchify
1184
+ height = width = int(img_vae_out.shape[1] ** 0.5)
1185
+ img_vae_out = img_vae_out.reshape(
1186
+ shape=(-1, height, width, self.patch_size, self.patch_size, self.out_channels)
1187
+ )
1188
+ img_vae_out = torch.einsum("nhwpqc->nchpwq", img_vae_out)
1189
+ img_vae_out = img_vae_out.reshape(
1190
+ shape=(-1, self.out_channels, height * self.patch_size, width * self.patch_size)
1191
+ )
1192
+
1193
+ img_clip_out = self.clip_img_out(img_clip_out)
1194
+
1195
+ text_out = self.text_out(text_out)
1196
+
1197
+ return img_vae_out, img_clip_out, text_out
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py ADDED
@@ -0,0 +1,1462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from dataclasses import dataclass
3
+ from typing import Callable, List, Optional, Union
4
+
5
+ import numpy as np
6
+ import PIL.Image
7
+ import torch
8
+ from transformers import (
9
+ CLIPImageProcessor,
10
+ CLIPTextModel,
11
+ CLIPTokenizer,
12
+ CLIPVisionModelWithProjection,
13
+ GPT2Tokenizer,
14
+ )
15
+
16
+ from ...image_processor import VaeImageProcessor
17
+ from ...loaders import StableDiffusionLoraLoaderMixin, TextualInversionLoaderMixin
18
+ from ...models import AutoencoderKL
19
+ from ...models.lora import adjust_lora_scale_text_encoder
20
+ from ...schedulers import KarrasDiffusionSchedulers
21
+ from ...utils import (
22
+ USE_PEFT_BACKEND,
23
+ deprecate,
24
+ is_torch_xla_available,
25
+ logging,
26
+ scale_lora_layers,
27
+ unscale_lora_layers,
28
+ )
29
+ from ...utils.outputs import BaseOutput
30
+ from ...utils.torch_utils import randn_tensor
31
+ from ..pipeline_utils import DeprecatedPipelineMixin, DiffusionPipeline
32
+ from .modeling_text_decoder import UniDiffuserTextDecoder
33
+ from .modeling_uvit import UniDiffuserModel
34
+
35
+
36
+ if is_torch_xla_available():
37
+ import torch_xla.core.xla_model as xm
38
+
39
+ XLA_AVAILABLE = True
40
+ else:
41
+ XLA_AVAILABLE = False
42
+
43
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
44
+
45
+
46
+ # New BaseOutput child class for joint image-text output
47
+ @dataclass
48
+ class ImageTextPipelineOutput(BaseOutput):
49
+ """
50
+ Output class for joint image-text pipelines.
51
+
52
+ Args:
53
+ images (`List[PIL.Image.Image]` or `np.ndarray`)
54
+ List of denoised PIL images of length `batch_size` or NumPy array of shape `(batch_size, height, width,
55
+ num_channels)`.
56
+ text (`List[str]` or `List[List[str]]`)
57
+ List of generated text strings of length `batch_size` or a list of list of strings whose outer list has
58
+ length `batch_size`.
59
+ """
60
+
61
+ images: Optional[Union[List[PIL.Image.Image], np.ndarray]]
62
+ text: Optional[Union[List[str], List[List[str]]]]
63
+
64
+
65
+ class UniDiffuserPipeline(DeprecatedPipelineMixin, DiffusionPipeline):
66
+ r"""
67
+ Pipeline for a bimodal image-text model which supports unconditional text and image generation, text-conditioned
68
+ image generation, image-conditioned text generation, and joint image-text generation.
69
+
70
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
71
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
72
+
73
+ Args:
74
+ vae ([`AutoencoderKL`]):
75
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations. This
76
+ is part of the UniDiffuser image representation along with the CLIP vision encoding.
77
+ text_encoder ([`CLIPTextModel`]):
78
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
79
+ image_encoder ([`CLIPVisionModel`]):
80
+ A [`~transformers.CLIPVisionModel`] to encode images as part of its image representation along with the VAE
81
+ latent representation.
82
+ image_processor ([`CLIPImageProcessor`]):
83
+ [`~transformers.CLIPImageProcessor`] to preprocess an image before CLIP encoding it with `image_encoder`.
84
+ clip_tokenizer ([`CLIPTokenizer`]):
85
+ A [`~transformers.CLIPTokenizer`] to tokenize the prompt before encoding it with `text_encoder`.
86
+ text_decoder ([`UniDiffuserTextDecoder`]):
87
+ Frozen text decoder. This is a GPT-style model which is used to generate text from the UniDiffuser
88
+ embedding.
89
+ text_tokenizer ([`GPT2Tokenizer`]):
90
+ A [`~transformers.GPT2Tokenizer`] to decode text for text generation; used along with the `text_decoder`.
91
+ unet ([`UniDiffuserModel`]):
92
+ A [U-ViT](https://github.com/baofff/U-ViT) model with UNNet-style skip connections between transformer
93
+ layers to denoise the encoded image latents.
94
+ scheduler ([`SchedulerMixin`]):
95
+ A scheduler to be used in combination with `unet` to denoise the encoded image and/or text latents. The
96
+ original UniDiffuser paper uses the [`DPMSolverMultistepScheduler`] scheduler.
97
+ """
98
+
99
+ _last_supported_version = "0.33.1"
100
+ # TODO: support for moving submodules for components with enable_model_cpu_offload
101
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae->text_decoder"
102
+
103
+ def __init__(
104
+ self,
105
+ vae: AutoencoderKL,
106
+ text_encoder: CLIPTextModel,
107
+ image_encoder: CLIPVisionModelWithProjection,
108
+ clip_image_processor: CLIPImageProcessor,
109
+ clip_tokenizer: CLIPTokenizer,
110
+ text_decoder: UniDiffuserTextDecoder,
111
+ text_tokenizer: GPT2Tokenizer,
112
+ unet: UniDiffuserModel,
113
+ scheduler: KarrasDiffusionSchedulers,
114
+ ):
115
+ super().__init__()
116
+
117
+ if text_encoder.config.hidden_size != text_decoder.prefix_inner_dim:
118
+ raise ValueError(
119
+ f"The text encoder hidden size and text decoder prefix inner dim must be the same, but"
120
+ f" `text_encoder.config.hidden_size`: {text_encoder.config.hidden_size} and `text_decoder.prefix_inner_dim`: {text_decoder.prefix_inner_dim}"
121
+ )
122
+
123
+ self.register_modules(
124
+ vae=vae,
125
+ text_encoder=text_encoder,
126
+ image_encoder=image_encoder,
127
+ clip_image_processor=clip_image_processor,
128
+ clip_tokenizer=clip_tokenizer,
129
+ text_decoder=text_decoder,
130
+ text_tokenizer=text_tokenizer,
131
+ unet=unet,
132
+ scheduler=scheduler,
133
+ )
134
+
135
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
136
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
137
+
138
+ self.num_channels_latents = vae.config.latent_channels
139
+ self.text_encoder_seq_len = text_encoder.config.max_position_embeddings
140
+ self.text_encoder_hidden_size = text_encoder.config.hidden_size
141
+ self.image_encoder_projection_dim = image_encoder.config.projection_dim
142
+ self.unet_resolution = unet.config.sample_size
143
+
144
+ self.text_intermediate_dim = self.text_encoder_hidden_size
145
+ if self.text_decoder.prefix_hidden_dim is not None:
146
+ self.text_intermediate_dim = self.text_decoder.prefix_hidden_dim
147
+
148
+ self.mode = None
149
+
150
+ # TODO: handle safety checking?
151
+ self.safety_checker = None
152
+
153
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
154
+ def prepare_extra_step_kwargs(self, generator, eta):
155
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
156
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
157
+ # eta corresponds to η in DDIM paper: https://huggingface.co/papers/2010.02502
158
+ # and should be between [0, 1]
159
+
160
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
161
+ extra_step_kwargs = {}
162
+ if accepts_eta:
163
+ extra_step_kwargs["eta"] = eta
164
+
165
+ # check if the scheduler accepts generator
166
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
167
+ if accepts_generator:
168
+ extra_step_kwargs["generator"] = generator
169
+ return extra_step_kwargs
170
+
171
+ def _infer_mode(self, prompt, prompt_embeds, image, latents, prompt_latents, vae_latents, clip_latents):
172
+ r"""
173
+ Infer the generation task ('mode') from the inputs to `__call__`. If the mode has been manually set, the set
174
+ mode will be used.
175
+ """
176
+ prompt_available = (prompt is not None) or (prompt_embeds is not None)
177
+ image_available = image is not None
178
+ input_available = prompt_available or image_available
179
+
180
+ prompt_latents_available = prompt_latents is not None
181
+ vae_latents_available = vae_latents is not None
182
+ clip_latents_available = clip_latents is not None
183
+ full_latents_available = latents is not None
184
+ image_latents_available = vae_latents_available and clip_latents_available
185
+ all_indv_latents_available = prompt_latents_available and image_latents_available
186
+
187
+ if self.mode is not None:
188
+ # Preferentially use the mode set by the user
189
+ mode = self.mode
190
+ elif prompt_available:
191
+ mode = "text2img"
192
+ elif image_available:
193
+ mode = "img2text"
194
+ else:
195
+ # Neither prompt nor image supplied, infer based on availability of latents
196
+ if full_latents_available or all_indv_latents_available:
197
+ mode = "joint"
198
+ elif prompt_latents_available:
199
+ mode = "text"
200
+ elif image_latents_available:
201
+ mode = "img"
202
+ else:
203
+ # No inputs or latents available
204
+ mode = "joint"
205
+
206
+ # Give warnings for ambiguous cases
207
+ if self.mode is None and prompt_available and image_available:
208
+ logger.warning(
209
+ f"You have supplied both a text prompt and image to the pipeline and mode has not been set manually,"
210
+ f" defaulting to mode '{mode}'."
211
+ )
212
+
213
+ if self.mode is None and not input_available:
214
+ if vae_latents_available != clip_latents_available:
215
+ # Exactly one of vae_latents and clip_latents is supplied
216
+ logger.warning(
217
+ f"You have supplied exactly one of `vae_latents` and `clip_latents`, whereas either both or none"
218
+ f" are expected to be supplied. Defaulting to mode '{mode}'."
219
+ )
220
+ elif not prompt_latents_available and not vae_latents_available and not clip_latents_available:
221
+ # No inputs or latents supplied
222
+ logger.warning(
223
+ f"No inputs or latents have been supplied, and mode has not been manually set,"
224
+ f" defaulting to mode '{mode}'."
225
+ )
226
+
227
+ return mode
228
+
229
+ # Copied from diffusers.pipelines.pipeline_utils.StableDiffusionMixin.enable_vae_slicing
230
+ def enable_vae_slicing(self):
231
+ r"""
232
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
233
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
234
+ """
235
+ depr_message = f"Calling `enable_vae_slicing()` on a `{self.__class__.__name__}` is deprecated and this method will be removed in a future version. Please use `pipe.vae.enable_slicing()`."
236
+ deprecate(
237
+ "enable_vae_slicing",
238
+ "0.40.0",
239
+ depr_message,
240
+ )
241
+ self.vae.enable_slicing()
242
+
243
+ # Copied from diffusers.pipelines.pipeline_utils.StableDiffusionMixin.disable_vae_slicing
244
+ def disable_vae_slicing(self):
245
+ r"""
246
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
247
+ computing decoding in one step.
248
+ """
249
+ depr_message = f"Calling `disable_vae_slicing()` on a `{self.__class__.__name__}` is deprecated and this method will be removed in a future version. Please use `pipe.vae.disable_slicing()`."
250
+ deprecate(
251
+ "disable_vae_slicing",
252
+ "0.40.0",
253
+ depr_message,
254
+ )
255
+ self.vae.disable_slicing()
256
+
257
+ # Copied from diffusers.pipelines.pipeline_utils.StableDiffusionMixin.enable_vae_tiling
258
+ def enable_vae_tiling(self):
259
+ r"""
260
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
261
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
262
+ processing larger images.
263
+ """
264
+ depr_message = f"Calling `enable_vae_tiling()` on a `{self.__class__.__name__}` is deprecated and this method will be removed in a future version. Please use `pipe.vae.enable_tiling()`."
265
+ deprecate(
266
+ "enable_vae_tiling",
267
+ "0.40.0",
268
+ depr_message,
269
+ )
270
+ self.vae.enable_tiling()
271
+
272
+ # Copied from diffusers.pipelines.pipeline_utils.StableDiffusionMixin.disable_vae_tiling
273
+ def disable_vae_tiling(self):
274
+ r"""
275
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
276
+ computing decoding in one step.
277
+ """
278
+ depr_message = f"Calling `disable_vae_tiling()` on a `{self.__class__.__name__}` is deprecated and this method will be removed in a future version. Please use `pipe.vae.disable_tiling()`."
279
+ deprecate(
280
+ "disable_vae_tiling",
281
+ "0.40.0",
282
+ depr_message,
283
+ )
284
+ self.vae.disable_tiling()
285
+
286
+ # Functions to manually set the mode
287
+ def set_text_mode(self):
288
+ r"""Manually set the generation mode to unconditional ("marginal") text generation."""
289
+ self.mode = "text"
290
+
291
+ def set_image_mode(self):
292
+ r"""Manually set the generation mode to unconditional ("marginal") image generation."""
293
+ self.mode = "img"
294
+
295
+ def set_text_to_image_mode(self):
296
+ r"""Manually set the generation mode to text-conditioned image generation."""
297
+ self.mode = "text2img"
298
+
299
+ def set_image_to_text_mode(self):
300
+ r"""Manually set the generation mode to image-conditioned text generation."""
301
+ self.mode = "img2text"
302
+
303
+ def set_joint_mode(self):
304
+ r"""Manually set the generation mode to unconditional joint image-text generation."""
305
+ self.mode = "joint"
306
+
307
+ def reset_mode(self):
308
+ r"""Removes a manually set mode; after calling this, the pipeline will infer the mode from inputs."""
309
+ self.mode = None
310
+
311
+ def _infer_batch_size(
312
+ self,
313
+ mode,
314
+ prompt,
315
+ prompt_embeds,
316
+ image,
317
+ num_images_per_prompt,
318
+ num_prompts_per_image,
319
+ latents,
320
+ prompt_latents,
321
+ vae_latents,
322
+ clip_latents,
323
+ ):
324
+ r"""Infers the batch size and multiplier depending on mode and supplied arguments to `__call__`."""
325
+ if num_images_per_prompt is None:
326
+ num_images_per_prompt = 1
327
+ if num_prompts_per_image is None:
328
+ num_prompts_per_image = 1
329
+
330
+ assert num_images_per_prompt > 0, "num_images_per_prompt must be a positive integer"
331
+ assert num_prompts_per_image > 0, "num_prompts_per_image must be a positive integer"
332
+
333
+ if mode in ["text2img"]:
334
+ if prompt is not None and isinstance(prompt, str):
335
+ batch_size = 1
336
+ elif prompt is not None and isinstance(prompt, list):
337
+ batch_size = len(prompt)
338
+ else:
339
+ # Either prompt or prompt_embeds must be present for text2img.
340
+ batch_size = prompt_embeds.shape[0]
341
+ multiplier = num_images_per_prompt
342
+ elif mode in ["img2text"]:
343
+ if isinstance(image, PIL.Image.Image):
344
+ batch_size = 1
345
+ else:
346
+ # Image must be available and type either PIL.Image.Image or torch.Tensor.
347
+ # Not currently supporting something like image_embeds.
348
+ batch_size = image.shape[0]
349
+ multiplier = num_prompts_per_image
350
+ elif mode in ["img"]:
351
+ if vae_latents is not None:
352
+ batch_size = vae_latents.shape[0]
353
+ elif clip_latents is not None:
354
+ batch_size = clip_latents.shape[0]
355
+ else:
356
+ batch_size = 1
357
+ multiplier = num_images_per_prompt
358
+ elif mode in ["text"]:
359
+ if prompt_latents is not None:
360
+ batch_size = prompt_latents.shape[0]
361
+ else:
362
+ batch_size = 1
363
+ multiplier = num_prompts_per_image
364
+ elif mode in ["joint"]:
365
+ if latents is not None:
366
+ batch_size = latents.shape[0]
367
+ elif prompt_latents is not None:
368
+ batch_size = prompt_latents.shape[0]
369
+ elif vae_latents is not None:
370
+ batch_size = vae_latents.shape[0]
371
+ elif clip_latents is not None:
372
+ batch_size = clip_latents.shape[0]
373
+ else:
374
+ batch_size = 1
375
+
376
+ if num_images_per_prompt == num_prompts_per_image:
377
+ multiplier = num_images_per_prompt
378
+ else:
379
+ multiplier = min(num_images_per_prompt, num_prompts_per_image)
380
+ logger.warning(
381
+ f"You are using mode `{mode}` and `num_images_per_prompt`: {num_images_per_prompt} and"
382
+ f" num_prompts_per_image: {num_prompts_per_image} are not equal. Using batch size equal to"
383
+ f" `min(num_images_per_prompt, num_prompts_per_image) = {batch_size}."
384
+ )
385
+ return batch_size, multiplier
386
+
387
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
388
+ def _encode_prompt(
389
+ self,
390
+ prompt,
391
+ device,
392
+ num_images_per_prompt,
393
+ do_classifier_free_guidance,
394
+ negative_prompt=None,
395
+ prompt_embeds: Optional[torch.Tensor] = None,
396
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
397
+ lora_scale: Optional[float] = None,
398
+ **kwargs,
399
+ ):
400
+ 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."
401
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
402
+
403
+ prompt_embeds_tuple = self.encode_prompt(
404
+ prompt=prompt,
405
+ device=device,
406
+ num_images_per_prompt=num_images_per_prompt,
407
+ do_classifier_free_guidance=do_classifier_free_guidance,
408
+ negative_prompt=negative_prompt,
409
+ prompt_embeds=prompt_embeds,
410
+ negative_prompt_embeds=negative_prompt_embeds,
411
+ lora_scale=lora_scale,
412
+ **kwargs,
413
+ )
414
+
415
+ # concatenate for backwards comp
416
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
417
+
418
+ return prompt_embeds
419
+
420
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt with self.tokenizer->self.clip_tokenizer
421
+ def encode_prompt(
422
+ self,
423
+ prompt,
424
+ device,
425
+ num_images_per_prompt,
426
+ do_classifier_free_guidance,
427
+ negative_prompt=None,
428
+ prompt_embeds: Optional[torch.Tensor] = None,
429
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
430
+ lora_scale: Optional[float] = None,
431
+ clip_skip: Optional[int] = None,
432
+ ):
433
+ r"""
434
+ Encodes the prompt into text encoder hidden states.
435
+
436
+ Args:
437
+ prompt (`str` or `List[str]`, *optional*):
438
+ prompt to be encoded
439
+ device: (`torch.device`):
440
+ torch device
441
+ num_images_per_prompt (`int`):
442
+ number of images that should be generated per prompt
443
+ do_classifier_free_guidance (`bool`):
444
+ whether to use classifier free guidance or not
445
+ negative_prompt (`str` or `List[str]`, *optional*):
446
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
447
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
448
+ less than `1`).
449
+ prompt_embeds (`torch.Tensor`, *optional*):
450
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
451
+ provided, text embeddings will be generated from `prompt` input argument.
452
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
453
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
454
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
455
+ argument.
456
+ lora_scale (`float`, *optional*):
457
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
458
+ clip_skip (`int`, *optional*):
459
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
460
+ the output of the pre-final layer will be used for computing the prompt embeddings.
461
+ """
462
+ # set lora scale so that monkey patched LoRA
463
+ # function of text encoder can correctly access it
464
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
465
+ self._lora_scale = lora_scale
466
+
467
+ # dynamically adjust the LoRA scale
468
+ if not USE_PEFT_BACKEND:
469
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
470
+ else:
471
+ scale_lora_layers(self.text_encoder, lora_scale)
472
+
473
+ if prompt is not None and isinstance(prompt, str):
474
+ batch_size = 1
475
+ elif prompt is not None and isinstance(prompt, list):
476
+ batch_size = len(prompt)
477
+ else:
478
+ batch_size = prompt_embeds.shape[0]
479
+
480
+ if prompt_embeds is None:
481
+ # textual inversion: process multi-vector tokens if necessary
482
+ if isinstance(self, TextualInversionLoaderMixin):
483
+ prompt = self.maybe_convert_prompt(prompt, self.clip_tokenizer)
484
+
485
+ text_inputs = self.clip_tokenizer(
486
+ prompt,
487
+ padding="max_length",
488
+ max_length=self.clip_tokenizer.model_max_length,
489
+ truncation=True,
490
+ return_tensors="pt",
491
+ )
492
+ text_input_ids = text_inputs.input_ids
493
+ untruncated_ids = self.clip_tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
494
+
495
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
496
+ text_input_ids, untruncated_ids
497
+ ):
498
+ removed_text = self.clip_tokenizer.batch_decode(
499
+ untruncated_ids[:, self.clip_tokenizer.model_max_length - 1 : -1]
500
+ )
501
+ logger.warning(
502
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
503
+ f" {self.clip_tokenizer.model_max_length} tokens: {removed_text}"
504
+ )
505
+
506
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
507
+ attention_mask = text_inputs.attention_mask.to(device)
508
+ else:
509
+ attention_mask = None
510
+
511
+ if clip_skip is None:
512
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
513
+ prompt_embeds = prompt_embeds[0]
514
+ else:
515
+ prompt_embeds = self.text_encoder(
516
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
517
+ )
518
+ # Access the `hidden_states` first, that contains a tuple of
519
+ # all the hidden states from the encoder layers. Then index into
520
+ # the tuple to access the hidden states from the desired layer.
521
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
522
+ # We also need to apply the final LayerNorm here to not mess with the
523
+ # representations. The `last_hidden_states` that we typically use for
524
+ # obtaining the final prompt representations passes through the LayerNorm
525
+ # layer.
526
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
527
+
528
+ if self.text_encoder is not None:
529
+ prompt_embeds_dtype = self.text_encoder.dtype
530
+ elif self.unet is not None:
531
+ prompt_embeds_dtype = self.unet.dtype
532
+ else:
533
+ prompt_embeds_dtype = prompt_embeds.dtype
534
+
535
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
536
+
537
+ bs_embed, seq_len, _ = prompt_embeds.shape
538
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
539
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
540
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
541
+
542
+ # get unconditional embeddings for classifier free guidance
543
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
544
+ uncond_tokens: List[str]
545
+ if negative_prompt is None:
546
+ uncond_tokens = [""] * batch_size
547
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
548
+ raise TypeError(
549
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
550
+ f" {type(prompt)}."
551
+ )
552
+ elif isinstance(negative_prompt, str):
553
+ uncond_tokens = [negative_prompt]
554
+ elif batch_size != len(negative_prompt):
555
+ raise ValueError(
556
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
557
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
558
+ " the batch size of `prompt`."
559
+ )
560
+ else:
561
+ uncond_tokens = negative_prompt
562
+
563
+ # textual inversion: process multi-vector tokens if necessary
564
+ if isinstance(self, TextualInversionLoaderMixin):
565
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.clip_tokenizer)
566
+
567
+ max_length = prompt_embeds.shape[1]
568
+ uncond_input = self.clip_tokenizer(
569
+ uncond_tokens,
570
+ padding="max_length",
571
+ max_length=max_length,
572
+ truncation=True,
573
+ return_tensors="pt",
574
+ )
575
+
576
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
577
+ attention_mask = uncond_input.attention_mask.to(device)
578
+ else:
579
+ attention_mask = None
580
+
581
+ negative_prompt_embeds = self.text_encoder(
582
+ uncond_input.input_ids.to(device),
583
+ attention_mask=attention_mask,
584
+ )
585
+ negative_prompt_embeds = negative_prompt_embeds[0]
586
+
587
+ if do_classifier_free_guidance:
588
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
589
+ seq_len = negative_prompt_embeds.shape[1]
590
+
591
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
592
+
593
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
594
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
595
+
596
+ if self.text_encoder is not None:
597
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
598
+ # Retrieve the original scale by scaling back the LoRA layers
599
+ unscale_lora_layers(self.text_encoder, lora_scale)
600
+
601
+ return prompt_embeds, negative_prompt_embeds
602
+
603
+ # Modified from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_instruct_pix2pix.StableDiffusionInstructPix2PixPipeline.prepare_image_latents
604
+ # Add num_prompts_per_image argument, sample from autoencoder moment distribution
605
+ def encode_image_vae_latents(
606
+ self,
607
+ image,
608
+ batch_size,
609
+ num_prompts_per_image,
610
+ dtype,
611
+ device,
612
+ do_classifier_free_guidance,
613
+ generator=None,
614
+ ):
615
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
616
+ raise ValueError(
617
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
618
+ )
619
+
620
+ image = image.to(device=device, dtype=dtype)
621
+
622
+ batch_size = batch_size * num_prompts_per_image
623
+ if isinstance(generator, list) and len(generator) != batch_size:
624
+ raise ValueError(
625
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
626
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
627
+ )
628
+
629
+ if isinstance(generator, list):
630
+ image_latents = [
631
+ self.vae.encode(image[i : i + 1]).latent_dist.sample(generator=generator[i])
632
+ * self.vae.config.scaling_factor
633
+ for i in range(batch_size)
634
+ ]
635
+ image_latents = torch.cat(image_latents, dim=0)
636
+ else:
637
+ image_latents = self.vae.encode(image).latent_dist.sample(generator=generator)
638
+ # Scale image_latents by the VAE's scaling factor
639
+ image_latents = image_latents * self.vae.config.scaling_factor
640
+
641
+ if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
642
+ # expand image_latents for batch_size
643
+ deprecation_message = (
644
+ f"You have passed {batch_size} text prompts (`prompt`), but only {image_latents.shape[0]} initial"
645
+ " images (`image`). Initial images are now duplicating to match the number of text prompts. Note"
646
+ " that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update"
647
+ " your script to pass as many initial images as text prompts to suppress this warning."
648
+ )
649
+ deprecate("len(prompt) != len(image)", "1.0.0", deprecation_message, standard_warn=False)
650
+ additional_image_per_prompt = batch_size // image_latents.shape[0]
651
+ image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0)
652
+ elif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] != 0:
653
+ raise ValueError(
654
+ f"Cannot duplicate `image` of batch size {image_latents.shape[0]} to {batch_size} text prompts."
655
+ )
656
+ else:
657
+ image_latents = torch.cat([image_latents], dim=0)
658
+
659
+ if do_classifier_free_guidance:
660
+ uncond_image_latents = torch.zeros_like(image_latents)
661
+ image_latents = torch.cat([image_latents, image_latents, uncond_image_latents], dim=0)
662
+
663
+ return image_latents
664
+
665
+ def encode_image_clip_latents(
666
+ self,
667
+ image,
668
+ batch_size,
669
+ num_prompts_per_image,
670
+ dtype,
671
+ device,
672
+ generator=None,
673
+ ):
674
+ # Map image to CLIP embedding.
675
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
676
+ raise ValueError(
677
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
678
+ )
679
+
680
+ preprocessed_image = self.clip_image_processor.preprocess(
681
+ image,
682
+ return_tensors="pt",
683
+ )
684
+ preprocessed_image = preprocessed_image.to(device=device, dtype=dtype)
685
+
686
+ batch_size = batch_size * num_prompts_per_image
687
+ if isinstance(generator, list):
688
+ image_latents = [
689
+ self.image_encoder(**preprocessed_image[i : i + 1]).image_embeds for i in range(batch_size)
690
+ ]
691
+ image_latents = torch.cat(image_latents, dim=0)
692
+ else:
693
+ image_latents = self.image_encoder(**preprocessed_image).image_embeds
694
+
695
+ if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
696
+ # expand image_latents for batch_size
697
+ deprecation_message = (
698
+ f"You have passed {batch_size} text prompts (`prompt`), but only {image_latents.shape[0]} initial"
699
+ " images (`image`). Initial images are now duplicating to match the number of text prompts. Note"
700
+ " that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update"
701
+ " your script to pass as many initial images as text prompts to suppress this warning."
702
+ )
703
+ deprecate("len(prompt) != len(image)", "1.0.0", deprecation_message, standard_warn=False)
704
+ additional_image_per_prompt = batch_size // image_latents.shape[0]
705
+ image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0)
706
+ elif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] != 0:
707
+ raise ValueError(
708
+ f"Cannot duplicate `image` of batch size {image_latents.shape[0]} to {batch_size} text prompts."
709
+ )
710
+ else:
711
+ image_latents = torch.cat([image_latents], dim=0)
712
+
713
+ if isinstance(generator, list) and len(generator) != batch_size:
714
+ raise ValueError(
715
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
716
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
717
+ )
718
+
719
+ return image_latents
720
+
721
+ def prepare_text_latents(
722
+ self, batch_size, num_images_per_prompt, seq_len, hidden_size, dtype, device, generator, latents=None
723
+ ):
724
+ # Prepare latents for the CLIP embedded prompt.
725
+ shape = (batch_size * num_images_per_prompt, seq_len, hidden_size)
726
+ if isinstance(generator, list) and len(generator) != batch_size:
727
+ raise ValueError(
728
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
729
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
730
+ )
731
+
732
+ if latents is None:
733
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
734
+ else:
735
+ # latents is assumed to have shace (B, L, D)
736
+ latents = latents.repeat(num_images_per_prompt, 1, 1)
737
+ latents = latents.to(device=device, dtype=dtype)
738
+
739
+ # scale the initial noise by the standard deviation required by the scheduler
740
+ latents = latents * self.scheduler.init_noise_sigma
741
+ return latents
742
+
743
+ # Modified from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
744
+ # Rename prepare_latents -> prepare_image_vae_latents and add num_prompts_per_image argument.
745
+ def prepare_image_vae_latents(
746
+ self,
747
+ batch_size,
748
+ num_prompts_per_image,
749
+ num_channels_latents,
750
+ height,
751
+ width,
752
+ dtype,
753
+ device,
754
+ generator,
755
+ latents=None,
756
+ ):
757
+ shape = (
758
+ batch_size * num_prompts_per_image,
759
+ num_channels_latents,
760
+ height // self.vae_scale_factor,
761
+ width // self.vae_scale_factor,
762
+ )
763
+ if isinstance(generator, list) and len(generator) != batch_size:
764
+ raise ValueError(
765
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
766
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
767
+ )
768
+
769
+ if latents is None:
770
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
771
+ else:
772
+ # latents is assumed to have shape (B, C, H, W)
773
+ latents = latents.repeat(num_prompts_per_image, 1, 1, 1)
774
+ latents = latents.to(device=device, dtype=dtype)
775
+
776
+ # scale the initial noise by the standard deviation required by the scheduler
777
+ latents = latents * self.scheduler.init_noise_sigma
778
+ return latents
779
+
780
+ def prepare_image_clip_latents(
781
+ self, batch_size, num_prompts_per_image, clip_img_dim, dtype, device, generator, latents=None
782
+ ):
783
+ # Prepare latents for the CLIP embedded image.
784
+ shape = (batch_size * num_prompts_per_image, 1, clip_img_dim)
785
+ if isinstance(generator, list) and len(generator) != batch_size:
786
+ raise ValueError(
787
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
788
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
789
+ )
790
+
791
+ if latents is None:
792
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
793
+ else:
794
+ # latents is assumed to have shape (B, L, D)
795
+ latents = latents.repeat(num_prompts_per_image, 1, 1)
796
+ latents = latents.to(device=device, dtype=dtype)
797
+
798
+ # scale the initial noise by the standard deviation required by the scheduler
799
+ latents = latents * self.scheduler.init_noise_sigma
800
+ return latents
801
+
802
+ def decode_text_latents(self, text_latents, device):
803
+ output_token_list, seq_lengths = self.text_decoder.generate_captions(
804
+ text_latents, self.text_tokenizer.eos_token_id, device=device
805
+ )
806
+ output_list = output_token_list.cpu().numpy()
807
+ generated_text = [
808
+ self.text_tokenizer.decode(output[: int(length)], skip_special_tokens=True)
809
+ for output, length in zip(output_list, seq_lengths)
810
+ ]
811
+ return generated_text
812
+
813
+ def _split(self, x, height, width):
814
+ r"""
815
+ Splits a flattened embedding x of shape (B, C * H * W + clip_img_dim) into two tensors of shape (B, C, H, W)
816
+ and (B, 1, clip_img_dim)
817
+ """
818
+ batch_size = x.shape[0]
819
+ latent_height = height // self.vae_scale_factor
820
+ latent_width = width // self.vae_scale_factor
821
+ img_vae_dim = self.num_channels_latents * latent_height * latent_width
822
+
823
+ img_vae, img_clip = x.split([img_vae_dim, self.image_encoder_projection_dim], dim=1)
824
+
825
+ img_vae = torch.reshape(img_vae, (batch_size, self.num_channels_latents, latent_height, latent_width))
826
+ img_clip = torch.reshape(img_clip, (batch_size, 1, self.image_encoder_projection_dim))
827
+ return img_vae, img_clip
828
+
829
+ def _combine(self, img_vae, img_clip):
830
+ r"""
831
+ Combines a latent image img_vae of shape (B, C, H, W) and a CLIP-embedded image img_clip of shape (B, 1,
832
+ clip_img_dim) into a single tensor of shape (B, C * H * W + clip_img_dim).
833
+ """
834
+ img_vae = torch.reshape(img_vae, (img_vae.shape[0], -1))
835
+ img_clip = torch.reshape(img_clip, (img_clip.shape[0], -1))
836
+ return torch.concat([img_vae, img_clip], dim=-1)
837
+
838
+ def _split_joint(self, x, height, width):
839
+ r"""
840
+ Splits a flattened embedding x of shape (B, C * H * W + clip_img_dim + text_seq_len * text_dim] into (img_vae,
841
+ img_clip, text) where img_vae is of shape (B, C, H, W), img_clip is of shape (B, 1, clip_img_dim), and text is
842
+ of shape (B, text_seq_len, text_dim).
843
+ """
844
+ batch_size = x.shape[0]
845
+ latent_height = height // self.vae_scale_factor
846
+ latent_width = width // self.vae_scale_factor
847
+ img_vae_dim = self.num_channels_latents * latent_height * latent_width
848
+ text_dim = self.text_encoder_seq_len * self.text_intermediate_dim
849
+
850
+ img_vae, img_clip, text = x.split([img_vae_dim, self.image_encoder_projection_dim, text_dim], dim=1)
851
+
852
+ img_vae = torch.reshape(img_vae, (batch_size, self.num_channels_latents, latent_height, latent_width))
853
+ img_clip = torch.reshape(img_clip, (batch_size, 1, self.image_encoder_projection_dim))
854
+ text = torch.reshape(text, (batch_size, self.text_encoder_seq_len, self.text_intermediate_dim))
855
+ return img_vae, img_clip, text
856
+
857
+ def _combine_joint(self, img_vae, img_clip, text):
858
+ r"""
859
+ Combines a latent image img_vae of shape (B, C, H, W), a CLIP-embedded image img_clip of shape (B, L_img,
860
+ clip_img_dim), and a text embedding text of shape (B, L_text, text_dim) into a single embedding x of shape (B,
861
+ C * H * W + L_img * clip_img_dim + L_text * text_dim).
862
+ """
863
+ img_vae = torch.reshape(img_vae, (img_vae.shape[0], -1))
864
+ img_clip = torch.reshape(img_clip, (img_clip.shape[0], -1))
865
+ text = torch.reshape(text, (text.shape[0], -1))
866
+ return torch.concat([img_vae, img_clip, text], dim=-1)
867
+
868
+ def _get_noise_pred(
869
+ self,
870
+ mode,
871
+ latents,
872
+ t,
873
+ prompt_embeds,
874
+ img_vae,
875
+ img_clip,
876
+ max_timestep,
877
+ data_type,
878
+ guidance_scale,
879
+ generator,
880
+ device,
881
+ height,
882
+ width,
883
+ ):
884
+ r"""
885
+ Gets the noise prediction using the `unet` and performs classifier-free guidance, if necessary.
886
+ """
887
+ if mode == "joint":
888
+ # Joint text-image generation
889
+ img_vae_latents, img_clip_latents, text_latents = self._split_joint(latents, height, width)
890
+
891
+ img_vae_out, img_clip_out, text_out = self.unet(
892
+ img_vae_latents, img_clip_latents, text_latents, timestep_img=t, timestep_text=t, data_type=data_type
893
+ )
894
+
895
+ x_out = self._combine_joint(img_vae_out, img_clip_out, text_out)
896
+
897
+ if guidance_scale <= 1.0:
898
+ return x_out
899
+
900
+ # Classifier-free guidance
901
+ img_vae_T = randn_tensor(img_vae.shape, generator=generator, device=device, dtype=img_vae.dtype)
902
+ img_clip_T = randn_tensor(img_clip.shape, generator=generator, device=device, dtype=img_clip.dtype)
903
+ text_T = randn_tensor(prompt_embeds.shape, generator=generator, device=device, dtype=prompt_embeds.dtype)
904
+
905
+ _, _, text_out_uncond = self.unet(
906
+ img_vae_T, img_clip_T, text_latents, timestep_img=max_timestep, timestep_text=t, data_type=data_type
907
+ )
908
+
909
+ img_vae_out_uncond, img_clip_out_uncond, _ = self.unet(
910
+ img_vae_latents,
911
+ img_clip_latents,
912
+ text_T,
913
+ timestep_img=t,
914
+ timestep_text=max_timestep,
915
+ data_type=data_type,
916
+ )
917
+
918
+ x_out_uncond = self._combine_joint(img_vae_out_uncond, img_clip_out_uncond, text_out_uncond)
919
+
920
+ return guidance_scale * x_out + (1.0 - guidance_scale) * x_out_uncond
921
+ elif mode == "text2img":
922
+ # Text-conditioned image generation
923
+ img_vae_latents, img_clip_latents = self._split(latents, height, width)
924
+
925
+ img_vae_out, img_clip_out, text_out = self.unet(
926
+ img_vae_latents, img_clip_latents, prompt_embeds, timestep_img=t, timestep_text=0, data_type=data_type
927
+ )
928
+
929
+ img_out = self._combine(img_vae_out, img_clip_out)
930
+
931
+ if guidance_scale <= 1.0:
932
+ return img_out
933
+
934
+ # Classifier-free guidance
935
+ text_T = randn_tensor(prompt_embeds.shape, generator=generator, device=device, dtype=prompt_embeds.dtype)
936
+
937
+ img_vae_out_uncond, img_clip_out_uncond, text_out_uncond = self.unet(
938
+ img_vae_latents,
939
+ img_clip_latents,
940
+ text_T,
941
+ timestep_img=t,
942
+ timestep_text=max_timestep,
943
+ data_type=data_type,
944
+ )
945
+
946
+ img_out_uncond = self._combine(img_vae_out_uncond, img_clip_out_uncond)
947
+
948
+ return guidance_scale * img_out + (1.0 - guidance_scale) * img_out_uncond
949
+ elif mode == "img2text":
950
+ # Image-conditioned text generation
951
+ img_vae_out, img_clip_out, text_out = self.unet(
952
+ img_vae, img_clip, latents, timestep_img=0, timestep_text=t, data_type=data_type
953
+ )
954
+
955
+ if guidance_scale <= 1.0:
956
+ return text_out
957
+
958
+ # Classifier-free guidance
959
+ img_vae_T = randn_tensor(img_vae.shape, generator=generator, device=device, dtype=img_vae.dtype)
960
+ img_clip_T = randn_tensor(img_clip.shape, generator=generator, device=device, dtype=img_clip.dtype)
961
+
962
+ img_vae_out_uncond, img_clip_out_uncond, text_out_uncond = self.unet(
963
+ img_vae_T, img_clip_T, latents, timestep_img=max_timestep, timestep_text=t, data_type=data_type
964
+ )
965
+
966
+ return guidance_scale * text_out + (1.0 - guidance_scale) * text_out_uncond
967
+ elif mode == "text":
968
+ # Unconditional ("marginal") text generation (no CFG)
969
+ img_vae_out, img_clip_out, text_out = self.unet(
970
+ img_vae, img_clip, latents, timestep_img=max_timestep, timestep_text=t, data_type=data_type
971
+ )
972
+
973
+ return text_out
974
+ elif mode == "img":
975
+ # Unconditional ("marginal") image generation (no CFG)
976
+ img_vae_latents, img_clip_latents = self._split(latents, height, width)
977
+
978
+ img_vae_out, img_clip_out, text_out = self.unet(
979
+ img_vae_latents,
980
+ img_clip_latents,
981
+ prompt_embeds,
982
+ timestep_img=t,
983
+ timestep_text=max_timestep,
984
+ data_type=data_type,
985
+ )
986
+
987
+ img_out = self._combine(img_vae_out, img_clip_out)
988
+ return img_out
989
+
990
+ def check_latents_shape(self, latents_name, latents, expected_shape):
991
+ latents_shape = latents.shape
992
+ expected_num_dims = len(expected_shape) + 1 # expected dimensions plus the batch dimension
993
+ expected_shape_str = ", ".join(str(dim) for dim in expected_shape)
994
+ if len(latents_shape) != expected_num_dims:
995
+ raise ValueError(
996
+ f"`{latents_name}` should have shape (batch_size, {expected_shape_str}), but the current shape"
997
+ f" {latents_shape} has {len(latents_shape)} dimensions."
998
+ )
999
+ for i in range(1, expected_num_dims):
1000
+ if latents_shape[i] != expected_shape[i - 1]:
1001
+ raise ValueError(
1002
+ f"`{latents_name}` should have shape (batch_size, {expected_shape_str}), but the current shape"
1003
+ f" {latents_shape} has {latents_shape[i]} != {expected_shape[i - 1]} at dimension {i}."
1004
+ )
1005
+
1006
+ def check_inputs(
1007
+ self,
1008
+ mode,
1009
+ prompt,
1010
+ image,
1011
+ height,
1012
+ width,
1013
+ callback_steps,
1014
+ negative_prompt=None,
1015
+ prompt_embeds=None,
1016
+ negative_prompt_embeds=None,
1017
+ latents=None,
1018
+ prompt_latents=None,
1019
+ vae_latents=None,
1020
+ clip_latents=None,
1021
+ ):
1022
+ # Check inputs before running the generative process.
1023
+ if height % self.vae_scale_factor != 0 or width % self.vae_scale_factor != 0:
1024
+ raise ValueError(
1025
+ f"`height` and `width` have to be divisible by {self.vae_scale_factor} but are {height} and {width}."
1026
+ )
1027
+
1028
+ if (callback_steps is None) or (
1029
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
1030
+ ):
1031
+ raise ValueError(
1032
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
1033
+ f" {type(callback_steps)}."
1034
+ )
1035
+
1036
+ if mode == "text2img":
1037
+ if prompt is not None and prompt_embeds is not None:
1038
+ raise ValueError(
1039
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
1040
+ " only forward one of the two."
1041
+ )
1042
+ elif prompt is None and prompt_embeds is None:
1043
+ raise ValueError(
1044
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
1045
+ )
1046
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
1047
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
1048
+
1049
+ if negative_prompt is not None and negative_prompt_embeds is not None:
1050
+ raise ValueError(
1051
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
1052
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
1053
+ )
1054
+
1055
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
1056
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
1057
+ raise ValueError(
1058
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
1059
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
1060
+ f" {negative_prompt_embeds.shape}."
1061
+ )
1062
+
1063
+ if mode == "img2text":
1064
+ if image is None:
1065
+ raise ValueError("`img2text` mode requires an image to be provided.")
1066
+
1067
+ # Check provided latents
1068
+ latent_height = height // self.vae_scale_factor
1069
+ latent_width = width // self.vae_scale_factor
1070
+ full_latents_available = latents is not None
1071
+ prompt_latents_available = prompt_latents is not None
1072
+ vae_latents_available = vae_latents is not None
1073
+ clip_latents_available = clip_latents is not None
1074
+
1075
+ if full_latents_available:
1076
+ individual_latents_available = (
1077
+ prompt_latents is not None or vae_latents is not None or clip_latents is not None
1078
+ )
1079
+ if individual_latents_available:
1080
+ logger.warning(
1081
+ "You have supplied both `latents` and at least one of `prompt_latents`, `vae_latents`, and"
1082
+ " `clip_latents`. The value of `latents` will override the value of any individually supplied latents."
1083
+ )
1084
+ # Check shape of full latents
1085
+ img_vae_dim = self.num_channels_latents * latent_height * latent_width
1086
+ text_dim = self.text_encoder_seq_len * self.text_encoder_hidden_size
1087
+ latents_dim = img_vae_dim + self.image_encoder_projection_dim + text_dim
1088
+ latents_expected_shape = (latents_dim,)
1089
+ self.check_latents_shape("latents", latents, latents_expected_shape)
1090
+
1091
+ # Check individual latent shapes, if present
1092
+ if prompt_latents_available:
1093
+ prompt_latents_expected_shape = (self.text_encoder_seq_len, self.text_encoder_hidden_size)
1094
+ self.check_latents_shape("prompt_latents", prompt_latents, prompt_latents_expected_shape)
1095
+
1096
+ if vae_latents_available:
1097
+ vae_latents_expected_shape = (self.num_channels_latents, latent_height, latent_width)
1098
+ self.check_latents_shape("vae_latents", vae_latents, vae_latents_expected_shape)
1099
+
1100
+ if clip_latents_available:
1101
+ clip_latents_expected_shape = (1, self.image_encoder_projection_dim)
1102
+ self.check_latents_shape("clip_latents", clip_latents, clip_latents_expected_shape)
1103
+
1104
+ if mode in ["text2img", "img"] and vae_latents_available and clip_latents_available:
1105
+ if vae_latents.shape[0] != clip_latents.shape[0]:
1106
+ raise ValueError(
1107
+ f"Both `vae_latents` and `clip_latents` are supplied, but their batch dimensions are not equal:"
1108
+ f" {vae_latents.shape[0]} != {clip_latents.shape[0]}."
1109
+ )
1110
+
1111
+ if mode == "joint" and prompt_latents_available and vae_latents_available and clip_latents_available:
1112
+ if prompt_latents.shape[0] != vae_latents.shape[0] or prompt_latents.shape[0] != clip_latents.shape[0]:
1113
+ raise ValueError(
1114
+ f"All of `prompt_latents`, `vae_latents`, and `clip_latents` are supplied, but their batch"
1115
+ f" dimensions are not equal: {prompt_latents.shape[0]} != {vae_latents.shape[0]}"
1116
+ f" != {clip_latents.shape[0]}."
1117
+ )
1118
+
1119
+ @torch.no_grad()
1120
+ def __call__(
1121
+ self,
1122
+ prompt: Optional[Union[str, List[str]]] = None,
1123
+ image: Optional[Union[torch.Tensor, PIL.Image.Image]] = None,
1124
+ height: Optional[int] = None,
1125
+ width: Optional[int] = None,
1126
+ data_type: Optional[int] = 1,
1127
+ num_inference_steps: int = 50,
1128
+ guidance_scale: float = 8.0,
1129
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1130
+ num_images_per_prompt: Optional[int] = 1,
1131
+ num_prompts_per_image: Optional[int] = 1,
1132
+ eta: float = 0.0,
1133
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1134
+ latents: Optional[torch.Tensor] = None,
1135
+ prompt_latents: Optional[torch.Tensor] = None,
1136
+ vae_latents: Optional[torch.Tensor] = None,
1137
+ clip_latents: Optional[torch.Tensor] = None,
1138
+ prompt_embeds: Optional[torch.Tensor] = None,
1139
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1140
+ output_type: Optional[str] = "pil",
1141
+ return_dict: bool = True,
1142
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
1143
+ callback_steps: int = 1,
1144
+ ):
1145
+ r"""
1146
+ The call function to the pipeline for generation.
1147
+
1148
+ Args:
1149
+ prompt (`str` or `List[str]`, *optional*):
1150
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
1151
+ Required for text-conditioned image generation (`text2img`) mode.
1152
+ image (`torch.Tensor` or `PIL.Image.Image`, *optional*):
1153
+ `Image` or tensor representing an image batch. Required for image-conditioned text generation
1154
+ (`img2text`) mode.
1155
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1156
+ The height in pixels of the generated image.
1157
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1158
+ The width in pixels of the generated image.
1159
+ data_type (`int`, *optional*, defaults to 1):
1160
+ The data type (either 0 or 1). Only used if you are loading a checkpoint which supports a data type
1161
+ embedding; this is added for compatibility with the
1162
+ [UniDiffuser-v1](https://huggingface.co/thu-ml/unidiffuser-v1) checkpoint.
1163
+ num_inference_steps (`int`, *optional*, defaults to 50):
1164
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1165
+ expense of slower inference.
1166
+ guidance_scale (`float`, *optional*, defaults to 8.0):
1167
+ A higher guidance scale value encourages the model to generate images closely linked to the text
1168
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
1169
+ negative_prompt (`str` or `List[str]`, *optional*):
1170
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
1171
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`). Used in
1172
+ text-conditioned image generation (`text2img`) mode.
1173
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1174
+ The number of images to generate per prompt. Used in `text2img` (text-conditioned image generation) and
1175
+ `img` mode. If the mode is joint and both `num_images_per_prompt` and `num_prompts_per_image` are
1176
+ supplied, `min(num_images_per_prompt, num_prompts_per_image)` samples are generated.
1177
+ num_prompts_per_image (`int`, *optional*, defaults to 1):
1178
+ The number of prompts to generate per image. Used in `img2text` (image-conditioned text generation) and
1179
+ `text` mode. If the mode is joint and both `num_images_per_prompt` and `num_prompts_per_image` are
1180
+ supplied, `min(num_images_per_prompt, num_prompts_per_image)` samples are generated.
1181
+ eta (`float`, *optional*, defaults to 0.0):
1182
+ Corresponds to parameter eta (η) from the [DDIM](https://huggingface.co/papers/2010.02502) paper. Only
1183
+ applies to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
1184
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1185
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
1186
+ generation deterministic.
1187
+ latents (`torch.Tensor`, *optional*):
1188
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for joint
1189
+ image-text generation. Can be used to tweak the same generation with different prompts. If not
1190
+ provided, a latents tensor is generated by sampling using the supplied random `generator`. This assumes
1191
+ a full set of VAE, CLIP, and text latents, if supplied, overrides the value of `prompt_latents`,
1192
+ `vae_latents`, and `clip_latents`.
1193
+ prompt_latents (`torch.Tensor`, *optional*):
1194
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for text
1195
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1196
+ tensor is generated by sampling using the supplied random `generator`.
1197
+ vae_latents (`torch.Tensor`, *optional*):
1198
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
1199
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1200
+ tensor is generated by sampling using the supplied random `generator`.
1201
+ clip_latents (`torch.Tensor`, *optional*):
1202
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
1203
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1204
+ tensor is generated by sampling using the supplied random `generator`.
1205
+ prompt_embeds (`torch.Tensor`, *optional*):
1206
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
1207
+ provided, text embeddings are generated from the `prompt` input argument. Used in text-conditioned
1208
+ image generation (`text2img`) mode.
1209
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1210
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
1211
+ not provided, `negative_prompt_embeds` are be generated from the `negative_prompt` input argument. Used
1212
+ in text-conditioned image generation (`text2img`) mode.
1213
+ output_type (`str`, *optional*, defaults to `"pil"`):
1214
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
1215
+ return_dict (`bool`, *optional*, defaults to `True`):
1216
+ Whether or not to return a [`~pipelines.ImageTextPipelineOutput`] instead of a plain tuple.
1217
+ callback (`Callable`, *optional*):
1218
+ A function that calls every `callback_steps` steps during inference. The function is called with the
1219
+ following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
1220
+ callback_steps (`int`, *optional*, defaults to 1):
1221
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
1222
+ every step.
1223
+
1224
+ Returns:
1225
+ [`~pipelines.unidiffuser.ImageTextPipelineOutput`] or `tuple`:
1226
+ If `return_dict` is `True`, [`~pipelines.unidiffuser.ImageTextPipelineOutput`] is returned, otherwise a
1227
+ `tuple` is returned where the first element is a list with the generated images and the second element
1228
+ is a list of generated texts.
1229
+ """
1230
+
1231
+ # 0. Default height and width to unet
1232
+ height = height or self.unet_resolution * self.vae_scale_factor
1233
+ width = width or self.unet_resolution * self.vae_scale_factor
1234
+
1235
+ # 1. Check inputs
1236
+ # Recalculate mode for each call to the pipeline.
1237
+ mode = self._infer_mode(prompt, prompt_embeds, image, latents, prompt_latents, vae_latents, clip_latents)
1238
+ self.check_inputs(
1239
+ mode,
1240
+ prompt,
1241
+ image,
1242
+ height,
1243
+ width,
1244
+ callback_steps,
1245
+ negative_prompt,
1246
+ prompt_embeds,
1247
+ negative_prompt_embeds,
1248
+ latents,
1249
+ prompt_latents,
1250
+ vae_latents,
1251
+ clip_latents,
1252
+ )
1253
+
1254
+ # 2. Define call parameters
1255
+ batch_size, multiplier = self._infer_batch_size(
1256
+ mode,
1257
+ prompt,
1258
+ prompt_embeds,
1259
+ image,
1260
+ num_images_per_prompt,
1261
+ num_prompts_per_image,
1262
+ latents,
1263
+ prompt_latents,
1264
+ vae_latents,
1265
+ clip_latents,
1266
+ )
1267
+ device = self._execution_device
1268
+ reduce_text_emb_dim = self.text_intermediate_dim < self.text_encoder_hidden_size or self.mode != "text2img"
1269
+
1270
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1271
+ # of the Imagen paper: https://huggingface.co/papers/2205.11487 . `guidance_scale = 1`
1272
+ # corresponds to doing no classifier free guidance.
1273
+ # Note that this differs from the formulation in the unidiffusers paper!
1274
+ do_classifier_free_guidance = guidance_scale > 1.0
1275
+
1276
+ # check if scheduler is in sigmas space
1277
+ # scheduler_is_in_sigma_space = hasattr(self.scheduler, "sigmas")
1278
+
1279
+ # 3. Encode input prompt, if available; otherwise prepare text latents
1280
+ if latents is not None:
1281
+ # Overwrite individual latents
1282
+ vae_latents, clip_latents, prompt_latents = self._split_joint(latents, height, width)
1283
+
1284
+ if mode in ["text2img"]:
1285
+ # 3.1. Encode input prompt, if available
1286
+ assert prompt is not None or prompt_embeds is not None
1287
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
1288
+ prompt=prompt,
1289
+ device=device,
1290
+ num_images_per_prompt=multiplier,
1291
+ do_classifier_free_guidance=do_classifier_free_guidance,
1292
+ negative_prompt=negative_prompt,
1293
+ prompt_embeds=prompt_embeds,
1294
+ negative_prompt_embeds=negative_prompt_embeds,
1295
+ )
1296
+
1297
+ # if do_classifier_free_guidance:
1298
+ # prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
1299
+ else:
1300
+ # 3.2. Prepare text latent variables, if input not available
1301
+ prompt_embeds = self.prepare_text_latents(
1302
+ batch_size=batch_size,
1303
+ num_images_per_prompt=multiplier,
1304
+ seq_len=self.text_encoder_seq_len,
1305
+ hidden_size=self.text_encoder_hidden_size,
1306
+ dtype=self.text_encoder.dtype, # Should work with both full precision and mixed precision
1307
+ device=device,
1308
+ generator=generator,
1309
+ latents=prompt_latents,
1310
+ )
1311
+
1312
+ if reduce_text_emb_dim:
1313
+ prompt_embeds = self.text_decoder.encode(prompt_embeds)
1314
+
1315
+ # 4. Encode image, if available; otherwise prepare image latents
1316
+ if mode in ["img2text"]:
1317
+ # 4.1. Encode images, if available
1318
+ assert image is not None, "`img2text` requires a conditioning image"
1319
+ # Encode image using VAE
1320
+ image_vae = self.image_processor.preprocess(image)
1321
+ height, width = image_vae.shape[-2:]
1322
+ image_vae_latents = self.encode_image_vae_latents(
1323
+ image=image_vae,
1324
+ batch_size=batch_size,
1325
+ num_prompts_per_image=multiplier,
1326
+ dtype=prompt_embeds.dtype,
1327
+ device=device,
1328
+ do_classifier_free_guidance=False, # Copied from InstructPix2Pix, don't use their version of CFG
1329
+ generator=generator,
1330
+ )
1331
+
1332
+ # Encode image using CLIP
1333
+ image_clip_latents = self.encode_image_clip_latents(
1334
+ image=image,
1335
+ batch_size=batch_size,
1336
+ num_prompts_per_image=multiplier,
1337
+ dtype=prompt_embeds.dtype,
1338
+ device=device,
1339
+ generator=generator,
1340
+ )
1341
+ # (batch_size, clip_hidden_size) => (batch_size, 1, clip_hidden_size)
1342
+ image_clip_latents = image_clip_latents.unsqueeze(1)
1343
+ else:
1344
+ # 4.2. Prepare image latent variables, if input not available
1345
+ # Prepare image VAE latents in latent space
1346
+ image_vae_latents = self.prepare_image_vae_latents(
1347
+ batch_size=batch_size,
1348
+ num_prompts_per_image=multiplier,
1349
+ num_channels_latents=self.num_channels_latents,
1350
+ height=height,
1351
+ width=width,
1352
+ dtype=prompt_embeds.dtype,
1353
+ device=device,
1354
+ generator=generator,
1355
+ latents=vae_latents,
1356
+ )
1357
+
1358
+ # Prepare image CLIP latents
1359
+ image_clip_latents = self.prepare_image_clip_latents(
1360
+ batch_size=batch_size,
1361
+ num_prompts_per_image=multiplier,
1362
+ clip_img_dim=self.image_encoder_projection_dim,
1363
+ dtype=prompt_embeds.dtype,
1364
+ device=device,
1365
+ generator=generator,
1366
+ latents=clip_latents,
1367
+ )
1368
+
1369
+ # 5. Set timesteps
1370
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1371
+ timesteps = self.scheduler.timesteps
1372
+ # max_timestep = timesteps[0]
1373
+ max_timestep = self.scheduler.config.num_train_timesteps
1374
+
1375
+ # 6. Prepare latent variables
1376
+ if mode == "joint":
1377
+ latents = self._combine_joint(image_vae_latents, image_clip_latents, prompt_embeds)
1378
+ elif mode in ["text2img", "img"]:
1379
+ latents = self._combine(image_vae_latents, image_clip_latents)
1380
+ elif mode in ["img2text", "text"]:
1381
+ latents = prompt_embeds
1382
+
1383
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1384
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1385
+
1386
+ logger.debug(f"Scheduler extra step kwargs: {extra_step_kwargs}")
1387
+
1388
+ # 8. Denoising loop
1389
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1390
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1391
+ for i, t in enumerate(timesteps):
1392
+ # predict the noise residual
1393
+ # Also applies classifier-free guidance as described in the UniDiffuser paper
1394
+ noise_pred = self._get_noise_pred(
1395
+ mode,
1396
+ latents,
1397
+ t,
1398
+ prompt_embeds,
1399
+ image_vae_latents,
1400
+ image_clip_latents,
1401
+ max_timestep,
1402
+ data_type,
1403
+ guidance_scale,
1404
+ generator,
1405
+ device,
1406
+ height,
1407
+ width,
1408
+ )
1409
+
1410
+ # compute the previous noisy sample x_t -> x_t-1
1411
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
1412
+
1413
+ # call the callback, if provided
1414
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1415
+ progress_bar.update()
1416
+ if callback is not None and i % callback_steps == 0:
1417
+ step_idx = i // getattr(self.scheduler, "order", 1)
1418
+ callback(step_idx, t, latents)
1419
+
1420
+ if XLA_AVAILABLE:
1421
+ xm.mark_step()
1422
+
1423
+ # 9. Post-processing
1424
+ image = None
1425
+ text = None
1426
+ if mode == "joint":
1427
+ image_vae_latents, image_clip_latents, text_latents = self._split_joint(latents, height, width)
1428
+
1429
+ if not output_type == "latent":
1430
+ # Map latent VAE image back to pixel space
1431
+ image = self.vae.decode(image_vae_latents / self.vae.config.scaling_factor, return_dict=False)[0]
1432
+ else:
1433
+ image = image_vae_latents
1434
+
1435
+ text = self.decode_text_latents(text_latents, device)
1436
+ elif mode in ["text2img", "img"]:
1437
+ image_vae_latents, image_clip_latents = self._split(latents, height, width)
1438
+
1439
+ if not output_type == "latent":
1440
+ # Map latent VAE image back to pixel space
1441
+ image = self.vae.decode(image_vae_latents / self.vae.config.scaling_factor, return_dict=False)[0]
1442
+ else:
1443
+ image = image_vae_latents
1444
+ elif mode in ["img2text", "text"]:
1445
+ text_latents = latents
1446
+ text = self.decode_text_latents(text_latents, device)
1447
+
1448
+ self.maybe_free_model_hooks()
1449
+
1450
+ # 10. Postprocess the image, if necessary
1451
+ if image is not None:
1452
+ do_denormalize = [True] * image.shape[0]
1453
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1454
+
1455
+ # Offload last model to CPU
1456
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1457
+ self.final_offload_hook.offload()
1458
+
1459
+ if not return_dict:
1460
+ return (image, text)
1461
+
1462
+ return ImageTextPipelineOutput(images=image, text=text)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/visualcloze/__init__.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING
2
+
3
+ from ...utils import (
4
+ DIFFUSERS_SLOW_IMPORT,
5
+ OptionalDependencyNotAvailable,
6
+ _LazyModule,
7
+ get_objects_from_module,
8
+ is_torch_available,
9
+ is_transformers_available,
10
+ )
11
+
12
+
13
+ _dummy_objects = {}
14
+ _import_structure = {}
15
+
16
+
17
+ try:
18
+ if not (is_transformers_available() and is_torch_available()):
19
+ raise OptionalDependencyNotAvailable()
20
+ except OptionalDependencyNotAvailable:
21
+ from ...utils import dummy_torch_and_transformers_objects # noqa F403
22
+
23
+ _dummy_objects.update(get_objects_from_module(dummy_torch_and_transformers_objects))
24
+ else:
25
+ _import_structure["pipeline_visualcloze_combined"] = ["VisualClozePipeline"]
26
+ _import_structure["pipeline_visualcloze_generation"] = ["VisualClozeGenerationPipeline"]
27
+
28
+
29
+ if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
30
+ try:
31
+ if not (is_transformers_available() and is_torch_available()):
32
+ raise OptionalDependencyNotAvailable()
33
+
34
+ except OptionalDependencyNotAvailable:
35
+ from ...utils.dummy_torch_and_transformers_objects import *
36
+ else:
37
+ from .pipeline_visualcloze_combined import VisualClozePipeline
38
+ from .pipeline_visualcloze_generation import VisualClozeGenerationPipeline
39
+
40
+
41
+ else:
42
+ import sys
43
+
44
+ sys.modules[__name__] = _LazyModule(
45
+ __name__,
46
+ globals()["__file__"],
47
+ _import_structure,
48
+ module_spec=__spec__,
49
+ )
50
+
51
+ for name, value in _dummy_objects.items():
52
+ setattr(sys.modules[__name__], name, value)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_combined.py ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 VisualCloze team and 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
+ from typing import Any, Callable, Dict, List, Optional, Union
16
+
17
+ import torch
18
+ from PIL import Image
19
+ from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
20
+
21
+ from ...loaders import FluxLoraLoaderMixin, FromSingleFileMixin, TextualInversionLoaderMixin
22
+ from ...models.autoencoders import AutoencoderKL
23
+ from ...models.transformers import FluxTransformer2DModel
24
+ from ...schedulers import FlowMatchEulerDiscreteScheduler
25
+ from ...utils import is_torch_xla_available, logging, replace_example_docstring
26
+ from ..flux.pipeline_flux_fill import FluxFillPipeline as VisualClozeUpsamplingPipeline
27
+ from ..flux.pipeline_output import FluxPipelineOutput
28
+ from ..pipeline_utils import DiffusionPipeline
29
+ from .pipeline_visualcloze_generation import VisualClozeGenerationPipeline
30
+
31
+
32
+ if is_torch_xla_available():
33
+ XLA_AVAILABLE = True
34
+ else:
35
+ XLA_AVAILABLE = False
36
+
37
+
38
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
39
+
40
+ EXAMPLE_DOC_STRING = """
41
+ Examples:
42
+ ```python
43
+ >>> import torch
44
+ >>> from diffusers import VisualClozePipeline
45
+ >>> from diffusers.utils import load_image
46
+
47
+ >>> image_paths = [
48
+ ... # in-context examples
49
+ ... [
50
+ ... load_image(
51
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_mask.jpg"
52
+ ... ),
53
+ ... load_image(
54
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_image.jpg"
55
+ ... ),
56
+ ... ],
57
+ ... # query with the target image
58
+ ... [
59
+ ... load_image(
60
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_query_mask.jpg"
61
+ ... ),
62
+ ... None, # No image needed for the target image
63
+ ... ],
64
+ ... ]
65
+ >>> task_prompt = "In each row, a logical task is demonstrated to achieve [IMAGE2] an aesthetically pleasing photograph based on [IMAGE1] sam 2-generated masks with rich color coding."
66
+ >>> content_prompt = "Majestic photo of a golden eagle perched on a rocky outcrop in a mountainous landscape. The eagle is positioned in the right foreground, facing left, with its sharp beak and keen eyes prominently visible. Its plumage is a mix of dark brown and golden hues, with intricate feather details. The background features a soft-focus view of snow-capped mountains under a cloudy sky, creating a serene and grandiose atmosphere. The foreground includes rugged rocks and patches of green moss. Photorealistic, medium depth of field, soft natural lighting, cool color palette, high contrast, sharp focus on the eagle, blurred background, tranquil, majestic, wildlife photography."
67
+ >>> pipe = VisualClozePipeline.from_pretrained(
68
+ ... "VisualCloze/VisualClozePipeline-384", resolution=384, torch_dtype=torch.bfloat16
69
+ ... )
70
+ >>> pipe.to("cuda")
71
+
72
+ >>> image = pipe(
73
+ ... task_prompt=task_prompt,
74
+ ... content_prompt=content_prompt,
75
+ ... image=image_paths,
76
+ ... upsampling_width=1344,
77
+ ... upsampling_height=768,
78
+ ... upsampling_strength=0.4,
79
+ ... guidance_scale=30,
80
+ ... num_inference_steps=30,
81
+ ... max_sequence_length=512,
82
+ ... generator=torch.Generator("cpu").manual_seed(0),
83
+ ... ).images[0][0]
84
+ >>> image.save("visualcloze.png")
85
+ ```
86
+ """
87
+
88
+
89
+ class VisualClozePipeline(
90
+ DiffusionPipeline,
91
+ FluxLoraLoaderMixin,
92
+ FromSingleFileMixin,
93
+ TextualInversionLoaderMixin,
94
+ ):
95
+ r"""
96
+ The VisualCloze pipeline for image generation with visual context. Reference:
97
+ https://github.com/lzyhha/VisualCloze/tree/main. This pipeline is designed to generate images based on visual
98
+ in-context examples.
99
+
100
+ Args:
101
+ transformer ([`FluxTransformer2DModel`]):
102
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
103
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
104
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
105
+ vae ([`AutoencoderKL`]):
106
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
107
+ text_encoder ([`CLIPTextModel`]):
108
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
109
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
110
+ text_encoder_2 ([`T5EncoderModel`]):
111
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
112
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
113
+ tokenizer (`CLIPTokenizer`):
114
+ Tokenizer of class
115
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
116
+ tokenizer_2 (`T5TokenizerFast`):
117
+ Second Tokenizer of class
118
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
119
+ resolution (`int`, *optional*, defaults to 384):
120
+ The resolution of each image when concatenating images from the query and in-context examples.
121
+ """
122
+
123
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
124
+ _optional_components = []
125
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
126
+
127
+ def __init__(
128
+ self,
129
+ scheduler: FlowMatchEulerDiscreteScheduler,
130
+ vae: AutoencoderKL,
131
+ text_encoder: CLIPTextModel,
132
+ tokenizer: CLIPTokenizer,
133
+ text_encoder_2: T5EncoderModel,
134
+ tokenizer_2: T5TokenizerFast,
135
+ transformer: FluxTransformer2DModel,
136
+ resolution: int = 384,
137
+ ):
138
+ super().__init__()
139
+
140
+ self.register_modules(
141
+ vae=vae,
142
+ text_encoder=text_encoder,
143
+ text_encoder_2=text_encoder_2,
144
+ tokenizer=tokenizer,
145
+ tokenizer_2=tokenizer_2,
146
+ transformer=transformer,
147
+ scheduler=scheduler,
148
+ )
149
+
150
+ self.generation_pipe = VisualClozeGenerationPipeline(
151
+ vae=vae,
152
+ text_encoder=text_encoder,
153
+ text_encoder_2=text_encoder_2,
154
+ tokenizer=tokenizer,
155
+ tokenizer_2=tokenizer_2,
156
+ transformer=transformer,
157
+ scheduler=scheduler,
158
+ resolution=resolution,
159
+ )
160
+ self.upsampling_pipe = VisualClozeUpsamplingPipeline(
161
+ vae=vae,
162
+ text_encoder=text_encoder,
163
+ text_encoder_2=text_encoder_2,
164
+ tokenizer=tokenizer,
165
+ tokenizer_2=tokenizer_2,
166
+ transformer=transformer,
167
+ scheduler=scheduler,
168
+ )
169
+
170
+ def check_inputs(
171
+ self,
172
+ image,
173
+ task_prompt,
174
+ content_prompt,
175
+ upsampling_height,
176
+ upsampling_width,
177
+ strength,
178
+ prompt_embeds=None,
179
+ pooled_prompt_embeds=None,
180
+ callback_on_step_end_tensor_inputs=None,
181
+ max_sequence_length=None,
182
+ ):
183
+ if strength < 0 or strength > 1:
184
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
185
+
186
+ if upsampling_height is not None and upsampling_height % (self.vae_scale_factor * 2) != 0:
187
+ logger.warning(
188
+ f"`upsampling_height`has to be divisible by {self.vae_scale_factor * 2} but are {upsampling_height}. Dimensions will be resized accordingly"
189
+ )
190
+ if upsampling_width is not None and upsampling_width % (self.vae_scale_factor * 2) != 0:
191
+ logger.warning(
192
+ f"`upsampling_width` have to be divisible by {self.vae_scale_factor * 2} but are {upsampling_width}. Dimensions will be resized accordingly"
193
+ )
194
+
195
+ if callback_on_step_end_tensor_inputs is not None and not all(
196
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
197
+ ):
198
+ raise ValueError(
199
+ 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]}"
200
+ )
201
+
202
+ # Validate prompt inputs
203
+ if (task_prompt is not None or content_prompt is not None) and prompt_embeds is not None:
204
+ raise ValueError("Cannot provide both text `task_prompt` + `content_prompt` and `prompt_embeds`. ")
205
+
206
+ if task_prompt is None and content_prompt is None and prompt_embeds is None:
207
+ raise ValueError("Must provide either `task_prompt` + `content_prompt` or pre-computed `prompt_embeds`. ")
208
+
209
+ # Validate prompt types and consistency
210
+ if task_prompt is None:
211
+ raise ValueError("`task_prompt` is missing.")
212
+
213
+ if task_prompt is not None and not isinstance(task_prompt, (str, list)):
214
+ raise ValueError(f"`task_prompt` must be str or list, got {type(task_prompt)}")
215
+
216
+ if content_prompt is not None and not isinstance(content_prompt, (str, list)):
217
+ raise ValueError(f"`content_prompt` must be str or list, got {type(content_prompt)}")
218
+
219
+ if isinstance(task_prompt, list) or isinstance(content_prompt, list):
220
+ if not isinstance(task_prompt, list) or not isinstance(content_prompt, list):
221
+ raise ValueError(
222
+ f"`task_prompt` and `content_prompt` must both be lists, or both be of type str or None, "
223
+ f"got {type(task_prompt)} and {type(content_prompt)}"
224
+ )
225
+ if len(content_prompt) != len(task_prompt):
226
+ raise ValueError("`task_prompt` and `content_prompt` must have the same length whe they are lists.")
227
+
228
+ for sample in image:
229
+ if not isinstance(sample, list) or not isinstance(sample[0], list):
230
+ raise ValueError("Each sample in the batch must have a 2D list of images.")
231
+ if len({len(row) for row in sample}) != 1:
232
+ raise ValueError("Each in-context example and query should contain the same number of images.")
233
+ if not any(img is None for img in sample[-1]):
234
+ raise ValueError("There are no targets in the query, which should be represented as None.")
235
+ for row in sample[:-1]:
236
+ if any(img is None for img in row):
237
+ raise ValueError("Images are missing in in-context examples.")
238
+
239
+ # Validate embeddings
240
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
241
+ raise ValueError(
242
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
243
+ )
244
+
245
+ # Validate sequence length
246
+ if max_sequence_length is not None and max_sequence_length > 512:
247
+ raise ValueError(f"max_sequence_length cannot exceed 512, got {max_sequence_length}")
248
+
249
+ @torch.no_grad()
250
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
251
+ def __call__(
252
+ self,
253
+ task_prompt: Union[str, List[str]] = None,
254
+ content_prompt: Union[str, List[str]] = None,
255
+ image: Optional[torch.FloatTensor] = None,
256
+ upsampling_height: Optional[int] = None,
257
+ upsampling_width: Optional[int] = None,
258
+ num_inference_steps: int = 50,
259
+ sigmas: Optional[List[float]] = None,
260
+ guidance_scale: float = 30.0,
261
+ num_images_per_prompt: Optional[int] = 1,
262
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
263
+ latents: Optional[torch.FloatTensor] = None,
264
+ prompt_embeds: Optional[torch.FloatTensor] = None,
265
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
266
+ output_type: Optional[str] = "pil",
267
+ return_dict: bool = True,
268
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
269
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
270
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
271
+ max_sequence_length: int = 512,
272
+ upsampling_strength: float = 1.0,
273
+ ):
274
+ r"""
275
+ Function invoked when calling the VisualCloze pipeline for generation.
276
+
277
+ Args:
278
+ task_prompt (`str` or `List[str]`, *optional*):
279
+ The prompt or prompts to define the task intention.
280
+ content_prompt (`str` or `List[str]`, *optional*):
281
+ The prompt or prompts to define the content or caption of the target image to be generated.
282
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
283
+ `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
284
+ numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
285
+ or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
286
+ list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)`.
287
+ upsampling_height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
288
+ The height in pixels of the generated image (i.e., output image) after upsampling via SDEdit. By
289
+ default, the image is upsampled by a factor of three, and the base resolution is determined by the
290
+ resolution parameter of the pipeline. When only one of `upsampling_height` or `upsampling_width` is
291
+ specified, the other will be automatically set based on the aspect ratio.
292
+ upsampling_width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
293
+ The width in pixels of the generated image (i.e., output image) after upsampling via SDEdit. By
294
+ default, the image is upsampled by a factor of three, and the base resolution is determined by the
295
+ resolution parameter of the pipeline. When only one of `upsampling_height` or `upsampling_width` is
296
+ specified, the other will be automatically set based on the aspect ratio.
297
+ num_inference_steps (`int`, *optional*, defaults to 50):
298
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
299
+ expense of slower inference.
300
+ sigmas (`List[float]`, *optional*):
301
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
302
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
303
+ will be used.
304
+ guidance_scale (`float`, *optional*, defaults to 30.0):
305
+ Guidance scale as defined in [Classifier-Free Diffusion
306
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
307
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
308
+ `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
309
+ the text `prompt`, usually at the expense of lower image quality.
310
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
311
+ The number of images to generate per prompt.
312
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
313
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
314
+ to make generation deterministic.
315
+ latents (`torch.FloatTensor`, *optional*):
316
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
317
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
318
+ tensor will be generated by sampling using the supplied random `generator`.
319
+ prompt_embeds (`torch.FloatTensor`, *optional*):
320
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
321
+ provided, text embeddings will be generated from `prompt` input argument.
322
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
323
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
324
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
325
+ output_type (`str`, *optional*, defaults to `"pil"`):
326
+ The output format of the generate image. Choose between
327
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
328
+ return_dict (`bool`, *optional*, defaults to `True`):
329
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
330
+ joint_attention_kwargs (`dict`, *optional*):
331
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
332
+ `self.processor` in
333
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
334
+ callback_on_step_end (`Callable`, *optional*):
335
+ A function that calls at the end of each denoising steps during the inference. The function is called
336
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
337
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
338
+ `callback_on_step_end_tensor_inputs`.
339
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
340
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
341
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
342
+ `._callback_tensor_inputs` attribute of your pipeline class.
343
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
344
+ upsampling_strength (`float`, *optional*, defaults to 1.0):
345
+ Indicates extent to transform the reference `image` when upsampling the results. Must be between 0 and
346
+ 1. The generated image is used as a starting point and more noise is added the higher the
347
+ `upsampling_strength`. The number of denoising steps depends on the amount of noise initially added.
348
+ When `upsampling_strength` is 1, added noise is maximum and the denoising process runs for the full
349
+ number of iterations specified in `num_inference_steps`. A value of 0 skips the upsampling step and
350
+ output the results at the resolution of `self.resolution`.
351
+
352
+ Examples:
353
+
354
+ Returns:
355
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
356
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
357
+ images.
358
+ """
359
+
360
+ generation_output = self.generation_pipe(
361
+ task_prompt=task_prompt,
362
+ content_prompt=content_prompt,
363
+ image=image,
364
+ num_inference_steps=num_inference_steps,
365
+ sigmas=sigmas,
366
+ guidance_scale=guidance_scale,
367
+ num_images_per_prompt=num_images_per_prompt,
368
+ generator=generator,
369
+ latents=latents,
370
+ prompt_embeds=prompt_embeds,
371
+ pooled_prompt_embeds=pooled_prompt_embeds,
372
+ joint_attention_kwargs=joint_attention_kwargs,
373
+ callback_on_step_end=callback_on_step_end,
374
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
375
+ max_sequence_length=max_sequence_length,
376
+ output_type=output_type if upsampling_strength == 0 else "pil",
377
+ )
378
+ if upsampling_strength == 0:
379
+ if not return_dict:
380
+ return (generation_output,)
381
+
382
+ return FluxPipelineOutput(images=generation_output)
383
+
384
+ # Upsampling the generated images
385
+ # 1. Prepare the input images and prompts
386
+ if not isinstance(content_prompt, (list)):
387
+ content_prompt = [content_prompt]
388
+ n_target_per_sample = []
389
+ upsampling_image = []
390
+ upsampling_mask = []
391
+ upsampling_prompt = []
392
+ upsampling_generator = generator if isinstance(generator, (torch.Generator,)) else []
393
+ for i in range(len(generation_output.images)):
394
+ n_target_per_sample.append(len(generation_output.images[i]))
395
+ for image in generation_output.images[i]:
396
+ upsampling_image.append(image)
397
+ upsampling_mask.append(Image.new("RGB", image.size, (255, 255, 255)))
398
+ upsampling_prompt.append(
399
+ content_prompt[i % len(content_prompt)] if content_prompt[i % len(content_prompt)] else ""
400
+ )
401
+ if not isinstance(generator, (torch.Generator,)):
402
+ upsampling_generator.append(generator[i % len(content_prompt)])
403
+
404
+ # 2. Apply the denosing loop
405
+ upsampling_output = self.upsampling_pipe(
406
+ prompt=upsampling_prompt,
407
+ image=upsampling_image,
408
+ mask_image=upsampling_mask,
409
+ height=upsampling_height,
410
+ width=upsampling_width,
411
+ strength=upsampling_strength,
412
+ num_inference_steps=num_inference_steps,
413
+ sigmas=sigmas,
414
+ guidance_scale=guidance_scale,
415
+ generator=upsampling_generator,
416
+ output_type=output_type,
417
+ joint_attention_kwargs=joint_attention_kwargs,
418
+ callback_on_step_end=callback_on_step_end,
419
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
420
+ max_sequence_length=max_sequence_length,
421
+ )
422
+ image = upsampling_output.images
423
+
424
+ output = []
425
+ if output_type == "pil":
426
+ # Each sample in the batch may have multiple output images. When returning as PIL images,
427
+ # these images cannot be concatenated. Therefore, for each sample,
428
+ # a list is used to represent all the output images.
429
+ output = []
430
+ start = 0
431
+ for n in n_target_per_sample:
432
+ output.append(image[start : start + n])
433
+ start += n
434
+ else:
435
+ output = image
436
+
437
+ if not return_dict:
438
+ return (output,)
439
+
440
+ return FluxPipelineOutput(images=output)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py ADDED
@@ -0,0 +1,977 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 VisualCloze team and 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
+ from typing import Any, Callable, Dict, List, Optional, Union
16
+
17
+ import numpy as np
18
+ import torch
19
+ from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
20
+
21
+ from ...loaders import FluxLoraLoaderMixin, FromSingleFileMixin, TextualInversionLoaderMixin
22
+ from ...models.autoencoders import AutoencoderKL
23
+ from ...models.transformers import FluxTransformer2DModel
24
+ from ...schedulers import FlowMatchEulerDiscreteScheduler
25
+ from ...utils import (
26
+ USE_PEFT_BACKEND,
27
+ deprecate,
28
+ is_torch_xla_available,
29
+ logging,
30
+ replace_example_docstring,
31
+ scale_lora_layers,
32
+ unscale_lora_layers,
33
+ )
34
+ from ...utils.torch_utils import randn_tensor
35
+ from ..flux.pipeline_flux_fill import calculate_shift, retrieve_latents, retrieve_timesteps
36
+ from ..flux.pipeline_output import FluxPipelineOutput
37
+ from ..pipeline_utils import DiffusionPipeline
38
+ from .visualcloze_utils import VisualClozeProcessor
39
+
40
+
41
+ if is_torch_xla_available():
42
+ import torch_xla.core.xla_model as xm
43
+
44
+ XLA_AVAILABLE = True
45
+ else:
46
+ XLA_AVAILABLE = False
47
+
48
+
49
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
50
+
51
+
52
+ EXAMPLE_DOC_STRING = """
53
+ Examples:
54
+ ```python
55
+ >>> import torch
56
+ >>> from diffusers import VisualClozeGenerationPipeline, FluxFillPipeline as VisualClozeUpsamplingPipeline
57
+ >>> from diffusers.utils import load_image
58
+ >>> from PIL import Image
59
+
60
+ >>> image_paths = [
61
+ ... # in-context examples
62
+ ... [
63
+ ... load_image(
64
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_mask.jpg"
65
+ ... ),
66
+ ... load_image(
67
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_image.jpg"
68
+ ... ),
69
+ ... ],
70
+ ... # query with the target image
71
+ ... [
72
+ ... load_image(
73
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_query_mask.jpg"
74
+ ... ),
75
+ ... None, # No image needed for the target image
76
+ ... ],
77
+ ... ]
78
+ >>> task_prompt = "In each row, a logical task is demonstrated to achieve [IMAGE2] an aesthetically pleasing photograph based on [IMAGE1] sam 2-generated masks with rich color coding."
79
+ >>> content_prompt = "Majestic photo of a golden eagle perched on a rocky outcrop in a mountainous landscape. The eagle is positioned in the right foreground, facing left, with its sharp beak and keen eyes prominently visible. Its plumage is a mix of dark brown and golden hues, with intricate feather details. The background features a soft-focus view of snow-capped mountains under a cloudy sky, creating a serene and grandiose atmosphere. The foreground includes rugged rocks and patches of green moss. Photorealistic, medium depth of field, soft natural lighting, cool color palette, high contrast, sharp focus on the eagle, blurred background, tranquil, majestic, wildlife photography."
80
+ >>> pipe = VisualClozeGenerationPipeline.from_pretrained(
81
+ ... "VisualCloze/VisualClozePipeline-384", resolution=384, torch_dtype=torch.bfloat16
82
+ ... )
83
+ >>> pipe.to("cuda")
84
+
85
+ >>> image = pipe(
86
+ ... task_prompt=task_prompt,
87
+ ... content_prompt=content_prompt,
88
+ ... image=image_paths,
89
+ ... guidance_scale=30,
90
+ ... num_inference_steps=30,
91
+ ... max_sequence_length=512,
92
+ ... generator=torch.Generator("cpu").manual_seed(0),
93
+ ... ).images[0][0]
94
+
95
+ >>> # optional, upsampling the generated image
96
+ >>> pipe_upsample = VisualClozeUpsamplingPipeline.from_pipe(pipe)
97
+ >>> pipe_upsample.to("cuda")
98
+
99
+ >>> mask_image = Image.new("RGB", image.size, (255, 255, 255))
100
+
101
+ >>> image = pipe_upsample(
102
+ ... image=image,
103
+ ... mask_image=mask_image,
104
+ ... prompt=content_prompt,
105
+ ... width=1344,
106
+ ... height=768,
107
+ ... strength=0.4,
108
+ ... guidance_scale=30,
109
+ ... num_inference_steps=30,
110
+ ... max_sequence_length=512,
111
+ ... generator=torch.Generator("cpu").manual_seed(0),
112
+ ... ).images[0]
113
+
114
+ >>> image.save("visualcloze.png")
115
+ ```
116
+ """
117
+
118
+
119
+ class VisualClozeGenerationPipeline(
120
+ DiffusionPipeline,
121
+ FluxLoraLoaderMixin,
122
+ FromSingleFileMixin,
123
+ TextualInversionLoaderMixin,
124
+ ):
125
+ r"""
126
+ The VisualCloze pipeline for image generation with visual context. Reference:
127
+ https://github.com/lzyhha/VisualCloze/tree/main This pipeline is designed to generate images based on visual
128
+ in-context examples.
129
+
130
+ Args:
131
+ transformer ([`FluxTransformer2DModel`]):
132
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
133
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
134
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
135
+ vae ([`AutoencoderKL`]):
136
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
137
+ text_encoder ([`CLIPTextModel`]):
138
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
139
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
140
+ text_encoder_2 ([`T5EncoderModel`]):
141
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
142
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
143
+ tokenizer (`CLIPTokenizer`):
144
+ Tokenizer of class
145
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
146
+ tokenizer_2 (`T5TokenizerFast`):
147
+ Second Tokenizer of class
148
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
149
+ resolution (`int`, *optional*, defaults to 384):
150
+ The resolution of each image when concatenating images from the query and in-context examples.
151
+ """
152
+
153
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
154
+ _optional_components = []
155
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
156
+
157
+ def __init__(
158
+ self,
159
+ scheduler: FlowMatchEulerDiscreteScheduler,
160
+ vae: AutoencoderKL,
161
+ text_encoder: CLIPTextModel,
162
+ tokenizer: CLIPTokenizer,
163
+ text_encoder_2: T5EncoderModel,
164
+ tokenizer_2: T5TokenizerFast,
165
+ transformer: FluxTransformer2DModel,
166
+ resolution: int = 384,
167
+ ):
168
+ super().__init__()
169
+
170
+ self.register_modules(
171
+ vae=vae,
172
+ text_encoder=text_encoder,
173
+ text_encoder_2=text_encoder_2,
174
+ tokenizer=tokenizer,
175
+ tokenizer_2=tokenizer_2,
176
+ transformer=transformer,
177
+ scheduler=scheduler,
178
+ )
179
+ self.resolution = resolution
180
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
181
+ # Flux latents are turned into 2x2 patches and packed. This means the latent width and height has to be divisible
182
+ # by the patch size. So the vae scale factor is multiplied by the patch size to account for this
183
+ self.latent_channels = self.vae.config.latent_channels if getattr(self, "vae", None) else 16
184
+ self.image_processor = VisualClozeProcessor(
185
+ vae_scale_factor=self.vae_scale_factor * 2, vae_latent_channels=self.latent_channels, resolution=resolution
186
+ )
187
+ self.tokenizer_max_length = (
188
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
189
+ )
190
+ self.default_sample_size = 128
191
+
192
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_t5_prompt_embeds
193
+ def _get_t5_prompt_embeds(
194
+ self,
195
+ prompt: Union[str, List[str]] = None,
196
+ num_images_per_prompt: int = 1,
197
+ max_sequence_length: int = 512,
198
+ device: Optional[torch.device] = None,
199
+ dtype: Optional[torch.dtype] = None,
200
+ ):
201
+ device = device or self._execution_device
202
+ dtype = dtype or self.text_encoder.dtype
203
+
204
+ prompt = [prompt] if isinstance(prompt, str) else prompt
205
+ batch_size = len(prompt)
206
+
207
+ if isinstance(self, TextualInversionLoaderMixin):
208
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer_2)
209
+
210
+ text_inputs = self.tokenizer_2(
211
+ prompt,
212
+ padding="max_length",
213
+ max_length=max_sequence_length,
214
+ truncation=True,
215
+ return_length=False,
216
+ return_overflowing_tokens=False,
217
+ return_tensors="pt",
218
+ )
219
+ text_input_ids = text_inputs.input_ids
220
+ untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
221
+
222
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
223
+ removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
224
+ logger.warning(
225
+ "The following part of your input was truncated because `max_sequence_length` is set to "
226
+ f" {max_sequence_length} tokens: {removed_text}"
227
+ )
228
+
229
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
230
+
231
+ dtype = self.text_encoder_2.dtype
232
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
233
+
234
+ _, seq_len, _ = prompt_embeds.shape
235
+
236
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
237
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
238
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
239
+
240
+ return prompt_embeds
241
+
242
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_clip_prompt_embeds
243
+ def _get_clip_prompt_embeds(
244
+ self,
245
+ prompt: Union[str, List[str]],
246
+ num_images_per_prompt: int = 1,
247
+ device: Optional[torch.device] = None,
248
+ ):
249
+ device = device or self._execution_device
250
+
251
+ prompt = [prompt] if isinstance(prompt, str) else prompt
252
+ batch_size = len(prompt)
253
+
254
+ if isinstance(self, TextualInversionLoaderMixin):
255
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
256
+
257
+ text_inputs = self.tokenizer(
258
+ prompt,
259
+ padding="max_length",
260
+ max_length=self.tokenizer_max_length,
261
+ truncation=True,
262
+ return_overflowing_tokens=False,
263
+ return_length=False,
264
+ return_tensors="pt",
265
+ )
266
+
267
+ text_input_ids = text_inputs.input_ids
268
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
269
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
270
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
271
+ logger.warning(
272
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
273
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
274
+ )
275
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
276
+
277
+ # Use pooled output of CLIPTextModel
278
+ prompt_embeds = prompt_embeds.pooler_output
279
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
280
+
281
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
282
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
283
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
284
+
285
+ return prompt_embeds
286
+
287
+ # Modified from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.encode_prompt
288
+ def encode_prompt(
289
+ self,
290
+ layout_prompt: Union[str, List[str]],
291
+ task_prompt: Union[str, List[str]],
292
+ content_prompt: Union[str, List[str]],
293
+ device: Optional[torch.device] = None,
294
+ num_images_per_prompt: int = 1,
295
+ prompt_embeds: Optional[torch.FloatTensor] = None,
296
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
297
+ max_sequence_length: int = 512,
298
+ lora_scale: Optional[float] = None,
299
+ ):
300
+ r"""
301
+
302
+ Args:
303
+ layout_prompt (`str` or `List[str]`, *optional*):
304
+ The prompt or prompts to define the number of in-context examples and the number of images involved in
305
+ the task.
306
+ task_prompt (`str` or `List[str]`, *optional*):
307
+ The prompt or prompts to define the task intention.
308
+ content_prompt (`str` or `List[str]`, *optional*):
309
+ The prompt or prompts to define the content or caption of the target image to be generated.
310
+ device: (`torch.device`):
311
+ torch device
312
+ num_images_per_prompt (`int`):
313
+ number of images that should be generated per prompt
314
+ prompt_embeds (`torch.FloatTensor`, *optional*):
315
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
316
+ provided, text embeddings will be generated from `prompt` input argument.
317
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
318
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
319
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
320
+ lora_scale (`float`, *optional*):
321
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
322
+ """
323
+ device = device or self._execution_device
324
+
325
+ # set lora scale so that monkey patched LoRA
326
+ # function of text encoder can correctly access it
327
+ if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
328
+ self._lora_scale = lora_scale
329
+
330
+ # dynamically adjust the LoRA scale
331
+ if self.text_encoder is not None and USE_PEFT_BACKEND:
332
+ scale_lora_layers(self.text_encoder, lora_scale)
333
+ if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
334
+ scale_lora_layers(self.text_encoder_2, lora_scale)
335
+
336
+ if isinstance(layout_prompt, str):
337
+ layout_prompt = [layout_prompt]
338
+ task_prompt = [task_prompt]
339
+ content_prompt = [content_prompt]
340
+
341
+ def _preprocess(prompt, content=False):
342
+ if prompt is not None:
343
+ return f"The last image of the last row depicts: {prompt}" if content else prompt
344
+ else:
345
+ return ""
346
+
347
+ prompt = [
348
+ f"{_preprocess(layout_prompt[i])} {_preprocess(task_prompt[i])} {_preprocess(content_prompt[i], content=True)}".strip()
349
+ for i in range(len(layout_prompt))
350
+ ]
351
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
352
+ prompt=prompt,
353
+ device=device,
354
+ num_images_per_prompt=num_images_per_prompt,
355
+ )
356
+ prompt_embeds = self._get_t5_prompt_embeds(
357
+ prompt=prompt,
358
+ num_images_per_prompt=num_images_per_prompt,
359
+ max_sequence_length=max_sequence_length,
360
+ device=device,
361
+ )
362
+
363
+ if self.text_encoder is not None:
364
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
365
+ # Retrieve the original scale by scaling back the LoRA layers
366
+ unscale_lora_layers(self.text_encoder, lora_scale)
367
+
368
+ if self.text_encoder_2 is not None:
369
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
370
+ # Retrieve the original scale by scaling back the LoRA layers
371
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
372
+
373
+ dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
374
+ text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
375
+
376
+ return prompt_embeds, pooled_prompt_embeds, text_ids
377
+
378
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_inpaint.StableDiffusion3InpaintPipeline._encode_vae_image
379
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
380
+ if isinstance(generator, list):
381
+ image_latents = [
382
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
383
+ for i in range(image.shape[0])
384
+ ]
385
+ image_latents = torch.cat(image_latents, dim=0)
386
+ else:
387
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
388
+
389
+ image_latents = (image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
390
+
391
+ return image_latents
392
+
393
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_img2img.StableDiffusion3Img2ImgPipeline.get_timesteps
394
+ def get_timesteps(self, num_inference_steps, strength, device):
395
+ # get the original timestep using init_timestep
396
+ init_timestep = min(num_inference_steps * strength, num_inference_steps)
397
+
398
+ t_start = int(max(num_inference_steps - init_timestep, 0))
399
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
400
+ if hasattr(self.scheduler, "set_begin_index"):
401
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
402
+
403
+ return timesteps, num_inference_steps - t_start
404
+
405
+ def check_inputs(
406
+ self,
407
+ image,
408
+ task_prompt,
409
+ content_prompt,
410
+ prompt_embeds=None,
411
+ pooled_prompt_embeds=None,
412
+ callback_on_step_end_tensor_inputs=None,
413
+ max_sequence_length=None,
414
+ ):
415
+ if callback_on_step_end_tensor_inputs is not None and not all(
416
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
417
+ ):
418
+ raise ValueError(
419
+ 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]}"
420
+ )
421
+
422
+ # Validate prompt inputs
423
+ if (task_prompt is not None or content_prompt is not None) and prompt_embeds is not None:
424
+ raise ValueError("Cannot provide both text `task_prompt` + `content_prompt` and `prompt_embeds`. ")
425
+
426
+ if task_prompt is None and content_prompt is None and prompt_embeds is None:
427
+ raise ValueError("Must provide either `task_prompt` + `content_prompt` or pre-computed `prompt_embeds`. ")
428
+
429
+ # Validate prompt types and consistency
430
+ if task_prompt is None:
431
+ raise ValueError("`task_prompt` is missing.")
432
+
433
+ if task_prompt is not None and not isinstance(task_prompt, (str, list)):
434
+ raise ValueError(f"`task_prompt` must be str or list, got {type(task_prompt)}")
435
+
436
+ if content_prompt is not None and not isinstance(content_prompt, (str, list)):
437
+ raise ValueError(f"`content_prompt` must be str or list, got {type(content_prompt)}")
438
+
439
+ if isinstance(task_prompt, list) or isinstance(content_prompt, list):
440
+ if not isinstance(task_prompt, list) or not isinstance(content_prompt, list):
441
+ raise ValueError(
442
+ f"`task_prompt` and `content_prompt` must both be lists, or both be of type str or None, "
443
+ f"got {type(task_prompt)} and {type(content_prompt)}"
444
+ )
445
+ if len(content_prompt) != len(task_prompt):
446
+ raise ValueError("`task_prompt` and `content_prompt` must have the same length whe they are lists.")
447
+
448
+ for sample in image:
449
+ if not isinstance(sample, list) or not isinstance(sample[0], list):
450
+ raise ValueError("Each sample in the batch must have a 2D list of images.")
451
+ if len({len(row) for row in sample}) != 1:
452
+ raise ValueError("Each in-context example and query should contain the same number of images.")
453
+ if not any(img is None for img in sample[-1]):
454
+ raise ValueError("There are no targets in the query, which should be represented as None.")
455
+ for row in sample[:-1]:
456
+ if any(img is None for img in row):
457
+ raise ValueError("Images are missing in in-context examples.")
458
+
459
+ # Validate embeddings
460
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
461
+ raise ValueError(
462
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
463
+ )
464
+
465
+ # Validate sequence length
466
+ if max_sequence_length is not None and max_sequence_length > 512:
467
+ raise ValueError(f"max_sequence_length cannot exceed 512, got {max_sequence_length}")
468
+
469
+ @staticmethod
470
+ def _prepare_latent_image_ids(image, vae_scale_factor, device, dtype):
471
+ latent_image_ids = []
472
+
473
+ for idx, img in enumerate(image, start=1):
474
+ img = img.squeeze(0)
475
+ channels, height, width = img.shape
476
+
477
+ num_patches_h = height // vae_scale_factor // 2
478
+ num_patches_w = width // vae_scale_factor // 2
479
+
480
+ patch_ids = torch.zeros(num_patches_h, num_patches_w, 3, device=device, dtype=dtype)
481
+ patch_ids[..., 0] = idx
482
+ patch_ids[..., 1] = torch.arange(num_patches_h, device=device, dtype=dtype)[:, None]
483
+ patch_ids[..., 2] = torch.arange(num_patches_w, device=device, dtype=dtype)[None, :]
484
+
485
+ patch_ids = patch_ids.reshape(-1, 3)
486
+ latent_image_ids.append(patch_ids)
487
+
488
+ return torch.cat(latent_image_ids, dim=0)
489
+
490
+ @staticmethod
491
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._pack_latents
492
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
493
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
494
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
495
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
496
+
497
+ return latents
498
+
499
+ @staticmethod
500
+ def _unpack_latents(latents, sizes, vae_scale_factor):
501
+ batch_size, num_patches, channels = latents.shape
502
+
503
+ start = 0
504
+ unpacked_latents = []
505
+ for i in range(len(sizes)):
506
+ cur_size = sizes[i]
507
+ height = cur_size[0][0] // vae_scale_factor
508
+ width = sum([size[1] for size in cur_size]) // vae_scale_factor
509
+
510
+ end = start + (height * width) // 4
511
+
512
+ cur_latents = latents[:, start:end]
513
+ cur_latents = cur_latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2)
514
+ cur_latents = cur_latents.permute(0, 3, 1, 4, 2, 5)
515
+ cur_latents = cur_latents.reshape(batch_size, channels // (2 * 2), height, width)
516
+
517
+ unpacked_latents.append(cur_latents)
518
+
519
+ start = end
520
+
521
+ return unpacked_latents
522
+
523
+ def enable_vae_slicing(self):
524
+ r"""
525
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
526
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
527
+ """
528
+ depr_message = f"Calling `enable_vae_slicing()` on a `{self.__class__.__name__}` is deprecated and this method will be removed in a future version. Please use `pipe.vae.enable_slicing()`."
529
+ deprecate(
530
+ "enable_vae_slicing",
531
+ "0.40.0",
532
+ depr_message,
533
+ )
534
+ self.vae.enable_slicing()
535
+
536
+ def disable_vae_slicing(self):
537
+ r"""
538
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
539
+ computing decoding in one step.
540
+ """
541
+ depr_message = f"Calling `disable_vae_slicing()` on a `{self.__class__.__name__}` is deprecated and this method will be removed in a future version. Please use `pipe.vae.disable_slicing()`."
542
+ deprecate(
543
+ "disable_vae_slicing",
544
+ "0.40.0",
545
+ depr_message,
546
+ )
547
+ self.vae.disable_slicing()
548
+
549
+ def enable_vae_tiling(self):
550
+ r"""
551
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
552
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
553
+ processing larger images.
554
+ """
555
+ depr_message = f"Calling `enable_vae_tiling()` on a `{self.__class__.__name__}` is deprecated and this method will be removed in a future version. Please use `pipe.vae.enable_tiling()`."
556
+ deprecate(
557
+ "enable_vae_tiling",
558
+ "0.40.0",
559
+ depr_message,
560
+ )
561
+ self.vae.enable_tiling()
562
+
563
+ def disable_vae_tiling(self):
564
+ r"""
565
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
566
+ computing decoding in one step.
567
+ """
568
+ depr_message = f"Calling `disable_vae_tiling()` on a `{self.__class__.__name__}` is deprecated and this method will be removed in a future version. Please use `pipe.vae.disable_tiling()`."
569
+ deprecate(
570
+ "disable_vae_tiling",
571
+ "0.40.0",
572
+ depr_message,
573
+ )
574
+ self.vae.disable_tiling()
575
+
576
+ def _prepare_latents(self, image, mask, gen, vae_scale_factor, device, dtype):
577
+ """Helper function to prepare latents for a single batch."""
578
+ # Concatenate images and masks along width dimension
579
+ image = [torch.cat(img, dim=3).to(device=device, dtype=dtype) for img in image]
580
+ mask = [torch.cat(m, dim=3).to(device=device, dtype=dtype) for m in mask]
581
+
582
+ # Generate latent image IDs
583
+ latent_image_ids = self._prepare_latent_image_ids(image, vae_scale_factor, device, dtype)
584
+
585
+ # For initial encoding, use actual images
586
+ image_latent = [self._encode_vae_image(img, gen) for img in image]
587
+ masked_image_latent = [img.clone() for img in image_latent]
588
+
589
+ for i in range(len(image_latent)):
590
+ # Rearrange latents and masks for patch processing
591
+ num_channels_latents, height, width = image_latent[i].shape[1:]
592
+ image_latent[i] = self._pack_latents(image_latent[i], 1, num_channels_latents, height, width)
593
+ masked_image_latent[i] = self._pack_latents(masked_image_latent[i], 1, num_channels_latents, height, width)
594
+
595
+ # Rearrange masks for patch processing
596
+ num_channels_latents, height, width = mask[i].shape[1:]
597
+ mask[i] = mask[i].view(
598
+ 1,
599
+ num_channels_latents,
600
+ height // vae_scale_factor,
601
+ vae_scale_factor,
602
+ width // vae_scale_factor,
603
+ vae_scale_factor,
604
+ )
605
+ mask[i] = mask[i].permute(0, 1, 3, 5, 2, 4)
606
+ mask[i] = mask[i].reshape(
607
+ 1,
608
+ num_channels_latents * (vae_scale_factor**2),
609
+ height // vae_scale_factor,
610
+ width // vae_scale_factor,
611
+ )
612
+ mask[i] = self._pack_latents(
613
+ mask[i],
614
+ 1,
615
+ num_channels_latents * (vae_scale_factor**2),
616
+ height // vae_scale_factor,
617
+ width // vae_scale_factor,
618
+ )
619
+
620
+ # Concatenate along batch dimension
621
+ image_latent = torch.cat(image_latent, dim=1)
622
+ masked_image_latent = torch.cat(masked_image_latent, dim=1)
623
+ mask = torch.cat(mask, dim=1)
624
+
625
+ return image_latent, masked_image_latent, mask, latent_image_ids
626
+
627
+ def prepare_latents(
628
+ self,
629
+ input_image,
630
+ input_mask,
631
+ timestep,
632
+ batch_size,
633
+ dtype,
634
+ device,
635
+ generator,
636
+ vae_scale_factor,
637
+ ):
638
+ if isinstance(generator, list) and len(generator) != batch_size:
639
+ raise ValueError(
640
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
641
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
642
+ )
643
+
644
+ # Process each batch
645
+ masked_image_latents = []
646
+ image_latents = []
647
+ masks = []
648
+ latent_image_ids = []
649
+
650
+ for i in range(len(input_image)):
651
+ _image_latent, _masked_image_latent, _mask, _latent_image_ids = self._prepare_latents(
652
+ input_image[i],
653
+ input_mask[i],
654
+ generator if isinstance(generator, torch.Generator) else generator[i],
655
+ vae_scale_factor,
656
+ device,
657
+ dtype,
658
+ )
659
+ masked_image_latents.append(_masked_image_latent)
660
+ image_latents.append(_image_latent)
661
+ masks.append(_mask)
662
+ latent_image_ids.append(_latent_image_ids)
663
+
664
+ # Concatenate all batches
665
+ masked_image_latents = torch.cat(masked_image_latents, dim=0)
666
+ image_latents = torch.cat(image_latents, dim=0)
667
+ masks = torch.cat(masks, dim=0)
668
+
669
+ # Handle batch size expansion
670
+ if batch_size > masked_image_latents.shape[0]:
671
+ if batch_size % masked_image_latents.shape[0] == 0:
672
+ # Expand batches by repeating
673
+ additional_image_per_prompt = batch_size // masked_image_latents.shape[0]
674
+ masked_image_latents = torch.cat([masked_image_latents] * additional_image_per_prompt, dim=0)
675
+ image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0)
676
+ masks = torch.cat([masks] * additional_image_per_prompt, dim=0)
677
+ else:
678
+ raise ValueError(
679
+ f"Cannot expand batch size from {masked_image_latents.shape[0]} to {batch_size}. "
680
+ "Batch sizes must be multiples of each other."
681
+ )
682
+
683
+ # Add noise to latents
684
+ noises = randn_tensor(image_latents.shape, generator=generator, device=device, dtype=dtype)
685
+ latents = self.scheduler.scale_noise(image_latents, timestep, noises).to(dtype=dtype)
686
+
687
+ # Combine masked latents with masks
688
+ masked_image_latents = torch.cat((masked_image_latents, masks), dim=-1).to(dtype=dtype)
689
+
690
+ return latents, masked_image_latents, latent_image_ids[0]
691
+
692
+ @property
693
+ def guidance_scale(self):
694
+ return self._guidance_scale
695
+
696
+ @property
697
+ def joint_attention_kwargs(self):
698
+ return self._joint_attention_kwargs
699
+
700
+ @property
701
+ def num_timesteps(self):
702
+ return self._num_timesteps
703
+
704
+ @property
705
+ def interrupt(self):
706
+ return self._interrupt
707
+
708
+ @torch.no_grad()
709
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
710
+ def __call__(
711
+ self,
712
+ task_prompt: Union[str, List[str]] = None,
713
+ content_prompt: Union[str, List[str]] = None,
714
+ image: Optional[torch.FloatTensor] = None,
715
+ num_inference_steps: int = 50,
716
+ sigmas: Optional[List[float]] = None,
717
+ guidance_scale: float = 30.0,
718
+ num_images_per_prompt: Optional[int] = 1,
719
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
720
+ latents: Optional[torch.FloatTensor] = None,
721
+ prompt_embeds: Optional[torch.FloatTensor] = None,
722
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
723
+ output_type: Optional[str] = "pil",
724
+ return_dict: bool = True,
725
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
726
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
727
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
728
+ max_sequence_length: int = 512,
729
+ ):
730
+ r"""
731
+ Function invoked when calling the VisualCloze pipeline for generation.
732
+
733
+ Args:
734
+ task_prompt (`str` or `List[str]`, *optional*):
735
+ The prompt or prompts to define the task intention.
736
+ content_prompt (`str` or `List[str]`, *optional*):
737
+ The prompt or prompts to define the content or caption of the target image to be generated.
738
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
739
+ `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
740
+ numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
741
+ or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
742
+ list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)`.
743
+ num_inference_steps (`int`, *optional*, defaults to 50):
744
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
745
+ expense of slower inference.
746
+ sigmas (`List[float]`, *optional*):
747
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
748
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
749
+ will be used.
750
+ guidance_scale (`float`, *optional*, defaults to 30.0):
751
+ Guidance scale as defined in [Classifier-Free Diffusion
752
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
753
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
754
+ `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
755
+ the text `prompt`, usually at the expense of lower image quality.
756
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
757
+ The number of images to generate per prompt.
758
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
759
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
760
+ to make generation deterministic.
761
+ latents (`torch.FloatTensor`, *optional*):
762
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
763
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
764
+ tensor will be generated by sampling using the supplied random `generator`.
765
+ prompt_embeds (`torch.FloatTensor`, *optional*):
766
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
767
+ provided, text embeddings will be generated from `prompt` input argument.
768
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
769
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
770
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
771
+ output_type (`str`, *optional*, defaults to `"pil"`):
772
+ The output format of the generate image. Choose between
773
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
774
+ return_dict (`bool`, *optional*, defaults to `True`):
775
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
776
+ joint_attention_kwargs (`dict`, *optional*):
777
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
778
+ `self.processor` in
779
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
780
+ callback_on_step_end (`Callable`, *optional*):
781
+ A function that calls at the end of each denoising steps during the inference. The function is called
782
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
783
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
784
+ `callback_on_step_end_tensor_inputs`.
785
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
786
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
787
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
788
+ `._callback_tensor_inputs` attribute of your pipeline class.
789
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
790
+
791
+ Examples:
792
+
793
+ Returns:
794
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
795
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
796
+ images.
797
+ """
798
+
799
+ # 1. Check inputs. Raise error if not correct
800
+ self.check_inputs(
801
+ image,
802
+ task_prompt,
803
+ content_prompt,
804
+ prompt_embeds=prompt_embeds,
805
+ pooled_prompt_embeds=pooled_prompt_embeds,
806
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
807
+ max_sequence_length=max_sequence_length,
808
+ )
809
+
810
+ self._guidance_scale = guidance_scale
811
+ self._joint_attention_kwargs = joint_attention_kwargs
812
+ self._interrupt = False
813
+
814
+ processor_output = self.image_processor.preprocess(
815
+ task_prompt, content_prompt, image, vae_scale_factor=self.vae_scale_factor
816
+ )
817
+
818
+ # 2. Define call parameters
819
+ if processor_output["task_prompt"] is not None and isinstance(processor_output["task_prompt"], str):
820
+ batch_size = 1
821
+ elif processor_output["task_prompt"] is not None and isinstance(processor_output["task_prompt"], list):
822
+ batch_size = len(processor_output["task_prompt"])
823
+
824
+ device = self._execution_device
825
+
826
+ # 3. Prepare prompt embeddings
827
+ lora_scale = (
828
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
829
+ )
830
+ prompt_embeds, pooled_prompt_embeds, text_ids = self.encode_prompt(
831
+ layout_prompt=processor_output["layout_prompt"],
832
+ task_prompt=processor_output["task_prompt"],
833
+ content_prompt=processor_output["content_prompt"],
834
+ prompt_embeds=prompt_embeds,
835
+ pooled_prompt_embeds=pooled_prompt_embeds,
836
+ device=device,
837
+ num_images_per_prompt=num_images_per_prompt,
838
+ max_sequence_length=max_sequence_length,
839
+ lora_scale=lora_scale,
840
+ )
841
+
842
+ # 4. Prepare timesteps
843
+ # Calculate sequence length and shift factor
844
+ image_seq_len = sum(
845
+ (size[0] // self.vae_scale_factor // 2) * (size[1] // self.vae_scale_factor // 2)
846
+ for sample in processor_output["image_size"][0]
847
+ for size in sample
848
+ )
849
+
850
+ # Calculate noise schedule parameters
851
+ mu = calculate_shift(
852
+ image_seq_len,
853
+ self.scheduler.config.get("base_image_seq_len", 256),
854
+ self.scheduler.config.get("max_image_seq_len", 4096),
855
+ self.scheduler.config.get("base_shift", 0.5),
856
+ self.scheduler.config.get("max_shift", 1.15),
857
+ )
858
+
859
+ # Get timesteps
860
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
861
+ timesteps, num_inference_steps = retrieve_timesteps(
862
+ self.scheduler,
863
+ num_inference_steps,
864
+ device,
865
+ sigmas=sigmas,
866
+ mu=mu,
867
+ )
868
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, 1.0, device)
869
+
870
+ # 5. Prepare latent variables
871
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
872
+ latents, masked_image_latents, latent_image_ids = self.prepare_latents(
873
+ processor_output["init_image"],
874
+ processor_output["mask"],
875
+ latent_timestep,
876
+ batch_size * num_images_per_prompt,
877
+ prompt_embeds.dtype,
878
+ device,
879
+ generator,
880
+ vae_scale_factor=self.vae_scale_factor,
881
+ )
882
+
883
+ # Calculate warmup steps
884
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
885
+ self._num_timesteps = len(timesteps)
886
+
887
+ # Prepare guidance
888
+ if self.transformer.config.guidance_embeds:
889
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
890
+ guidance = guidance.expand(latents.shape[0])
891
+ else:
892
+ guidance = None
893
+
894
+ # 6. Denoising loop
895
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
896
+ for i, t in enumerate(timesteps):
897
+ if self.interrupt:
898
+ continue
899
+
900
+ # Broadcast to batch dimension in a way that's compatible with ONNX/Core ML
901
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
902
+ latent_model_input = torch.cat((latents, masked_image_latents), dim=2)
903
+
904
+ noise_pred = self.transformer(
905
+ hidden_states=latent_model_input,
906
+ timestep=timestep / 1000,
907
+ guidance=guidance,
908
+ pooled_projections=pooled_prompt_embeds,
909
+ encoder_hidden_states=prompt_embeds,
910
+ txt_ids=text_ids,
911
+ img_ids=latent_image_ids,
912
+ joint_attention_kwargs=self.joint_attention_kwargs,
913
+ return_dict=False,
914
+ )[0]
915
+
916
+ # Compute the previous noisy sample x_t -> x_t-1
917
+ latents_dtype = latents.dtype
918
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
919
+
920
+ if latents.dtype != latents_dtype:
921
+ if torch.backends.mps.is_available():
922
+ # Some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
923
+ latents = latents.to(latents_dtype)
924
+
925
+ if callback_on_step_end is not None:
926
+ callback_kwargs = {}
927
+ for k in callback_on_step_end_tensor_inputs:
928
+ callback_kwargs[k] = locals()[k]
929
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
930
+
931
+ latents = callback_outputs.pop("latents", latents)
932
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
933
+
934
+ # Call the callback, if provided
935
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
936
+ progress_bar.update()
937
+
938
+ # XLA optimization
939
+ if XLA_AVAILABLE:
940
+ xm.mark_step()
941
+
942
+ # 7. Post-process the image
943
+ # Crop the target image
944
+ # Since the generated image is a concatenation of the conditional and target regions,
945
+ # we need to extract only the target regions based on their positions
946
+ image = []
947
+ if output_type == "latent":
948
+ image = latents
949
+ else:
950
+ for b in range(len(latents)):
951
+ cur_image_size = processor_output["image_size"][b % batch_size]
952
+ cur_target_position = processor_output["target_position"][b % batch_size]
953
+ cur_latent = self._unpack_latents(latents[b].unsqueeze(0), cur_image_size, self.vae_scale_factor)[-1]
954
+ cur_latent = (cur_latent / self.vae.config.scaling_factor) + self.vae.config.shift_factor
955
+ cur_image = self.vae.decode(cur_latent, return_dict=False)[0]
956
+ cur_image = self.image_processor.postprocess(cur_image, output_type=output_type)[0]
957
+
958
+ start = 0
959
+ cropped = []
960
+ for i, size in enumerate(cur_image_size[-1]):
961
+ if cur_target_position[i]:
962
+ if output_type == "pil":
963
+ cropped.append(cur_image.crop((start, 0, start + size[1], size[0])))
964
+ else:
965
+ cropped.append(cur_image[0 : size[0], start : start + size[1]])
966
+ start += size[1]
967
+ image.append(cropped)
968
+ if output_type != "pil":
969
+ image = np.concatenate([arr[None] for sub_image in image for arr in sub_image], axis=0)
970
+
971
+ # Offload all models
972
+ self.maybe_free_model_hooks()
973
+
974
+ if not return_dict:
975
+ return (image,)
976
+
977
+ return FluxPipelineOutput(images=image)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/visualcloze/visualcloze_utils.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 VisualCloze team and 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
+ from typing import Dict, List, Optional, Tuple, Union
16
+
17
+ import torch
18
+ from PIL import Image
19
+
20
+ from ...image_processor import VaeImageProcessor
21
+
22
+
23
+ class VisualClozeProcessor(VaeImageProcessor):
24
+ """
25
+ Image processor for the VisualCloze pipeline.
26
+
27
+ This processor handles the preprocessing of images for visual cloze tasks, including resizing, normalization, and
28
+ mask generation.
29
+
30
+ Args:
31
+ resolution (int, optional):
32
+ Target resolution for processing images. Each image will be resized to this resolution before being
33
+ concatenated to avoid the out-of-memory error. Defaults to 384.
34
+ *args: Additional arguments passed to [~image_processor.VaeImageProcessor]
35
+ **kwargs: Additional keyword arguments passed to [~image_processor.VaeImageProcessor]
36
+ """
37
+
38
+ def __init__(self, *args, resolution: int = 384, **kwargs):
39
+ super().__init__(*args, **kwargs)
40
+ self.resolution = resolution
41
+
42
+ def preprocess_image(
43
+ self, input_images: List[List[Optional[Image.Image]]], vae_scale_factor: int
44
+ ) -> Tuple[List[List[torch.Tensor]], List[List[List[int]]], List[int]]:
45
+ """
46
+ Preprocesses input images for the VisualCloze pipeline.
47
+
48
+ This function handles the preprocessing of input images by:
49
+ 1. Resizing and cropping images to maintain consistent dimensions
50
+ 2. Converting images to the Tensor format for the VAE
51
+ 3. Normalizing pixel values
52
+ 4. Tracking image sizes and positions of target images
53
+
54
+ Args:
55
+ input_images (List[List[Optional[Image.Image]]]):
56
+ A nested list of PIL Images where:
57
+ - Outer list represents different samples, including in-context examples and the query
58
+ - Inner list contains images for the task
59
+ - In the last row, condition images are provided and the target images are placed as None
60
+ vae_scale_factor (int):
61
+ The scale factor used by the VAE for resizing images
62
+
63
+ Returns:
64
+ Tuple containing:
65
+ - List[List[torch.Tensor]]: Preprocessed images in tensor format
66
+ - List[List[List[int]]]: Dimensions of each processed image [height, width]
67
+ - List[int]: Target positions indicating which images are to be generated
68
+ """
69
+ n_samples, n_task_images = len(input_images), len(input_images[0])
70
+ divisible = 2 * vae_scale_factor
71
+
72
+ processed_images: List[List[Image.Image]] = [[] for _ in range(n_samples)]
73
+ resize_size: List[Optional[Tuple[int, int]]] = [None for _ in range(n_samples)]
74
+ target_position: List[int] = []
75
+
76
+ # Process each sample
77
+ for i in range(n_samples):
78
+ # Determine size from first non-None image
79
+ for j in range(n_task_images):
80
+ if input_images[i][j] is not None:
81
+ aspect_ratio = input_images[i][j].width / input_images[i][j].height
82
+ target_area = self.resolution * self.resolution
83
+ new_h = int((target_area / aspect_ratio) ** 0.5)
84
+ new_w = int(new_h * aspect_ratio)
85
+
86
+ new_w = max(new_w // divisible, 1) * divisible
87
+ new_h = max(new_h // divisible, 1) * divisible
88
+ resize_size[i] = (new_w, new_h)
89
+ break
90
+
91
+ # Process all images in the sample
92
+ for j in range(n_task_images):
93
+ if input_images[i][j] is not None:
94
+ target = self._resize_and_crop(input_images[i][j], resize_size[i][0], resize_size[i][1])
95
+ processed_images[i].append(target)
96
+ if i == n_samples - 1:
97
+ target_position.append(0)
98
+ else:
99
+ blank = Image.new("RGB", resize_size[i] or (self.resolution, self.resolution), (0, 0, 0))
100
+ processed_images[i].append(blank)
101
+ if i == n_samples - 1:
102
+ target_position.append(1)
103
+
104
+ # Ensure consistent width for multiple target images when there are multiple target images
105
+ if len(target_position) > 1 and sum(target_position) > 1:
106
+ new_w = resize_size[n_samples - 1][0] or 384
107
+ for i in range(len(processed_images)):
108
+ for j in range(len(processed_images[i])):
109
+ if processed_images[i][j] is not None:
110
+ new_h = int(processed_images[i][j].height * (new_w / processed_images[i][j].width))
111
+ new_w = int(new_w / 16) * 16
112
+ new_h = int(new_h / 16) * 16
113
+ processed_images[i][j] = self._resize_and_crop(processed_images[i][j], new_h, new_w)
114
+
115
+ # Convert to tensors and normalize
116
+ image_sizes = []
117
+ for i in range(len(processed_images)):
118
+ image_sizes.append([[img.height, img.width] for img in processed_images[i]])
119
+ for j, image in enumerate(processed_images[i]):
120
+ image = self.pil_to_numpy(image)
121
+ image = self.numpy_to_pt(image)
122
+ image = self.normalize(image)
123
+ processed_images[i][j] = image
124
+
125
+ return processed_images, image_sizes, target_position
126
+
127
+ def preprocess_mask(
128
+ self, input_images: List[List[Image.Image]], target_position: List[int]
129
+ ) -> List[List[torch.Tensor]]:
130
+ """
131
+ Generate masks for the VisualCloze pipeline.
132
+
133
+ Args:
134
+ input_images (List[List[Image.Image]]):
135
+ Processed images from preprocess_image
136
+ target_position (List[int]):
137
+ Binary list marking the positions of target images (1 for target, 0 for condition)
138
+
139
+ Returns:
140
+ List[List[torch.Tensor]]:
141
+ A nested list of mask tensors (1 for target positions, 0 for condition images)
142
+ """
143
+ mask = []
144
+ for i, row in enumerate(input_images):
145
+ if i == len(input_images) - 1: # Query row
146
+ row_masks = [
147
+ torch.full((1, 1, row[0].shape[2], row[0].shape[3]), fill_value=m) for m in target_position
148
+ ]
149
+ else: # In-context examples
150
+ row_masks = [
151
+ torch.full((1, 1, row[0].shape[2], row[0].shape[3]), fill_value=0) for _ in target_position
152
+ ]
153
+ mask.append(row_masks)
154
+ return mask
155
+
156
+ def preprocess_image_upsampling(
157
+ self,
158
+ input_images: List[List[Image.Image]],
159
+ height: int,
160
+ width: int,
161
+ ) -> Tuple[List[List[Image.Image]], List[List[List[int]]]]:
162
+ """Process images for the upsampling stage in the VisualCloze pipeline.
163
+
164
+ Args:
165
+ input_images: Input image to process
166
+ height: Target height
167
+ width: Target width
168
+
169
+ Returns:
170
+ Tuple of processed image and its size
171
+ """
172
+ image = self.resize(input_images[0][0], height, width)
173
+ image = self.pil_to_numpy(image) # to np
174
+ image = self.numpy_to_pt(image) # to pt
175
+ image = self.normalize(image)
176
+
177
+ input_images[0][0] = image
178
+ image_sizes = [[[height, width]]]
179
+ return input_images, image_sizes
180
+
181
+ def preprocess_mask_upsampling(self, input_images: List[List[Image.Image]]) -> List[List[torch.Tensor]]:
182
+ return [[torch.ones((1, 1, input_images[0][0].shape[2], input_images[0][0].shape[3]))]]
183
+
184
+ def get_layout_prompt(self, size: Tuple[int, int]) -> str:
185
+ layout_instruction = (
186
+ f"A grid layout with {size[0]} rows and {size[1]} columns, displaying {size[0] * size[1]} images arranged side by side.",
187
+ )
188
+ return layout_instruction
189
+
190
+ def preprocess(
191
+ self,
192
+ task_prompt: Union[str, List[str]],
193
+ content_prompt: Union[str, List[str]],
194
+ input_images: Optional[List[List[List[Optional[str]]]]] = None,
195
+ height: Optional[int] = None,
196
+ width: Optional[int] = None,
197
+ upsampling: bool = False,
198
+ vae_scale_factor: int = 16,
199
+ ) -> Dict:
200
+ """Process visual cloze inputs.
201
+
202
+ Args:
203
+ task_prompt: Task description(s)
204
+ content_prompt: Content description(s)
205
+ input_images: List of images or None for the target images
206
+ height: Optional target height for upsampling stage
207
+ width: Optional target width for upsampling stage
208
+ upsampling: Whether this is in the upsampling processing stage
209
+
210
+ Returns:
211
+ Dictionary containing processed images, masks, prompts and metadata
212
+ """
213
+ if isinstance(task_prompt, str):
214
+ task_prompt = [task_prompt]
215
+ content_prompt = [content_prompt]
216
+ input_images = [input_images]
217
+
218
+ output = {
219
+ "init_image": [],
220
+ "mask": [],
221
+ "task_prompt": task_prompt if not upsampling else [None for _ in range(len(task_prompt))],
222
+ "content_prompt": content_prompt,
223
+ "layout_prompt": [],
224
+ "target_position": [],
225
+ "image_size": [],
226
+ }
227
+ for i in range(len(task_prompt)):
228
+ if upsampling:
229
+ layout_prompt = None
230
+ else:
231
+ layout_prompt = self.get_layout_prompt((len(input_images[i]), len(input_images[i][0])))
232
+
233
+ if upsampling:
234
+ cur_processed_images, cur_image_size = self.preprocess_image_upsampling(
235
+ input_images[i], height=height, width=width
236
+ )
237
+ cur_mask = self.preprocess_mask_upsampling(cur_processed_images)
238
+ else:
239
+ cur_processed_images, cur_image_size, cur_target_position = self.preprocess_image(
240
+ input_images[i], vae_scale_factor=vae_scale_factor
241
+ )
242
+ cur_mask = self.preprocess_mask(cur_processed_images, cur_target_position)
243
+
244
+ output["target_position"].append(cur_target_position)
245
+
246
+ output["image_size"].append(cur_image_size)
247
+ output["init_image"].append(cur_processed_images)
248
+ output["mask"].append(cur_mask)
249
+ output["layout_prompt"].append(layout_prompt)
250
+
251
+ return output
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wan/__init__.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING
2
+
3
+ from ...utils import (
4
+ DIFFUSERS_SLOW_IMPORT,
5
+ OptionalDependencyNotAvailable,
6
+ _LazyModule,
7
+ get_objects_from_module,
8
+ is_torch_available,
9
+ is_transformers_available,
10
+ )
11
+
12
+
13
+ _dummy_objects = {}
14
+ _import_structure = {}
15
+
16
+
17
+ try:
18
+ if not (is_transformers_available() and is_torch_available()):
19
+ raise OptionalDependencyNotAvailable()
20
+ except OptionalDependencyNotAvailable:
21
+ from ...utils import dummy_torch_and_transformers_objects # noqa F403
22
+
23
+ _dummy_objects.update(get_objects_from_module(dummy_torch_and_transformers_objects))
24
+ else:
25
+ _import_structure["pipeline_wan"] = ["WanPipeline"]
26
+ _import_structure["pipeline_wan_animate"] = ["WanAnimatePipeline"]
27
+ _import_structure["pipeline_wan_i2v"] = ["WanImageToVideoPipeline"]
28
+ _import_structure["pipeline_wan_vace"] = ["WanVACEPipeline"]
29
+ _import_structure["pipeline_wan_video2video"] = ["WanVideoToVideoPipeline"]
30
+ if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
31
+ try:
32
+ if not (is_transformers_available() and is_torch_available()):
33
+ raise OptionalDependencyNotAvailable()
34
+
35
+ except OptionalDependencyNotAvailable:
36
+ from ...utils.dummy_torch_and_transformers_objects import *
37
+ else:
38
+ from .pipeline_wan import WanPipeline
39
+ from .pipeline_wan_animate import WanAnimatePipeline
40
+ from .pipeline_wan_i2v import WanImageToVideoPipeline
41
+ from .pipeline_wan_vace import WanVACEPipeline
42
+ from .pipeline_wan_video2video import WanVideoToVideoPipeline
43
+ else:
44
+ import sys
45
+
46
+ sys.modules[__name__] = _LazyModule(
47
+ __name__,
48
+ globals()["__file__"],
49
+ _import_structure,
50
+ module_spec=__spec__,
51
+ )
52
+
53
+ for name, value in _dummy_objects.items():
54
+ setattr(sys.modules[__name__], name, value)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wan/image_processor.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The Wan Team and 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
+ from typing import Optional, Tuple, Union
16
+
17
+ import numpy as np
18
+ import PIL.Image
19
+ import torch
20
+
21
+ from ...configuration_utils import register_to_config
22
+ from ...image_processor import VaeImageProcessor
23
+ from ...utils import PIL_INTERPOLATION
24
+
25
+
26
+ class WanAnimateImageProcessor(VaeImageProcessor):
27
+ r"""
28
+ Image processor to preprocess the reference (character) image for the Wan Animate model.
29
+
30
+ Args:
31
+ do_resize (`bool`, *optional*, defaults to `True`):
32
+ Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
33
+ `height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
34
+ vae_scale_factor (`int`, *optional*, defaults to `8`):
35
+ VAE (spatial) scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of
36
+ this factor.
37
+ vae_latent_channels (`int`, *optional*, defaults to `16`):
38
+ VAE latent channels.
39
+ spatial_patch_size (`Tuple[int, int]`, *optional*, defaults to `(2, 2)`):
40
+ The spatial patch size used by the diffusion transformer. For Wan models, this is typically (2, 2).
41
+ resample (`str`, *optional*, defaults to `lanczos`):
42
+ Resampling filter to use when resizing the image.
43
+ do_normalize (`bool`, *optional*, defaults to `True`):
44
+ Whether to normalize the image to [-1,1].
45
+ do_binarize (`bool`, *optional*, defaults to `False`):
46
+ Whether to binarize the image to 0/1.
47
+ do_convert_rgb (`bool`, *optional*, defaults to be `False`):
48
+ Whether to convert the images to RGB format.
49
+ do_convert_grayscale (`bool`, *optional*, defaults to be `False`):
50
+ Whether to convert the images to grayscale format.
51
+ fill_color (`str` or `float` or `Tuple[float, ...]`, *optional*, defaults to `None`):
52
+ An optional fill color when `resize_mode` is set to `"fill"`. This will fill the empty space with that
53
+ color instead of filling with data from the image. Any valid `color` argument to `PIL.Image.new` is valid;
54
+ if `None`, will default to filling with data from `image`.
55
+ """
56
+
57
+ @register_to_config
58
+ def __init__(
59
+ self,
60
+ do_resize: bool = True,
61
+ vae_scale_factor: int = 8,
62
+ vae_latent_channels: int = 16,
63
+ spatial_patch_size: Tuple[int, int] = (2, 2),
64
+ resample: str = "lanczos",
65
+ reducing_gap: int = None,
66
+ do_normalize: bool = True,
67
+ do_binarize: bool = False,
68
+ do_convert_rgb: bool = False,
69
+ do_convert_grayscale: bool = False,
70
+ fill_color: Optional[Union[str, float, Tuple[float, ...]]] = 0,
71
+ ):
72
+ super().__init__()
73
+ if do_convert_rgb and do_convert_grayscale:
74
+ raise ValueError(
75
+ "`do_convert_rgb` and `do_convert_grayscale` can not both be set to `True`,"
76
+ " if you intended to convert the image into RGB format, please set `do_convert_grayscale = False`.",
77
+ " if you intended to convert the image into grayscale format, please set `do_convert_rgb = False`",
78
+ )
79
+
80
+ def _resize_and_fill(
81
+ self,
82
+ image: PIL.Image.Image,
83
+ width: int,
84
+ height: int,
85
+ ) -> PIL.Image.Image:
86
+ r"""
87
+ Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center
88
+ the image within the dimensions, filling empty with data from image.
89
+
90
+ Args:
91
+ image (`PIL.Image.Image`):
92
+ The image to resize and fill.
93
+ width (`int`):
94
+ The width to resize the image to.
95
+ height (`int`):
96
+ The height to resize the image to.
97
+
98
+ Returns:
99
+ `PIL.Image.Image`:
100
+ The resized and filled image.
101
+ """
102
+
103
+ ratio = width / height
104
+ src_ratio = image.width / image.height
105
+ fill_with_image_data = self.config.fill_color is None
106
+ fill_color = self.config.fill_color or 0
107
+
108
+ src_w = width if ratio < src_ratio else image.width * height // image.height
109
+ src_h = height if ratio >= src_ratio else image.height * width // image.width
110
+
111
+ resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION[self.config.resample])
112
+ res = PIL.Image.new("RGB", (width, height), color=fill_color)
113
+ res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
114
+
115
+ if fill_with_image_data:
116
+ if ratio < src_ratio:
117
+ fill_height = height // 2 - src_h // 2
118
+ if fill_height > 0:
119
+ res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0))
120
+ res.paste(
121
+ resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)),
122
+ box=(0, fill_height + src_h),
123
+ )
124
+ elif ratio > src_ratio:
125
+ fill_width = width // 2 - src_w // 2
126
+ if fill_width > 0:
127
+ res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0))
128
+ res.paste(
129
+ resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)),
130
+ box=(fill_width + src_w, 0),
131
+ )
132
+
133
+ return res
134
+
135
+ def get_default_height_width(
136
+ self,
137
+ image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
138
+ height: Optional[int] = None,
139
+ width: Optional[int] = None,
140
+ ) -> Tuple[int, int]:
141
+ r"""
142
+ Returns the height and width of the image, downscaled to the next integer multiple of `vae_scale_factor`.
143
+
144
+ Args:
145
+ image (`Union[PIL.Image.Image, np.ndarray, torch.Tensor]`):
146
+ The image input, which can be a PIL image, NumPy array, or PyTorch tensor. If it is a NumPy array, it
147
+ should have shape `[batch, height, width]` or `[batch, height, width, channels]`. If it is a PyTorch
148
+ tensor, it should have shape `[batch, channels, height, width]`.
149
+ height (`Optional[int]`, *optional*, defaults to `None`):
150
+ The height of the preprocessed image. If `None`, the height of the `image` input will be used.
151
+ width (`Optional[int]`, *optional*, defaults to `None`):
152
+ The width of the preprocessed image. If `None`, the width of the `image` input will be used.
153
+
154
+ Returns:
155
+ `Tuple[int, int]`:
156
+ A tuple containing the height and width, both resized to the nearest integer multiple of
157
+ `vae_scale_factor * spatial_patch_size`.
158
+ """
159
+
160
+ if height is None:
161
+ if isinstance(image, PIL.Image.Image):
162
+ height = image.height
163
+ elif isinstance(image, torch.Tensor):
164
+ height = image.shape[2]
165
+ else:
166
+ height = image.shape[1]
167
+
168
+ if width is None:
169
+ if isinstance(image, PIL.Image.Image):
170
+ width = image.width
171
+ elif isinstance(image, torch.Tensor):
172
+ width = image.shape[3]
173
+ else:
174
+ width = image.shape[2]
175
+
176
+ max_area = width * height
177
+ aspect_ratio = height / width
178
+ mod_value_h = self.config.vae_scale_factor * self.config.spatial_patch_size[0]
179
+ mod_value_w = self.config.vae_scale_factor * self.config.spatial_patch_size[1]
180
+
181
+ # Try to preserve the aspect ratio
182
+ height = round(np.sqrt(max_area * aspect_ratio)) // mod_value_h * mod_value_h
183
+ width = round(np.sqrt(max_area / aspect_ratio)) // mod_value_w * mod_value_w
184
+
185
+ return height, width
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wan/pipeline_output.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ import torch
4
+
5
+ from diffusers.utils import BaseOutput
6
+
7
+
8
+ @dataclass
9
+ class WanPipelineOutput(BaseOutput):
10
+ r"""
11
+ Output class for Wan pipelines.
12
+
13
+ Args:
14
+ frames (`torch.Tensor`, `np.ndarray`, or List[List[PIL.Image.Image]]):
15
+ List of video outputs - It can be a nested list of length `batch_size,` with each sub-list containing
16
+ denoised PIL image sequences of length `num_frames.` It can also be a NumPy array or Torch tensor of shape
17
+ `(batch_size, num_frames, channels, height, width)`.
18
+ """
19
+
20
+ frames: torch.Tensor
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wan/pipeline_wan.py ADDED
@@ -0,0 +1,656 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The Wan Team and 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 html
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import regex as re
19
+ import torch
20
+ from transformers import AutoTokenizer, UMT5EncoderModel
21
+
22
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
23
+ from ...loaders import WanLoraLoaderMixin
24
+ from ...models import AutoencoderKLWan, WanTransformer3DModel
25
+ from ...schedulers import FlowMatchEulerDiscreteScheduler
26
+ from ...utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring
27
+ from ...utils.torch_utils import randn_tensor
28
+ from ...video_processor import VideoProcessor
29
+ from ..pipeline_utils import DiffusionPipeline
30
+ from .pipeline_output import WanPipelineOutput
31
+
32
+
33
+ if is_torch_xla_available():
34
+ import torch_xla.core.xla_model as xm
35
+
36
+ XLA_AVAILABLE = True
37
+ else:
38
+ XLA_AVAILABLE = False
39
+
40
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
41
+
42
+ if is_ftfy_available():
43
+ import ftfy
44
+
45
+
46
+ EXAMPLE_DOC_STRING = """
47
+ Examples:
48
+ ```python
49
+ >>> import torch
50
+ >>> from diffusers.utils import export_to_video
51
+ >>> from diffusers import AutoencoderKLWan, WanPipeline
52
+ >>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
53
+
54
+ >>> # Available models: Wan-AI/Wan2.1-T2V-14B-Diffusers, Wan-AI/Wan2.1-T2V-1.3B-Diffusers
55
+ >>> model_id = "Wan-AI/Wan2.1-T2V-14B-Diffusers"
56
+ >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
57
+ >>> pipe = WanPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
58
+ >>> flow_shift = 5.0 # 5.0 for 720P, 3.0 for 480P
59
+ >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
60
+ >>> pipe.to("cuda")
61
+
62
+ >>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
63
+ >>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
64
+
65
+ >>> output = pipe(
66
+ ... prompt=prompt,
67
+ ... negative_prompt=negative_prompt,
68
+ ... height=720,
69
+ ... width=1280,
70
+ ... num_frames=81,
71
+ ... guidance_scale=5.0,
72
+ ... ).frames[0]
73
+ >>> export_to_video(output, "output.mp4", fps=16)
74
+ ```
75
+ """
76
+
77
+
78
+ def basic_clean(text):
79
+ text = ftfy.fix_text(text)
80
+ text = html.unescape(html.unescape(text))
81
+ return text.strip()
82
+
83
+
84
+ def whitespace_clean(text):
85
+ text = re.sub(r"\s+", " ", text)
86
+ text = text.strip()
87
+ return text
88
+
89
+
90
+ def prompt_clean(text):
91
+ text = whitespace_clean(basic_clean(text))
92
+ return text
93
+
94
+
95
+ class WanPipeline(DiffusionPipeline, WanLoraLoaderMixin):
96
+ r"""
97
+ Pipeline for text-to-video generation using Wan.
98
+
99
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
100
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
101
+
102
+ Args:
103
+ tokenizer ([`T5Tokenizer`]):
104
+ Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
105
+ specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
106
+ text_encoder ([`T5EncoderModel`]):
107
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
108
+ the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
109
+ transformer ([`WanTransformer3DModel`]):
110
+ Conditional Transformer to denoise the input latents.
111
+ scheduler ([`UniPCMultistepScheduler`]):
112
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
113
+ vae ([`AutoencoderKLWan`]):
114
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
115
+ transformer_2 ([`WanTransformer3DModel`], *optional*):
116
+ Conditional Transformer to denoise the input latents during the low-noise stage. If provided, enables
117
+ two-stage denoising where `transformer` handles high-noise stages and `transformer_2` handles low-noise
118
+ stages. If not provided, only `transformer` is used.
119
+ boundary_ratio (`float`, *optional*, defaults to `None`):
120
+ Ratio of total timesteps to use as the boundary for switching between transformers in two-stage denoising.
121
+ The actual boundary timestep is calculated as `boundary_ratio * num_train_timesteps`. When provided,
122
+ `transformer` handles timesteps >= boundary_timestep and `transformer_2` handles timesteps <
123
+ boundary_timestep. If `None`, only `transformer` is used for the entire denoising process.
124
+ """
125
+
126
+ model_cpu_offload_seq = "text_encoder->transformer->transformer_2->vae"
127
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
128
+ _optional_components = ["transformer", "transformer_2"]
129
+
130
+ def __init__(
131
+ self,
132
+ tokenizer: AutoTokenizer,
133
+ text_encoder: UMT5EncoderModel,
134
+ vae: AutoencoderKLWan,
135
+ scheduler: FlowMatchEulerDiscreteScheduler,
136
+ transformer: Optional[WanTransformer3DModel] = None,
137
+ transformer_2: Optional[WanTransformer3DModel] = None,
138
+ boundary_ratio: Optional[float] = None,
139
+ expand_timesteps: bool = False, # Wan2.2 ti2v
140
+ ):
141
+ super().__init__()
142
+
143
+ self.register_modules(
144
+ vae=vae,
145
+ text_encoder=text_encoder,
146
+ tokenizer=tokenizer,
147
+ transformer=transformer,
148
+ scheduler=scheduler,
149
+ transformer_2=transformer_2,
150
+ )
151
+ self.register_to_config(boundary_ratio=boundary_ratio)
152
+ self.register_to_config(expand_timesteps=expand_timesteps)
153
+ self.vae_scale_factor_temporal = self.vae.config.scale_factor_temporal if getattr(self, "vae", None) else 4
154
+ self.vae_scale_factor_spatial = self.vae.config.scale_factor_spatial if getattr(self, "vae", None) else 8
155
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
156
+
157
+ def _get_t5_prompt_embeds(
158
+ self,
159
+ prompt: Union[str, List[str]] = None,
160
+ num_videos_per_prompt: int = 1,
161
+ max_sequence_length: int = 226,
162
+ device: Optional[torch.device] = None,
163
+ dtype: Optional[torch.dtype] = None,
164
+ ):
165
+ device = device or self._execution_device
166
+ dtype = dtype or self.text_encoder.dtype
167
+
168
+ prompt = [prompt] if isinstance(prompt, str) else prompt
169
+ prompt = [prompt_clean(u) for u in prompt]
170
+ batch_size = len(prompt)
171
+
172
+ text_inputs = self.tokenizer(
173
+ prompt,
174
+ padding="max_length",
175
+ max_length=max_sequence_length,
176
+ truncation=True,
177
+ add_special_tokens=True,
178
+ return_attention_mask=True,
179
+ return_tensors="pt",
180
+ )
181
+ text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
182
+ seq_lens = mask.gt(0).sum(dim=1).long()
183
+
184
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
185
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
186
+ prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
187
+ prompt_embeds = torch.stack(
188
+ [torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
189
+ )
190
+
191
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
192
+ _, seq_len, _ = prompt_embeds.shape
193
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
194
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
195
+
196
+ return prompt_embeds
197
+
198
+ def encode_prompt(
199
+ self,
200
+ prompt: Union[str, List[str]],
201
+ negative_prompt: Optional[Union[str, List[str]]] = None,
202
+ do_classifier_free_guidance: bool = True,
203
+ num_videos_per_prompt: int = 1,
204
+ prompt_embeds: Optional[torch.Tensor] = None,
205
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
206
+ max_sequence_length: int = 226,
207
+ device: Optional[torch.device] = None,
208
+ dtype: Optional[torch.dtype] = None,
209
+ ):
210
+ r"""
211
+ Encodes the prompt into text encoder hidden states.
212
+
213
+ Args:
214
+ prompt (`str` or `List[str]`, *optional*):
215
+ prompt to be encoded
216
+ negative_prompt (`str` or `List[str]`, *optional*):
217
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
218
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
219
+ less than `1`).
220
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
221
+ Whether to use classifier free guidance or not.
222
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
223
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
224
+ prompt_embeds (`torch.Tensor`, *optional*):
225
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
226
+ provided, text embeddings will be generated from `prompt` input argument.
227
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
228
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
229
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
230
+ argument.
231
+ device: (`torch.device`, *optional*):
232
+ torch device
233
+ dtype: (`torch.dtype`, *optional*):
234
+ torch dtype
235
+ """
236
+ device = device or self._execution_device
237
+
238
+ prompt = [prompt] if isinstance(prompt, str) else prompt
239
+ if prompt is not None:
240
+ batch_size = len(prompt)
241
+ else:
242
+ batch_size = prompt_embeds.shape[0]
243
+
244
+ if prompt_embeds is None:
245
+ prompt_embeds = self._get_t5_prompt_embeds(
246
+ prompt=prompt,
247
+ num_videos_per_prompt=num_videos_per_prompt,
248
+ max_sequence_length=max_sequence_length,
249
+ device=device,
250
+ dtype=dtype,
251
+ )
252
+
253
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
254
+ negative_prompt = negative_prompt or ""
255
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
256
+
257
+ if prompt is not None and type(prompt) is not type(negative_prompt):
258
+ raise TypeError(
259
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
260
+ f" {type(prompt)}."
261
+ )
262
+ elif batch_size != len(negative_prompt):
263
+ raise ValueError(
264
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
265
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
266
+ " the batch size of `prompt`."
267
+ )
268
+
269
+ negative_prompt_embeds = self._get_t5_prompt_embeds(
270
+ prompt=negative_prompt,
271
+ num_videos_per_prompt=num_videos_per_prompt,
272
+ max_sequence_length=max_sequence_length,
273
+ device=device,
274
+ dtype=dtype,
275
+ )
276
+
277
+ return prompt_embeds, negative_prompt_embeds
278
+
279
+ def check_inputs(
280
+ self,
281
+ prompt,
282
+ negative_prompt,
283
+ height,
284
+ width,
285
+ prompt_embeds=None,
286
+ negative_prompt_embeds=None,
287
+ callback_on_step_end_tensor_inputs=None,
288
+ guidance_scale_2=None,
289
+ ):
290
+ if height % 16 != 0 or width % 16 != 0:
291
+ raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
292
+
293
+ if callback_on_step_end_tensor_inputs is not None and not all(
294
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
295
+ ):
296
+ raise ValueError(
297
+ 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]}"
298
+ )
299
+
300
+ if prompt is not None and prompt_embeds is not None:
301
+ raise ValueError(
302
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
303
+ " only forward one of the two."
304
+ )
305
+ elif negative_prompt is not None and negative_prompt_embeds is not None:
306
+ raise ValueError(
307
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
308
+ " only forward one of the two."
309
+ )
310
+ elif prompt is None and prompt_embeds is None:
311
+ raise ValueError(
312
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
313
+ )
314
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
315
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
316
+ elif negative_prompt is not None and (
317
+ not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
318
+ ):
319
+ raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
320
+
321
+ if self.config.boundary_ratio is None and guidance_scale_2 is not None:
322
+ raise ValueError("`guidance_scale_2` is only supported when the pipeline's `boundary_ratio` is not None.")
323
+
324
+ def prepare_latents(
325
+ self,
326
+ batch_size: int,
327
+ num_channels_latents: int = 16,
328
+ height: int = 480,
329
+ width: int = 832,
330
+ num_frames: int = 81,
331
+ dtype: Optional[torch.dtype] = None,
332
+ device: Optional[torch.device] = None,
333
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
334
+ latents: Optional[torch.Tensor] = None,
335
+ ) -> torch.Tensor:
336
+ if latents is not None:
337
+ return latents.to(device=device, dtype=dtype)
338
+
339
+ num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
340
+ shape = (
341
+ batch_size,
342
+ num_channels_latents,
343
+ num_latent_frames,
344
+ int(height) // self.vae_scale_factor_spatial,
345
+ int(width) // self.vae_scale_factor_spatial,
346
+ )
347
+ if isinstance(generator, list) and len(generator) != batch_size:
348
+ raise ValueError(
349
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
350
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
351
+ )
352
+
353
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
354
+ return latents
355
+
356
+ @property
357
+ def guidance_scale(self):
358
+ return self._guidance_scale
359
+
360
+ @property
361
+ def do_classifier_free_guidance(self):
362
+ return self._guidance_scale > 1.0
363
+
364
+ @property
365
+ def num_timesteps(self):
366
+ return self._num_timesteps
367
+
368
+ @property
369
+ def current_timestep(self):
370
+ return self._current_timestep
371
+
372
+ @property
373
+ def interrupt(self):
374
+ return self._interrupt
375
+
376
+ @property
377
+ def attention_kwargs(self):
378
+ return self._attention_kwargs
379
+
380
+ @torch.no_grad()
381
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
382
+ def __call__(
383
+ self,
384
+ prompt: Union[str, List[str]] = None,
385
+ negative_prompt: Union[str, List[str]] = None,
386
+ height: int = 480,
387
+ width: int = 832,
388
+ num_frames: int = 81,
389
+ num_inference_steps: int = 50,
390
+ guidance_scale: float = 5.0,
391
+ guidance_scale_2: Optional[float] = None,
392
+ num_videos_per_prompt: Optional[int] = 1,
393
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
394
+ latents: Optional[torch.Tensor] = None,
395
+ prompt_embeds: Optional[torch.Tensor] = None,
396
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
397
+ output_type: Optional[str] = "np",
398
+ return_dict: bool = True,
399
+ attention_kwargs: Optional[Dict[str, Any]] = None,
400
+ callback_on_step_end: Optional[
401
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
402
+ ] = None,
403
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
404
+ max_sequence_length: int = 512,
405
+ ):
406
+ r"""
407
+ The call function to the pipeline for generation.
408
+
409
+ Args:
410
+ prompt (`str` or `List[str]`, *optional*):
411
+ The prompt or prompts to guide the image generation. If not defined, pass `prompt_embeds` instead.
412
+ negative_prompt (`str` or `List[str]`, *optional*):
413
+ The prompt or prompts to avoid during image generation. If not defined, pass `negative_prompt_embeds`
414
+ instead. Ignored when not using guidance (`guidance_scale` < `1`).
415
+ height (`int`, defaults to `480`):
416
+ The height in pixels of the generated image.
417
+ width (`int`, defaults to `832`):
418
+ The width in pixels of the generated image.
419
+ num_frames (`int`, defaults to `81`):
420
+ The number of frames in the generated video.
421
+ num_inference_steps (`int`, defaults to `50`):
422
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
423
+ expense of slower inference.
424
+ guidance_scale (`float`, defaults to `5.0`):
425
+ Guidance scale as defined in [Classifier-Free Diffusion
426
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
427
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
428
+ `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
429
+ the text `prompt`, usually at the expense of lower image quality.
430
+ guidance_scale_2 (`float`, *optional*, defaults to `None`):
431
+ Guidance scale for the low-noise stage transformer (`transformer_2`). If `None` and the pipeline's
432
+ `boundary_ratio` is not None, uses the same value as `guidance_scale`. Only used when `transformer_2`
433
+ and the pipeline's `boundary_ratio` are not None.
434
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
435
+ The number of images to generate per prompt.
436
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
437
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
438
+ generation deterministic.
439
+ latents (`torch.Tensor`, *optional*):
440
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
441
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
442
+ tensor is generated by sampling using the supplied random `generator`.
443
+ prompt_embeds (`torch.Tensor`, *optional*):
444
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
445
+ provided, text embeddings are generated from the `prompt` input argument.
446
+ output_type (`str`, *optional*, defaults to `"np"`):
447
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
448
+ return_dict (`bool`, *optional*, defaults to `True`):
449
+ Whether or not to return a [`WanPipelineOutput`] instead of a plain tuple.
450
+ attention_kwargs (`dict`, *optional*):
451
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
452
+ `self.processor` in
453
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
454
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
455
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
456
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
457
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
458
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
459
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
460
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
461
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
462
+ `._callback_tensor_inputs` attribute of your pipeline class.
463
+ max_sequence_length (`int`, defaults to `512`):
464
+ The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
465
+ truncated. If the prompt is shorter, it will be padded to this length.
466
+
467
+ Examples:
468
+
469
+ Returns:
470
+ [`~WanPipelineOutput`] or `tuple`:
471
+ If `return_dict` is `True`, [`WanPipelineOutput`] is returned, otherwise a `tuple` is returned where
472
+ the first element is a list with the generated images and the second element is a list of `bool`s
473
+ indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
474
+ """
475
+
476
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
477
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
478
+
479
+ # 1. Check inputs. Raise error if not correct
480
+ self.check_inputs(
481
+ prompt,
482
+ negative_prompt,
483
+ height,
484
+ width,
485
+ prompt_embeds,
486
+ negative_prompt_embeds,
487
+ callback_on_step_end_tensor_inputs,
488
+ guidance_scale_2,
489
+ )
490
+
491
+ if num_frames % self.vae_scale_factor_temporal != 1:
492
+ logger.warning(
493
+ f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
494
+ )
495
+ num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
496
+ num_frames = max(num_frames, 1)
497
+
498
+ if self.config.boundary_ratio is not None and guidance_scale_2 is None:
499
+ guidance_scale_2 = guidance_scale
500
+
501
+ self._guidance_scale = guidance_scale
502
+ self._guidance_scale_2 = guidance_scale_2
503
+ self._attention_kwargs = attention_kwargs
504
+ self._current_timestep = None
505
+ self._interrupt = False
506
+
507
+ device = self._execution_device
508
+
509
+ # 2. Define call parameters
510
+ if prompt is not None and isinstance(prompt, str):
511
+ batch_size = 1
512
+ elif prompt is not None and isinstance(prompt, list):
513
+ batch_size = len(prompt)
514
+ else:
515
+ batch_size = prompt_embeds.shape[0]
516
+
517
+ # 3. Encode input prompt
518
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
519
+ prompt=prompt,
520
+ negative_prompt=negative_prompt,
521
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
522
+ num_videos_per_prompt=num_videos_per_prompt,
523
+ prompt_embeds=prompt_embeds,
524
+ negative_prompt_embeds=negative_prompt_embeds,
525
+ max_sequence_length=max_sequence_length,
526
+ device=device,
527
+ )
528
+
529
+ transformer_dtype = self.transformer.dtype if self.transformer is not None else self.transformer_2.dtype
530
+ prompt_embeds = prompt_embeds.to(transformer_dtype)
531
+ if negative_prompt_embeds is not None:
532
+ negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
533
+
534
+ # 4. Prepare timesteps
535
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
536
+ timesteps = self.scheduler.timesteps
537
+
538
+ # 5. Prepare latent variables
539
+ num_channels_latents = (
540
+ self.transformer.config.in_channels
541
+ if self.transformer is not None
542
+ else self.transformer_2.config.in_channels
543
+ )
544
+ latents = self.prepare_latents(
545
+ batch_size * num_videos_per_prompt,
546
+ num_channels_latents,
547
+ height,
548
+ width,
549
+ num_frames,
550
+ torch.float32,
551
+ device,
552
+ generator,
553
+ latents,
554
+ )
555
+
556
+ mask = torch.ones(latents.shape, dtype=torch.float32, device=device)
557
+
558
+ # 6. Denoising loop
559
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
560
+ self._num_timesteps = len(timesteps)
561
+
562
+ if self.config.boundary_ratio is not None:
563
+ boundary_timestep = self.config.boundary_ratio * self.scheduler.config.num_train_timesteps
564
+ else:
565
+ boundary_timestep = None
566
+
567
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
568
+ for i, t in enumerate(timesteps):
569
+ if self.interrupt:
570
+ continue
571
+
572
+ self._current_timestep = t
573
+
574
+ if boundary_timestep is None or t >= boundary_timestep:
575
+ # wan2.1 or high-noise stage in wan2.2
576
+ current_model = self.transformer
577
+ current_guidance_scale = guidance_scale
578
+ else:
579
+ # low-noise stage in wan2.2
580
+ current_model = self.transformer_2
581
+ current_guidance_scale = guidance_scale_2
582
+
583
+ latent_model_input = latents.to(transformer_dtype)
584
+ if self.config.expand_timesteps:
585
+ # seq_len: num_latent_frames * latent_height//2 * latent_width//2
586
+ temp_ts = (mask[0][0][:, ::2, ::2] * t).flatten()
587
+ # batch_size, seq_len
588
+ timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1)
589
+ else:
590
+ timestep = t.expand(latents.shape[0])
591
+
592
+ with current_model.cache_context("cond"):
593
+ noise_pred = current_model(
594
+ hidden_states=latent_model_input,
595
+ timestep=timestep,
596
+ encoder_hidden_states=prompt_embeds,
597
+ attention_kwargs=attention_kwargs,
598
+ return_dict=False,
599
+ )[0]
600
+
601
+ if self.do_classifier_free_guidance:
602
+ with current_model.cache_context("uncond"):
603
+ noise_uncond = current_model(
604
+ hidden_states=latent_model_input,
605
+ timestep=timestep,
606
+ encoder_hidden_states=negative_prompt_embeds,
607
+ attention_kwargs=attention_kwargs,
608
+ return_dict=False,
609
+ )[0]
610
+ noise_pred = noise_uncond + current_guidance_scale * (noise_pred - noise_uncond)
611
+
612
+ # compute the previous noisy sample x_t -> x_t-1
613
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
614
+
615
+ if callback_on_step_end is not None:
616
+ callback_kwargs = {}
617
+ for k in callback_on_step_end_tensor_inputs:
618
+ callback_kwargs[k] = locals()[k]
619
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
620
+
621
+ latents = callback_outputs.pop("latents", latents)
622
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
623
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
624
+
625
+ # call the callback, if provided
626
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
627
+ progress_bar.update()
628
+
629
+ if XLA_AVAILABLE:
630
+ xm.mark_step()
631
+
632
+ self._current_timestep = None
633
+
634
+ if not output_type == "latent":
635
+ latents = latents.to(self.vae.dtype)
636
+ latents_mean = (
637
+ torch.tensor(self.vae.config.latents_mean)
638
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
639
+ .to(latents.device, latents.dtype)
640
+ )
641
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
642
+ latents.device, latents.dtype
643
+ )
644
+ latents = latents / latents_std + latents_mean
645
+ video = self.vae.decode(latents, return_dict=False)[0]
646
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
647
+ else:
648
+ video = latents
649
+
650
+ # Offload all models
651
+ self.maybe_free_model_hooks()
652
+
653
+ if not return_dict:
654
+ return (video,)
655
+
656
+ return WanPipelineOutput(frames=video)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wan/pipeline_wan_animate.py ADDED
@@ -0,0 +1,1204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The Wan Team and 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 html
16
+ from copy import deepcopy
17
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
18
+
19
+ import PIL
20
+ import regex as re
21
+ import torch
22
+ import torch.nn.functional as F
23
+ from transformers import AutoTokenizer, CLIPImageProcessor, CLIPVisionModel, UMT5EncoderModel
24
+
25
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
26
+ from ...image_processor import PipelineImageInput
27
+ from ...loaders import WanLoraLoaderMixin
28
+ from ...models import AutoencoderKLWan, WanAnimateTransformer3DModel
29
+ from ...schedulers import UniPCMultistepScheduler
30
+ from ...utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring
31
+ from ...utils.torch_utils import randn_tensor
32
+ from ...video_processor import VideoProcessor
33
+ from ..pipeline_utils import DiffusionPipeline
34
+ from .image_processor import WanAnimateImageProcessor
35
+ from .pipeline_output import WanPipelineOutput
36
+
37
+
38
+ if is_torch_xla_available():
39
+ import torch_xla.core.xla_model as xm
40
+
41
+ XLA_AVAILABLE = True
42
+ else:
43
+ XLA_AVAILABLE = False
44
+
45
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
46
+
47
+ if is_ftfy_available():
48
+ import ftfy
49
+
50
+ EXAMPLE_DOC_STRING = """
51
+ Examples:
52
+ ```python
53
+ >>> import torch
54
+ >>> import numpy as np
55
+ >>> from diffusers import WanAnimatePipeline
56
+ >>> from diffusers.utils import export_to_video, load_image, load_video
57
+
58
+ >>> model_id = "Wan-AI/Wan2.2-Animate-14B-Diffusers"
59
+ >>> pipe = WanAnimatePipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
60
+ >>> # Optionally upcast the Wan VAE to FP32
61
+ >>> pipe.vae.to(torch.float32)
62
+ >>> pipe.to("cuda")
63
+
64
+ >>> # Load the reference character image
65
+ >>> image = load_image(
66
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
67
+ ... )
68
+
69
+ >>> # Load pose and face videos (preprocessed from reference video)
70
+ >>> # Note: Videos should be preprocessed to extract pose keypoints and face features
71
+ >>> # Refer to the Wan-Animate preprocessing documentation for details
72
+ >>> pose_video = load_video("path/to/pose_video.mp4")
73
+ >>> face_video = load_video("path/to/face_video.mp4")
74
+
75
+ >>> # CFG is generally not used for Wan Animate
76
+ >>> prompt = (
77
+ ... "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in "
78
+ ... "the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
79
+ ... )
80
+
81
+ >>> # Animation mode: Animate the character with the motion from pose/face videos
82
+ >>> output = pipe(
83
+ ... image=image,
84
+ ... pose_video=pose_video,
85
+ ... face_video=face_video,
86
+ ... prompt=prompt,
87
+ ... height=height,
88
+ ... width=width,
89
+ ... segment_frame_length=77, # Frame length of each inference segment
90
+ ... guidance_scale=1.0,
91
+ ... num_inference_steps=20,
92
+ ... mode="animate",
93
+ ... ).frames[0]
94
+ >>> export_to_video(output, "output_animation.mp4", fps=30)
95
+
96
+ >>> # Replacement mode: Replace a character in the background video
97
+ >>> # Requires additional background_video and mask_video inputs
98
+ >>> background_video = load_video("path/to/background_video.mp4")
99
+ >>> mask_video = load_video("path/to/mask_video.mp4") # Black areas preserved, white areas generated
100
+ >>> output = pipe(
101
+ ... image=image,
102
+ ... pose_video=pose_video,
103
+ ... face_video=face_video,
104
+ ... background_video=background_video,
105
+ ... mask_video=mask_video,
106
+ ... prompt=prompt,
107
+ ... height=height,
108
+ ... width=width,
109
+ ... segment_frame_length=77, # Frame length of each inference segment
110
+ ... guidance_scale=1.0,
111
+ ... num_inference_steps=20,
112
+ ... mode="replace",
113
+ ... ).frames[0]
114
+ >>> export_to_video(output, "output_replacement.mp4", fps=30)
115
+ ```
116
+ """
117
+
118
+
119
+ def basic_clean(text):
120
+ text = ftfy.fix_text(text)
121
+ text = html.unescape(html.unescape(text))
122
+ return text.strip()
123
+
124
+
125
+ def whitespace_clean(text):
126
+ text = re.sub(r"\s+", " ", text)
127
+ text = text.strip()
128
+ return text
129
+
130
+
131
+ def prompt_clean(text):
132
+ text = whitespace_clean(basic_clean(text))
133
+ return text
134
+
135
+
136
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
137
+ def retrieve_latents(
138
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
139
+ ):
140
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
141
+ return encoder_output.latent_dist.sample(generator)
142
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
143
+ return encoder_output.latent_dist.mode()
144
+ elif hasattr(encoder_output, "latents"):
145
+ return encoder_output.latents
146
+ else:
147
+ raise AttributeError("Could not access latents of provided encoder_output")
148
+
149
+
150
+ class WanAnimatePipeline(DiffusionPipeline, WanLoraLoaderMixin):
151
+ r"""
152
+ Pipeline for unified character animation and replacement using Wan-Animate.
153
+
154
+ WanAnimatePipeline takes a character image, pose video, and face video as input, and generates a video in two
155
+ modes:
156
+
157
+ 1. **Animation mode**: The model generates a video of the character image that mimics the human motion in the input
158
+ pose and face videos. The character is animated based on the provided motion controls, creating a new animated
159
+ video of the character.
160
+
161
+ 2. **Replacement mode**: The model replaces a character in a background video with the provided character image,
162
+ using the pose and face videos for motion control. This mode requires additional `background_video` and
163
+ `mask_video` inputs. The mask video should have black regions where the original content should be preserved and
164
+ white regions where the new character should be generated.
165
+
166
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
167
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
168
+
169
+ The pipeline also inherits the following loading methods:
170
+ - [`~loaders.WanLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
171
+
172
+ Args:
173
+ tokenizer ([`T5Tokenizer`]):
174
+ Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
175
+ specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
176
+ text_encoder ([`T5EncoderModel`]):
177
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
178
+ the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
179
+ image_encoder ([`CLIPVisionModel`]):
180
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPVisionModel), specifically
181
+ the
182
+ [clip-vit-huge-patch14](https://github.com/mlfoundations/open_clip/blob/main/docs/PRETRAINED.md#vit-h14-xlm-roberta-large)
183
+ variant.
184
+ transformer ([`WanAnimateTransformer3DModel`]):
185
+ Conditional Transformer to denoise the input latents.
186
+ scheduler ([`UniPCMultistepScheduler`]):
187
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
188
+ vae ([`AutoencoderKLWan`]):
189
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
190
+ image_processor ([`CLIPImageProcessor`]):
191
+ Image processor for preprocessing images before encoding.
192
+ """
193
+
194
+ model_cpu_offload_seq = "text_encoder->image_encoder->transformer->vae"
195
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
196
+
197
+ def __init__(
198
+ self,
199
+ tokenizer: AutoTokenizer,
200
+ text_encoder: UMT5EncoderModel,
201
+ vae: AutoencoderKLWan,
202
+ scheduler: UniPCMultistepScheduler,
203
+ image_processor: CLIPImageProcessor,
204
+ image_encoder: CLIPVisionModel,
205
+ transformer: WanAnimateTransformer3DModel,
206
+ ):
207
+ super().__init__()
208
+
209
+ self.register_modules(
210
+ vae=vae,
211
+ text_encoder=text_encoder,
212
+ tokenizer=tokenizer,
213
+ image_encoder=image_encoder,
214
+ transformer=transformer,
215
+ scheduler=scheduler,
216
+ image_processor=image_processor,
217
+ )
218
+
219
+ self.vae_scale_factor_temporal = self.vae.config.scale_factor_temporal if getattr(self, "vae", None) else 4
220
+ self.vae_scale_factor_spatial = self.vae.config.scale_factor_spatial if getattr(self, "vae", None) else 8
221
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
222
+ self.video_processor_for_mask = VideoProcessor(
223
+ vae_scale_factor=self.vae_scale_factor_spatial, do_normalize=False, do_convert_grayscale=True
224
+ )
225
+ # In case self.transformer is None (e.g. for some pipeline tests)
226
+ spatial_patch_size = self.transformer.config.patch_size[-2:] if self.transformer is not None else (2, 2)
227
+ self.vae_image_processor = WanAnimateImageProcessor(
228
+ vae_scale_factor=self.vae_scale_factor_spatial,
229
+ spatial_patch_size=spatial_patch_size,
230
+ resample="bilinear",
231
+ fill_color=0,
232
+ )
233
+ self.image_processor = image_processor
234
+
235
+ def _get_t5_prompt_embeds(
236
+ self,
237
+ prompt: Union[str, List[str]] = None,
238
+ num_videos_per_prompt: int = 1,
239
+ max_sequence_length: int = 512,
240
+ device: Optional[torch.device] = None,
241
+ dtype: Optional[torch.dtype] = None,
242
+ ):
243
+ device = device or self._execution_device
244
+ dtype = dtype or self.text_encoder.dtype
245
+
246
+ prompt = [prompt] if isinstance(prompt, str) else prompt
247
+ prompt = [prompt_clean(u) for u in prompt]
248
+ batch_size = len(prompt)
249
+
250
+ text_inputs = self.tokenizer(
251
+ prompt,
252
+ padding="max_length",
253
+ max_length=max_sequence_length,
254
+ truncation=True,
255
+ add_special_tokens=True,
256
+ return_attention_mask=True,
257
+ return_tensors="pt",
258
+ )
259
+ text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
260
+ seq_lens = mask.gt(0).sum(dim=1).long()
261
+
262
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
263
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
264
+ prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
265
+ prompt_embeds = torch.stack(
266
+ [torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
267
+ )
268
+
269
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
270
+ _, seq_len, _ = prompt_embeds.shape
271
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
272
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
273
+
274
+ return prompt_embeds
275
+
276
+ # Copied from diffusers.pipelines.wan.pipeline_wan_i2v.WanImageToVideoPipeline.encode_image
277
+ def encode_image(
278
+ self,
279
+ image: PipelineImageInput,
280
+ device: Optional[torch.device] = None,
281
+ ):
282
+ device = device or self._execution_device
283
+ image = self.image_processor(images=image, return_tensors="pt").to(device)
284
+ image_embeds = self.image_encoder(**image, output_hidden_states=True)
285
+ return image_embeds.hidden_states[-2]
286
+
287
+ # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline.encode_prompt
288
+ def encode_prompt(
289
+ self,
290
+ prompt: Union[str, List[str]],
291
+ negative_prompt: Optional[Union[str, List[str]]] = None,
292
+ do_classifier_free_guidance: bool = True,
293
+ num_videos_per_prompt: int = 1,
294
+ prompt_embeds: Optional[torch.Tensor] = None,
295
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
296
+ max_sequence_length: int = 226,
297
+ device: Optional[torch.device] = None,
298
+ dtype: Optional[torch.dtype] = 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
+ negative_prompt (`str` or `List[str]`, *optional*):
307
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
308
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
309
+ less than `1`).
310
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
311
+ Whether to use classifier free guidance or not.
312
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
313
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
314
+ prompt_embeds (`torch.Tensor`, *optional*):
315
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
316
+ provided, text embeddings will be generated from `prompt` input argument.
317
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
318
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
319
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
320
+ argument.
321
+ device: (`torch.device`, *optional*):
322
+ torch device
323
+ dtype: (`torch.dtype`, *optional*):
324
+ torch dtype
325
+ """
326
+ device = device or self._execution_device
327
+
328
+ prompt = [prompt] if isinstance(prompt, str) else prompt
329
+ if prompt is not None:
330
+ batch_size = len(prompt)
331
+ else:
332
+ batch_size = prompt_embeds.shape[0]
333
+
334
+ if prompt_embeds is None:
335
+ prompt_embeds = self._get_t5_prompt_embeds(
336
+ prompt=prompt,
337
+ num_videos_per_prompt=num_videos_per_prompt,
338
+ max_sequence_length=max_sequence_length,
339
+ device=device,
340
+ dtype=dtype,
341
+ )
342
+
343
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
344
+ negative_prompt = negative_prompt or ""
345
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
346
+
347
+ if prompt is not None and type(prompt) is not type(negative_prompt):
348
+ raise TypeError(
349
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
350
+ f" {type(prompt)}."
351
+ )
352
+ elif batch_size != len(negative_prompt):
353
+ raise ValueError(
354
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
355
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
356
+ " the batch size of `prompt`."
357
+ )
358
+
359
+ negative_prompt_embeds = self._get_t5_prompt_embeds(
360
+ prompt=negative_prompt,
361
+ num_videos_per_prompt=num_videos_per_prompt,
362
+ max_sequence_length=max_sequence_length,
363
+ device=device,
364
+ dtype=dtype,
365
+ )
366
+
367
+ return prompt_embeds, negative_prompt_embeds
368
+
369
+ def check_inputs(
370
+ self,
371
+ prompt,
372
+ negative_prompt,
373
+ image,
374
+ pose_video,
375
+ face_video,
376
+ background_video,
377
+ mask_video,
378
+ height,
379
+ width,
380
+ prompt_embeds=None,
381
+ negative_prompt_embeds=None,
382
+ image_embeds=None,
383
+ callback_on_step_end_tensor_inputs=None,
384
+ mode=None,
385
+ prev_segment_conditioning_frames=None,
386
+ ):
387
+ if image is not None and image_embeds is not None:
388
+ raise ValueError(
389
+ f"Cannot forward both `image`: {image} and `image_embeds`: {image_embeds}. Please make sure to"
390
+ " only forward one of the two."
391
+ )
392
+ if image is None and image_embeds is None:
393
+ raise ValueError(
394
+ "Provide either `image` or `prompt_embeds`. Cannot leave both `image` and `image_embeds` undefined."
395
+ )
396
+ if image is not None and not isinstance(image, torch.Tensor) and not isinstance(image, PIL.Image.Image):
397
+ raise ValueError(f"`image` has to be of type `torch.Tensor` or `PIL.Image.Image` but is {type(image)}")
398
+ if pose_video is None:
399
+ raise ValueError("Provide `pose_video`. Cannot leave `pose_video` undefined.")
400
+ if face_video is None:
401
+ raise ValueError("Provide `face_video`. Cannot leave `face_video` undefined.")
402
+ if not isinstance(pose_video, list) or not isinstance(face_video, list):
403
+ raise ValueError("`pose_video` and `face_video` must be lists of PIL images.")
404
+ if len(pose_video) == 0 or len(face_video) == 0:
405
+ raise ValueError("`pose_video` and `face_video` must contain at least one frame.")
406
+ if mode == "replace" and (background_video is None or mask_video is None):
407
+ raise ValueError(
408
+ "Provide `background_video` and `mask_video`. Cannot leave both `background_video` and `mask_video`"
409
+ " undefined when mode is `replace`."
410
+ )
411
+ if mode == "replace" and (not isinstance(background_video, list) or not isinstance(mask_video, list)):
412
+ raise ValueError("`background_video` and `mask_video` must be lists of PIL images when mode is `replace`.")
413
+
414
+ if height % 16 != 0 or width % 16 != 0:
415
+ raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
416
+
417
+ if callback_on_step_end_tensor_inputs is not None and not all(
418
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
419
+ ):
420
+ raise ValueError(
421
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found"
422
+ f" {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
423
+ )
424
+
425
+ if prompt is not None and prompt_embeds is not None:
426
+ raise ValueError(
427
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
428
+ " only forward one of the two."
429
+ )
430
+ elif negative_prompt is not None and negative_prompt_embeds is not None:
431
+ raise ValueError(
432
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
433
+ " only forward one of the two."
434
+ )
435
+ elif prompt is None and prompt_embeds is None:
436
+ raise ValueError(
437
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
438
+ )
439
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
440
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
441
+ elif negative_prompt is not None and (
442
+ not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
443
+ ):
444
+ raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
445
+
446
+ if mode is not None and (not isinstance(mode, str) or mode not in ("animate", "replace")):
447
+ raise ValueError(
448
+ f"`mode` has to be of type `str` and in ('animate', 'replace') but its type is {type(mode)} and value is {mode}"
449
+ )
450
+
451
+ if prev_segment_conditioning_frames is not None and (
452
+ not isinstance(prev_segment_conditioning_frames, int) or prev_segment_conditioning_frames not in (1, 5)
453
+ ):
454
+ raise ValueError(
455
+ f"`prev_segment_conditioning_frames` has to be of type `int` and 1 or 5 but its type is"
456
+ f" {type(prev_segment_conditioning_frames)} and value is {prev_segment_conditioning_frames}"
457
+ )
458
+
459
+ def get_i2v_mask(
460
+ self,
461
+ batch_size: int,
462
+ latent_t: int,
463
+ latent_h: int,
464
+ latent_w: int,
465
+ mask_len: int = 1,
466
+ mask_pixel_values: Optional[torch.Tensor] = None,
467
+ dtype: Optional[torch.dtype] = None,
468
+ device: Union[str, torch.device] = "cuda",
469
+ ) -> torch.Tensor:
470
+ # mask_pixel_values shape (if supplied): [B, C = 1, T, latent_h, latent_w]
471
+ if mask_pixel_values is None:
472
+ mask_lat_size = torch.zeros(
473
+ batch_size, 1, (latent_t - 1) * 4 + 1, latent_h, latent_w, dtype=dtype, device=device
474
+ )
475
+ else:
476
+ mask_lat_size = mask_pixel_values.clone().to(device=device, dtype=dtype)
477
+ mask_lat_size[:, :, :mask_len] = 1
478
+ first_frame_mask = mask_lat_size[:, :, 0:1]
479
+ # Repeat first frame mask self.vae_scale_factor_temporal (= 4) times in the frame dimension
480
+ first_frame_mask = torch.repeat_interleave(first_frame_mask, dim=2, repeats=self.vae_scale_factor_temporal)
481
+ mask_lat_size = torch.concat([first_frame_mask, mask_lat_size[:, :, 1:]], dim=2)
482
+ mask_lat_size = mask_lat_size.view(
483
+ batch_size, -1, self.vae_scale_factor_temporal, latent_h, latent_w
484
+ ).transpose(1, 2) # [B, C = 1, 4 * T_lat, H_lat, W_lat] --> [B, C = 4, T_lat, H_lat, W_lat]
485
+
486
+ return mask_lat_size
487
+
488
+ def prepare_reference_image_latents(
489
+ self,
490
+ image: torch.Tensor,
491
+ batch_size: int = 1,
492
+ sample_mode: int = "argmax",
493
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
494
+ dtype: Optional[torch.dtype] = None,
495
+ device: Optional[torch.device] = None,
496
+ ) -> torch.Tensor:
497
+ # image shape: (B, C, H, W) or (B, C, T, H, W)
498
+ dtype = dtype or self.vae.dtype
499
+ if image.ndim == 4:
500
+ # Add a singleton frame dimension after the channels dimension
501
+ image = image.unsqueeze(2)
502
+
503
+ _, _, _, height, width = image.shape
504
+ latent_height = height // self.vae_scale_factor_spatial
505
+ latent_width = width // self.vae_scale_factor_spatial
506
+
507
+ # Encode image to latents using VAE
508
+ image = image.to(device=device, dtype=dtype)
509
+ if isinstance(generator, list):
510
+ # Like in prepare_latents, assume len(generator) == batch_size
511
+ ref_image_latents = [
512
+ retrieve_latents(self.vae.encode(image), generator=g, sample_mode=sample_mode) for g in generator
513
+ ]
514
+ ref_image_latents = torch.cat(ref_image_latents)
515
+ else:
516
+ ref_image_latents = retrieve_latents(self.vae.encode(image), generator, sample_mode)
517
+ # Standardize latents in preparation for Wan VAE encode
518
+ latents_mean = (
519
+ torch.tensor(self.vae.config.latents_mean)
520
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
521
+ .to(ref_image_latents.device, ref_image_latents.dtype)
522
+ )
523
+ latents_recip_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
524
+ ref_image_latents.device, ref_image_latents.dtype
525
+ )
526
+ ref_image_latents = (ref_image_latents - latents_mean) * latents_recip_std
527
+ # Handle the case where we supply one image and one generator, but batch_size > 1 (e.g. generating multiple
528
+ # videos per prompt)
529
+ if ref_image_latents.shape[0] == 1 and batch_size > 1:
530
+ ref_image_latents = ref_image_latents.expand(batch_size, -1, -1, -1, -1)
531
+
532
+ # Prepare I2V mask in latent space and prepend to the reference image latents along channel dim
533
+ reference_image_mask = self.get_i2v_mask(batch_size, 1, latent_height, latent_width, 1, None, dtype, device)
534
+ reference_image_latents = torch.cat([reference_image_mask, ref_image_latents], dim=1)
535
+
536
+ return reference_image_latents
537
+
538
+ def prepare_prev_segment_cond_latents(
539
+ self,
540
+ prev_segment_cond_video: Optional[torch.Tensor] = None,
541
+ background_video: Optional[torch.Tensor] = None,
542
+ mask_video: Optional[torch.Tensor] = None,
543
+ batch_size: int = 1,
544
+ segment_frame_length: int = 77,
545
+ start_frame: int = 0,
546
+ height: int = 720,
547
+ width: int = 1280,
548
+ prev_segment_cond_frames: int = 1,
549
+ task: str = "animate",
550
+ interpolation_mode: str = "bicubic",
551
+ sample_mode: str = "argmax",
552
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
553
+ dtype: Optional[torch.dtype] = None,
554
+ device: Optional[torch.device] = None,
555
+ ) -> torch.Tensor:
556
+ # prev_segment_cond_video shape: (B, C, T, H, W) in pixel space if supplied
557
+ # background_video shape: (B, C, T, H, W) (same as prev_segment_cond_video shape)
558
+ # mask_video shape: (B, 1, T, H, W) (same as prev_segment_cond_video, but with only 1 channel)
559
+ dtype = dtype or self.vae.dtype
560
+ if prev_segment_cond_video is None:
561
+ if task == "replace":
562
+ prev_segment_cond_video = background_video[:, :, :prev_segment_cond_frames].to(dtype)
563
+ else:
564
+ cond_frames_shape = (batch_size, 3, prev_segment_cond_frames, height, width) # In pixel space
565
+ prev_segment_cond_video = torch.zeros(cond_frames_shape, dtype=dtype, device=device)
566
+
567
+ data_batch_size, channels, _, segment_height, segment_width = prev_segment_cond_video.shape
568
+ num_latent_frames = (segment_frame_length - 1) // self.vae_scale_factor_temporal + 1
569
+ latent_height = height // self.vae_scale_factor_spatial
570
+ latent_width = width // self.vae_scale_factor_spatial
571
+ if segment_height != height or segment_width != width:
572
+ print(
573
+ f"Interpolating prev segment cond video from ({segment_width}, {segment_height}) to ({width}, {height})"
574
+ )
575
+ # Perform a 4D (spatial) rather than a 5D (spatiotemporal) reshape, following the original code
576
+ prev_segment_cond_video = prev_segment_cond_video.transpose(1, 2).flatten(0, 1) # [B * T, C, H, W]
577
+ prev_segment_cond_video = F.interpolate(
578
+ prev_segment_cond_video, size=(height, width), mode=interpolation_mode
579
+ )
580
+ prev_segment_cond_video = prev_segment_cond_video.unflatten(0, (batch_size, -1)).transpose(1, 2)
581
+
582
+ # Fill the remaining part of the cond video segment with zeros (if animating) or the background video (if
583
+ # replacing).
584
+ if task == "replace":
585
+ remaining_segment = background_video[:, :, prev_segment_cond_frames:].to(dtype)
586
+ else:
587
+ remaining_segment_frames = segment_frame_length - prev_segment_cond_frames
588
+ remaining_segment = torch.zeros(
589
+ batch_size, channels, remaining_segment_frames, height, width, dtype=dtype, device=device
590
+ )
591
+
592
+ # Prepend the conditioning frames from the previous segment to the remaining segment video in the frame dim
593
+ prev_segment_cond_video = prev_segment_cond_video.to(dtype=dtype)
594
+ full_segment_cond_video = torch.cat([prev_segment_cond_video, remaining_segment], dim=2)
595
+
596
+ if isinstance(generator, list):
597
+ if data_batch_size == len(generator):
598
+ prev_segment_cond_latents = [
599
+ retrieve_latents(self.vae.encode(full_segment_cond_video[i].unsqueeze(0)), g, sample_mode)
600
+ for i, g in enumerate(generator)
601
+ ]
602
+ elif data_batch_size == 1:
603
+ # Like prepare_latents, assume len(generator) == batch_size
604
+ prev_segment_cond_latents = [
605
+ retrieve_latents(self.vae.encode(full_segment_cond_video), g, sample_mode) for g in generator
606
+ ]
607
+ else:
608
+ raise ValueError(
609
+ f"The batch size of the prev segment video should be either {len(generator)} or 1 but is"
610
+ f" {data_batch_size}"
611
+ )
612
+ prev_segment_cond_latents = torch.cat(prev_segment_cond_latents)
613
+ else:
614
+ prev_segment_cond_latents = retrieve_latents(
615
+ self.vae.encode(full_segment_cond_video), generator, sample_mode
616
+ )
617
+ # Standardize latents in preparation for Wan VAE encode
618
+ latents_mean = (
619
+ torch.tensor(self.vae.config.latents_mean)
620
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
621
+ .to(prev_segment_cond_latents.device, prev_segment_cond_latents.dtype)
622
+ )
623
+ latents_recip_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
624
+ prev_segment_cond_latents.device, prev_segment_cond_latents.dtype
625
+ )
626
+ prev_segment_cond_latents = (prev_segment_cond_latents - latents_mean) * latents_recip_std
627
+
628
+ # Prepare I2V mask
629
+ if task == "replace":
630
+ mask_video = 1 - mask_video
631
+ mask_video = mask_video.permute(0, 2, 1, 3, 4)
632
+ mask_video = mask_video.flatten(0, 1)
633
+ mask_video = F.interpolate(mask_video, size=(latent_height, latent_width), mode="nearest")
634
+ mask_pixel_values = mask_video.unflatten(0, (batch_size, -1))
635
+ mask_pixel_values = mask_pixel_values.permute(0, 2, 1, 3, 4) # output shape: [B, C = 1, T, H_lat, W_lat]
636
+ else:
637
+ mask_pixel_values = None
638
+ prev_segment_cond_mask = self.get_i2v_mask(
639
+ batch_size,
640
+ num_latent_frames,
641
+ latent_height,
642
+ latent_width,
643
+ mask_len=prev_segment_cond_frames if start_frame > 0 else 0,
644
+ mask_pixel_values=mask_pixel_values,
645
+ dtype=dtype,
646
+ device=device,
647
+ )
648
+
649
+ # Prepend cond I2V mask to prev segment cond latents along channel dimension
650
+ prev_segment_cond_latents = torch.cat([prev_segment_cond_mask, prev_segment_cond_latents], dim=1)
651
+ return prev_segment_cond_latents
652
+
653
+ def prepare_pose_latents(
654
+ self,
655
+ pose_video: torch.Tensor,
656
+ batch_size: int = 1,
657
+ sample_mode: int = "argmax",
658
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
659
+ dtype: Optional[torch.dtype] = None,
660
+ device: Optional[torch.device] = None,
661
+ ) -> torch.Tensor:
662
+ # pose_video shape: (B, C, T, H, W)
663
+ pose_video = pose_video.to(device=device, dtype=dtype if dtype is not None else self.vae.dtype)
664
+ if isinstance(generator, list):
665
+ pose_latents = [
666
+ retrieve_latents(self.vae.encode(pose_video), generator=g, sample_mode=sample_mode) for g in generator
667
+ ]
668
+ pose_latents = torch.cat(pose_latents)
669
+ else:
670
+ pose_latents = retrieve_latents(self.vae.encode(pose_video), generator, sample_mode)
671
+ # Standardize latents in preparation for Wan VAE encode
672
+ latents_mean = (
673
+ torch.tensor(self.vae.config.latents_mean)
674
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
675
+ .to(pose_latents.device, pose_latents.dtype)
676
+ )
677
+ latents_recip_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
678
+ pose_latents.device, pose_latents.dtype
679
+ )
680
+ pose_latents = (pose_latents - latents_mean) * latents_recip_std
681
+ if pose_latents.shape[0] == 1 and batch_size > 1:
682
+ pose_latents = pose_latents.expand(batch_size, -1, -1, -1, -1)
683
+ return pose_latents
684
+
685
+ def prepare_latents(
686
+ self,
687
+ batch_size: int,
688
+ num_channels_latents: int = 16,
689
+ height: int = 720,
690
+ width: int = 1280,
691
+ num_frames: int = 77,
692
+ dtype: Optional[torch.dtype] = None,
693
+ device: Optional[torch.device] = None,
694
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
695
+ latents: Optional[torch.Tensor] = None,
696
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
697
+ num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
698
+ latent_height = height // self.vae_scale_factor_spatial
699
+ latent_width = width // self.vae_scale_factor_spatial
700
+
701
+ shape = (batch_size, num_channels_latents, num_latent_frames + 1, latent_height, latent_width)
702
+ if isinstance(generator, list) and len(generator) != batch_size:
703
+ raise ValueError(
704
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
705
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
706
+ )
707
+
708
+ if latents is None:
709
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
710
+ else:
711
+ latents = latents.to(device=device, dtype=dtype)
712
+
713
+ return latents
714
+
715
+ def pad_video_frames(self, frames: List[Any], num_target_frames: int) -> List[Any]:
716
+ """
717
+ Pads an array-like video `frames` to `num_target_frames` using a "reflect"-like strategy. The frame dimension
718
+ is assumed to be the first dimension. In the 1D case, we can visualize this strategy as follows:
719
+
720
+ pad_video_frames([1, 2, 3, 4, 5], 10) -> [1, 2, 3, 4, 5, 4, 3, 2, 1, 2]
721
+ """
722
+ idx = 0
723
+ flip = False
724
+ target_frames = []
725
+ while len(target_frames) < num_target_frames:
726
+ target_frames.append(deepcopy(frames[idx]))
727
+ if flip:
728
+ idx -= 1
729
+ else:
730
+ idx += 1
731
+ if idx == 0 or idx == len(frames) - 1:
732
+ flip = not flip
733
+
734
+ return target_frames
735
+
736
+ @property
737
+ def guidance_scale(self):
738
+ return self._guidance_scale
739
+
740
+ @property
741
+ def do_classifier_free_guidance(self):
742
+ return self._guidance_scale > 1
743
+
744
+ @property
745
+ def num_timesteps(self):
746
+ return self._num_timesteps
747
+
748
+ @property
749
+ def current_timestep(self):
750
+ return self._current_timestep
751
+
752
+ @property
753
+ def interrupt(self):
754
+ return self._interrupt
755
+
756
+ @property
757
+ def attention_kwargs(self):
758
+ return self._attention_kwargs
759
+
760
+ @torch.no_grad()
761
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
762
+ def __call__(
763
+ self,
764
+ image: PipelineImageInput,
765
+ pose_video: List[PIL.Image.Image],
766
+ face_video: List[PIL.Image.Image],
767
+ background_video: Optional[List[PIL.Image.Image]] = None,
768
+ mask_video: Optional[List[PIL.Image.Image]] = None,
769
+ prompt: Union[str, List[str]] = None,
770
+ negative_prompt: Union[str, List[str]] = None,
771
+ height: int = 720,
772
+ width: int = 1280,
773
+ segment_frame_length: int = 77,
774
+ num_inference_steps: int = 20,
775
+ mode: str = "animate",
776
+ prev_segment_conditioning_frames: int = 1,
777
+ motion_encode_batch_size: Optional[int] = None,
778
+ guidance_scale: float = 1.0,
779
+ num_videos_per_prompt: Optional[int] = 1,
780
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
781
+ latents: Optional[torch.Tensor] = None,
782
+ prompt_embeds: Optional[torch.Tensor] = None,
783
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
784
+ image_embeds: Optional[torch.Tensor] = None,
785
+ output_type: Optional[str] = "np",
786
+ return_dict: bool = True,
787
+ attention_kwargs: Optional[Dict[str, Any]] = None,
788
+ callback_on_step_end: Optional[
789
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
790
+ ] = None,
791
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
792
+ max_sequence_length: int = 512,
793
+ ):
794
+ r"""
795
+ The call function to the pipeline for generation.
796
+
797
+ Args:
798
+ image (`PipelineImageInput`):
799
+ The input character image to condition the generation on. Must be an image, a list of images or a
800
+ `torch.Tensor`.
801
+ pose_video (`List[PIL.Image.Image]`):
802
+ The input pose video to condition the generation on. Must be a list of PIL images.
803
+ face_video (`List[PIL.Image.Image]`):
804
+ The input face video to condition the generation on. Must be a list of PIL images.
805
+ background_video (`List[PIL.Image.Image]`, *optional*):
806
+ When mode is `"replace"`, the input background video to condition the generation on. Must be a list of
807
+ PIL images.
808
+ mask_video (`List[PIL.Image.Image]`, *optional*):
809
+ When mode is `"replace"`, the input mask video to condition the generation on. Must be a list of PIL
810
+ images.
811
+ prompt (`str` or `List[str]`, *optional*):
812
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
813
+ instead.
814
+ negative_prompt (`str` or `List[str]`, *optional*):
815
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
816
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
817
+ less than `1`).
818
+ mode (`str`, defaults to `"animation"`):
819
+ The mode of the generation. Choose between `"animate"` and `"replace"`.
820
+ prev_segment_conditioning_frames (`int`, defaults to `1`):
821
+ The number of frames from the previous video segment to be used for temporal guidance. Recommended to
822
+ be 1 or 5. In general, should be 4N + 1, where N is a non-negative integer.
823
+ motion_encode_batch_size (`int`, *optional*):
824
+ The batch size for batched encoding of the face video via the motion encoder. This allows trading off
825
+ inference speed for lower memory usage by setting a smaller batch size. Will default to
826
+ `self.transformer.config.motion_encoder_batch_size` if not set.
827
+ height (`int`, defaults to `720`):
828
+ The height of the generated video.
829
+ width (`int`, defaults to `1280`):
830
+ The width of the generated video.
831
+ segment_frame_length (`int`, defaults to `77`):
832
+ The number of frames in each generated video segment. The total frames of video generated will be equal
833
+ to the number of frames in `pose_video`; we will generate the video in segments until we have hit this
834
+ length. In general, should be 4N + 1, where N is a non-negative integer.
835
+ num_inference_steps (`int`, defaults to `20`):
836
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
837
+ expense of slower inference.
838
+ guidance_scale (`float`, defaults to `1.0`):
839
+ Guidance scale as defined in [Classifier-Free Diffusion
840
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
841
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
842
+ `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
843
+ the text `prompt`, usually at the expense of lower image quality. By default, CFG is not used in Wan
844
+ Animate inference.
845
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
846
+ The number of images to generate per prompt.
847
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
848
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
849
+ generation deterministic.
850
+ latents (`torch.Tensor`, *optional*):
851
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
852
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
853
+ tensor is generated by sampling using the supplied random `generator`.
854
+ prompt_embeds (`torch.Tensor`, *optional*):
855
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
856
+ provided, text embeddings are generated from the `prompt` input argument.
857
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
858
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
859
+ provided, text embeddings are generated from the `negative_prompt` input argument.
860
+ image_embeds (`torch.Tensor`, *optional*):
861
+ Pre-generated image embeddings. Can be used to easily tweak image inputs (weighting). If not provided,
862
+ image embeddings are generated from the `image` input argument.
863
+ output_type (`str`, *optional*, defaults to `"np"`):
864
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
865
+ return_dict (`bool`, *optional*, defaults to `True`):
866
+ Whether or not to return a [`WanPipelineOutput`] instead of a plain tuple.
867
+ attention_kwargs (`dict`, *optional*):
868
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
869
+ `self.processor` in
870
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
871
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
872
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
873
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
874
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
875
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
876
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
877
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
878
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
879
+ `._callback_tensor_inputs` attribute of your pipeline class.
880
+ max_sequence_length (`int`, defaults to `512`):
881
+ The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
882
+ truncated. If the prompt is shorter, it will be padded to this length.
883
+
884
+ Examples:
885
+
886
+ Returns:
887
+ [`~WanPipelineOutput`] or `tuple`:
888
+ If `return_dict` is `True`, [`WanPipelineOutput`] is returned, otherwise a `tuple` is returned where
889
+ the first element is a list with the generated images and the second element is a list of `bool`s
890
+ indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
891
+ """
892
+
893
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
894
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
895
+
896
+ # 1. Check inputs. Raise error if not correct
897
+ self.check_inputs(
898
+ prompt,
899
+ negative_prompt,
900
+ image,
901
+ pose_video,
902
+ face_video,
903
+ background_video,
904
+ mask_video,
905
+ height,
906
+ width,
907
+ prompt_embeds,
908
+ negative_prompt_embeds,
909
+ image_embeds,
910
+ callback_on_step_end_tensor_inputs,
911
+ mode,
912
+ prev_segment_conditioning_frames,
913
+ )
914
+
915
+ if segment_frame_length % self.vae_scale_factor_temporal != 1:
916
+ logger.warning(
917
+ f"`segment_frame_length - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the"
918
+ f" nearest number."
919
+ )
920
+ segment_frame_length = (
921
+ segment_frame_length // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
922
+ )
923
+ segment_frame_length = max(segment_frame_length, 1)
924
+
925
+ self._guidance_scale = guidance_scale
926
+ self._attention_kwargs = attention_kwargs
927
+ self._current_timestep = None
928
+ self._interrupt = False
929
+
930
+ device = self._execution_device
931
+
932
+ # 2. Define call parameters
933
+ if prompt is not None and isinstance(prompt, str):
934
+ batch_size = 1
935
+ elif prompt is not None and isinstance(prompt, list):
936
+ batch_size = len(prompt)
937
+ else:
938
+ batch_size = prompt_embeds.shape[0]
939
+
940
+ # As we generate in segments of `segment_frame_length`, set the target frame length to be the least multiple
941
+ # of the effective segment length greater than or equal to the length of `pose_video`.
942
+ cond_video_frames = len(pose_video)
943
+ effective_segment_length = segment_frame_length - prev_segment_conditioning_frames
944
+ last_segment_frames = (cond_video_frames - prev_segment_conditioning_frames) % effective_segment_length
945
+ if last_segment_frames == 0:
946
+ num_padding_frames = 0
947
+ else:
948
+ num_padding_frames = effective_segment_length - last_segment_frames
949
+ num_target_frames = cond_video_frames + num_padding_frames
950
+ num_segments = num_target_frames // effective_segment_length
951
+
952
+ # 3. Encode input prompt
953
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
954
+ prompt=prompt,
955
+ negative_prompt=negative_prompt,
956
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
957
+ num_videos_per_prompt=num_videos_per_prompt,
958
+ prompt_embeds=prompt_embeds,
959
+ negative_prompt_embeds=negative_prompt_embeds,
960
+ max_sequence_length=max_sequence_length,
961
+ device=device,
962
+ )
963
+
964
+ transformer_dtype = self.transformer.dtype
965
+ prompt_embeds = prompt_embeds.to(transformer_dtype)
966
+ if negative_prompt_embeds is not None:
967
+ negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
968
+
969
+ # 4. Preprocess and encode the reference (character) image
970
+ image_height, image_width = self.video_processor.get_default_height_width(image)
971
+ if image_height != height or image_width != width:
972
+ logger.warning(f"Reshaping reference image from ({image_width}, {image_height}) to ({width}, {height})")
973
+ image_pixels = self.vae_image_processor.preprocess(image, height=height, width=width, resize_mode="fill").to(
974
+ device, dtype=torch.float32
975
+ )
976
+
977
+ # Get CLIP features from the reference image
978
+ if image_embeds is None:
979
+ image_embeds = self.encode_image(image, device)
980
+ image_embeds = image_embeds.repeat(batch_size * num_videos_per_prompt, 1, 1)
981
+ image_embeds = image_embeds.to(transformer_dtype)
982
+
983
+ # 5. Encode conditioning videos (pose, face)
984
+ pose_video = self.pad_video_frames(pose_video, num_target_frames)
985
+ face_video = self.pad_video_frames(face_video, num_target_frames)
986
+
987
+ # TODO: also support np.ndarray input (e.g. from decord like the original implementation?)
988
+ pose_video_width, pose_video_height = pose_video[0].size
989
+ if pose_video_height != height or pose_video_width != width:
990
+ logger.warning(
991
+ f"Reshaping pose video from ({pose_video_width}, {pose_video_height}) to ({width}, {height})"
992
+ )
993
+ pose_video = self.video_processor.preprocess_video(pose_video, height=height, width=width).to(
994
+ device, dtype=torch.float32
995
+ )
996
+
997
+ face_video_width, face_video_height = face_video[0].size
998
+ expected_face_size = self.transformer.config.motion_encoder_size
999
+ if face_video_width != expected_face_size or face_video_height != expected_face_size:
1000
+ logger.warning(
1001
+ f"Reshaping face video from ({face_video_width}, {face_video_height}) to ({expected_face_size},"
1002
+ f" {expected_face_size})"
1003
+ )
1004
+ face_video = self.video_processor.preprocess_video(
1005
+ face_video, height=expected_face_size, width=expected_face_size
1006
+ ).to(device, dtype=torch.float32)
1007
+
1008
+ if mode == "replace":
1009
+ background_video = self.pad_video_frames(background_video, num_target_frames)
1010
+ mask_video = self.pad_video_frames(mask_video, num_target_frames)
1011
+
1012
+ background_video = self.video_processor.preprocess_video(background_video, height=height, width=width).to(
1013
+ device, dtype=torch.float32
1014
+ )
1015
+ mask_video = self.video_processor_for_mask.preprocess_video(mask_video, height=height, width=width).to(
1016
+ device, dtype=torch.float32
1017
+ )
1018
+
1019
+ # 6. Prepare timesteps
1020
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1021
+ timesteps = self.scheduler.timesteps
1022
+
1023
+ # 7. Prepare latent variables which stay constant for all inference segments
1024
+ num_channels_latents = self.vae.config.z_dim
1025
+
1026
+ # Get VAE-encoded latents of the reference (character) image
1027
+ reference_image_latents = self.prepare_reference_image_latents(
1028
+ image_pixels, batch_size * num_videos_per_prompt, generator=generator, device=device
1029
+ )
1030
+
1031
+ # 8. Loop over video inference segments
1032
+ start = 0
1033
+ end = segment_frame_length # Data space frames, not latent frames
1034
+ all_out_frames = []
1035
+ out_frames = None
1036
+
1037
+ for _ in range(num_segments):
1038
+ assert start + prev_segment_conditioning_frames < cond_video_frames
1039
+
1040
+ # Sample noisy latents from prior for the current inference segment
1041
+ latents = self.prepare_latents(
1042
+ batch_size * num_videos_per_prompt,
1043
+ num_channels_latents=num_channels_latents,
1044
+ height=height,
1045
+ width=width,
1046
+ num_frames=segment_frame_length,
1047
+ dtype=torch.float32,
1048
+ device=device,
1049
+ generator=generator,
1050
+ latents=latents if start == 0 else None, # Only use pre-calculated latents for first segment
1051
+ )
1052
+
1053
+ pose_video_segment = pose_video[:, :, start:end]
1054
+ face_video_segment = face_video[:, :, start:end]
1055
+
1056
+ face_video_segment = face_video_segment.expand(batch_size * num_videos_per_prompt, -1, -1, -1, -1)
1057
+ face_video_segment = face_video_segment.to(dtype=transformer_dtype)
1058
+
1059
+ if start > 0:
1060
+ prev_segment_cond_video = out_frames[:, :, -prev_segment_conditioning_frames:].clone().detach()
1061
+ else:
1062
+ prev_segment_cond_video = None
1063
+
1064
+ if mode == "replace":
1065
+ background_video_segment = background_video[:, :, start:end]
1066
+ mask_video_segment = mask_video[:, :, start:end]
1067
+
1068
+ background_video_segment = background_video_segment.expand(
1069
+ batch_size * num_videos_per_prompt, -1, -1, -1, -1
1070
+ )
1071
+ mask_video_segment = mask_video_segment.expand(batch_size * num_videos_per_prompt, -1, -1, -1, -1)
1072
+ else:
1073
+ background_video_segment = None
1074
+ mask_video_segment = None
1075
+
1076
+ pose_latents = self.prepare_pose_latents(
1077
+ pose_video_segment, batch_size * num_videos_per_prompt, generator=generator, device=device
1078
+ )
1079
+ pose_latents = pose_latents.to(dtype=transformer_dtype)
1080
+
1081
+ prev_segment_cond_latents = self.prepare_prev_segment_cond_latents(
1082
+ prev_segment_cond_video,
1083
+ background_video=background_video_segment,
1084
+ mask_video=mask_video_segment,
1085
+ batch_size=batch_size * num_videos_per_prompt,
1086
+ segment_frame_length=segment_frame_length,
1087
+ start_frame=start,
1088
+ height=height,
1089
+ width=width,
1090
+ prev_segment_cond_frames=prev_segment_conditioning_frames,
1091
+ task=mode,
1092
+ generator=generator,
1093
+ device=device,
1094
+ )
1095
+
1096
+ # Concatenate the reference latents in the frame dimension
1097
+ reference_latents = torch.cat([reference_image_latents, prev_segment_cond_latents], dim=2)
1098
+
1099
+ # 8.1 Denoising loop
1100
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1101
+ self._num_timesteps = len(timesteps)
1102
+
1103
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1104
+ for i, t in enumerate(timesteps):
1105
+ if self.interrupt:
1106
+ continue
1107
+
1108
+ self._current_timestep = t
1109
+
1110
+ # Concatenate the reference image + prev segment conditioning in the channel dim
1111
+ latent_model_input = torch.cat([latents, reference_latents], dim=1).to(transformer_dtype)
1112
+ timestep = t.expand(latents.shape[0])
1113
+
1114
+ with self.transformer.cache_context("cond"):
1115
+ noise_pred = self.transformer(
1116
+ hidden_states=latent_model_input,
1117
+ timestep=timestep,
1118
+ encoder_hidden_states=prompt_embeds,
1119
+ encoder_hidden_states_image=image_embeds,
1120
+ pose_hidden_states=pose_latents,
1121
+ face_pixel_values=face_video_segment,
1122
+ motion_encode_batch_size=motion_encode_batch_size,
1123
+ attention_kwargs=attention_kwargs,
1124
+ return_dict=False,
1125
+ )[0]
1126
+
1127
+ if self.do_classifier_free_guidance:
1128
+ # Blank out face for unconditional guidance (set all pixels to -1)
1129
+ face_pixel_values_uncond = face_video_segment * 0 - 1
1130
+ with self.transformer.cache_context("uncond"):
1131
+ noise_uncond = self.transformer(
1132
+ hidden_states=latent_model_input,
1133
+ timestep=timestep,
1134
+ encoder_hidden_states=negative_prompt_embeds,
1135
+ encoder_hidden_states_image=image_embeds,
1136
+ pose_hidden_states=pose_latents,
1137
+ face_pixel_values=face_pixel_values_uncond,
1138
+ motion_encode_batch_size=motion_encode_batch_size,
1139
+ attention_kwargs=attention_kwargs,
1140
+ return_dict=False,
1141
+ )[0]
1142
+ noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)
1143
+
1144
+ # compute the previous noisy sample x_t -> x_t-1
1145
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
1146
+
1147
+ if callback_on_step_end is not None:
1148
+ callback_kwargs = {}
1149
+ for k in callback_on_step_end_tensor_inputs:
1150
+ callback_kwargs[k] = locals()[k]
1151
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1152
+
1153
+ latents = callback_outputs.pop("latents", latents)
1154
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1155
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1156
+
1157
+ # call the callback, if provided
1158
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1159
+ progress_bar.update()
1160
+
1161
+ if XLA_AVAILABLE:
1162
+ xm.mark_step()
1163
+
1164
+ latents = latents.to(self.vae.dtype)
1165
+ # Destandardize latents in preparation for Wan VAE decoding
1166
+ latents_mean = (
1167
+ torch.tensor(self.vae.config.latents_mean)
1168
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
1169
+ .to(latents.device, latents.dtype)
1170
+ )
1171
+ latents_recip_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(
1172
+ 1, self.vae.config.z_dim, 1, 1, 1
1173
+ ).to(latents.device, latents.dtype)
1174
+ latents = latents / latents_recip_std + latents_mean
1175
+ # Skip the first latent frame (used for conditioning)
1176
+ out_frames = self.vae.decode(latents[:, :, 1:], return_dict=False)[0]
1177
+
1178
+ if start > 0:
1179
+ out_frames = out_frames[:, :, prev_segment_conditioning_frames:]
1180
+ all_out_frames.append(out_frames)
1181
+
1182
+ start += effective_segment_length
1183
+ end += effective_segment_length
1184
+
1185
+ # Reset scheduler timesteps / state for next denoising loop
1186
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1187
+ timesteps = self.scheduler.timesteps
1188
+
1189
+ self._current_timestep = None
1190
+ assert start + prev_segment_conditioning_frames >= cond_video_frames
1191
+
1192
+ if not output_type == "latent":
1193
+ video = torch.cat(all_out_frames, dim=2)[:, :, :cond_video_frames]
1194
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
1195
+ else:
1196
+ video = latents
1197
+
1198
+ # Offload all models
1199
+ self.maybe_free_model_hooks()
1200
+
1201
+ if not return_dict:
1202
+ return (video,)
1203
+
1204
+ return WanPipelineOutput(frames=video)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wan/pipeline_wan_i2v.py ADDED
@@ -0,0 +1,824 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The Wan Team and 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 html
16
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
17
+
18
+ import PIL
19
+ import regex as re
20
+ import torch
21
+ from transformers import AutoTokenizer, CLIPImageProcessor, CLIPVisionModel, UMT5EncoderModel
22
+
23
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
24
+ from ...image_processor import PipelineImageInput
25
+ from ...loaders import WanLoraLoaderMixin
26
+ from ...models import AutoencoderKLWan, WanTransformer3DModel
27
+ from ...schedulers import FlowMatchEulerDiscreteScheduler
28
+ from ...utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring
29
+ from ...utils.torch_utils import randn_tensor
30
+ from ...video_processor import VideoProcessor
31
+ from ..pipeline_utils import DiffusionPipeline
32
+ from .pipeline_output import WanPipelineOutput
33
+
34
+
35
+ if is_torch_xla_available():
36
+ import torch_xla.core.xla_model as xm
37
+
38
+ XLA_AVAILABLE = True
39
+ else:
40
+ XLA_AVAILABLE = False
41
+
42
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
43
+
44
+ if is_ftfy_available():
45
+ import ftfy
46
+
47
+ EXAMPLE_DOC_STRING = """
48
+ Examples:
49
+ ```python
50
+ >>> import torch
51
+ >>> import numpy as np
52
+ >>> from diffusers import AutoencoderKLWan, WanImageToVideoPipeline
53
+ >>> from diffusers.utils import export_to_video, load_image
54
+ >>> from transformers import CLIPVisionModel
55
+
56
+ >>> # Available models: Wan-AI/Wan2.1-I2V-14B-480P-Diffusers, Wan-AI/Wan2.1-I2V-14B-720P-Diffusers
57
+ >>> model_id = "Wan-AI/Wan2.1-I2V-14B-480P-Diffusers"
58
+ >>> image_encoder = CLIPVisionModel.from_pretrained(
59
+ ... model_id, subfolder="image_encoder", torch_dtype=torch.float32
60
+ ... )
61
+ >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
62
+ >>> pipe = WanImageToVideoPipeline.from_pretrained(
63
+ ... model_id, vae=vae, image_encoder=image_encoder, torch_dtype=torch.bfloat16
64
+ ... )
65
+ >>> pipe.to("cuda")
66
+
67
+ >>> image = load_image(
68
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
69
+ ... )
70
+ >>> max_area = 480 * 832
71
+ >>> aspect_ratio = image.height / image.width
72
+ >>> mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
73
+ >>> height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
74
+ >>> width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
75
+ >>> image = image.resize((width, height))
76
+ >>> prompt = (
77
+ ... "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in "
78
+ ... "the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
79
+ ... )
80
+ >>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
81
+
82
+ >>> output = pipe(
83
+ ... image=image,
84
+ ... prompt=prompt,
85
+ ... negative_prompt=negative_prompt,
86
+ ... height=height,
87
+ ... width=width,
88
+ ... num_frames=81,
89
+ ... guidance_scale=5.0,
90
+ ... ).frames[0]
91
+ >>> export_to_video(output, "output.mp4", fps=16)
92
+ ```
93
+ """
94
+
95
+
96
+ def basic_clean(text):
97
+ text = ftfy.fix_text(text)
98
+ text = html.unescape(html.unescape(text))
99
+ return text.strip()
100
+
101
+
102
+ def whitespace_clean(text):
103
+ text = re.sub(r"\s+", " ", text)
104
+ text = text.strip()
105
+ return text
106
+
107
+
108
+ def prompt_clean(text):
109
+ text = whitespace_clean(basic_clean(text))
110
+ return text
111
+
112
+
113
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
114
+ def retrieve_latents(
115
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
116
+ ):
117
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
118
+ return encoder_output.latent_dist.sample(generator)
119
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
120
+ return encoder_output.latent_dist.mode()
121
+ elif hasattr(encoder_output, "latents"):
122
+ return encoder_output.latents
123
+ else:
124
+ raise AttributeError("Could not access latents of provided encoder_output")
125
+
126
+
127
+ class WanImageToVideoPipeline(DiffusionPipeline, WanLoraLoaderMixin):
128
+ r"""
129
+ Pipeline for image-to-video generation using Wan.
130
+
131
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
132
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
133
+
134
+ Args:
135
+ tokenizer ([`T5Tokenizer`]):
136
+ Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
137
+ specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
138
+ text_encoder ([`T5EncoderModel`]):
139
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
140
+ the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
141
+ image_encoder ([`CLIPVisionModel`]):
142
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPVisionModel), specifically
143
+ the
144
+ [clip-vit-huge-patch14](https://github.com/mlfoundations/open_clip/blob/main/docs/PRETRAINED.md#vit-h14-xlm-roberta-large)
145
+ variant.
146
+ transformer ([`WanTransformer3DModel`]):
147
+ Conditional Transformer to denoise the input latents.
148
+ scheduler ([`UniPCMultistepScheduler`]):
149
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
150
+ vae ([`AutoencoderKLWan`]):
151
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
152
+ transformer_2 ([`WanTransformer3DModel`], *optional*):
153
+ Conditional Transformer to denoise the input latents during the low-noise stage. In two-stage denoising,
154
+ `transformer` handles high-noise stages and `transformer_2` handles low-noise stages. If not provided, only
155
+ `transformer` is used.
156
+ boundary_ratio (`float`, *optional*, defaults to `None`):
157
+ Ratio of total timesteps to use as the boundary for switching between transformers in two-stage denoising.
158
+ The actual boundary timestep is calculated as `boundary_ratio * num_train_timesteps`. When provided,
159
+ `transformer` handles timesteps >= boundary_timestep and `transformer_2` handles timesteps <
160
+ boundary_timestep. If `None`, only `transformer` is used for the entire denoising process.
161
+ """
162
+
163
+ model_cpu_offload_seq = "text_encoder->image_encoder->transformer->transformer_2->vae"
164
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
165
+ _optional_components = ["transformer", "transformer_2", "image_encoder", "image_processor"]
166
+
167
+ def __init__(
168
+ self,
169
+ tokenizer: AutoTokenizer,
170
+ text_encoder: UMT5EncoderModel,
171
+ vae: AutoencoderKLWan,
172
+ scheduler: FlowMatchEulerDiscreteScheduler,
173
+ image_processor: CLIPImageProcessor = None,
174
+ image_encoder: CLIPVisionModel = None,
175
+ transformer: WanTransformer3DModel = None,
176
+ transformer_2: WanTransformer3DModel = None,
177
+ boundary_ratio: Optional[float] = None,
178
+ expand_timesteps: bool = False,
179
+ ):
180
+ super().__init__()
181
+
182
+ self.register_modules(
183
+ vae=vae,
184
+ text_encoder=text_encoder,
185
+ tokenizer=tokenizer,
186
+ image_encoder=image_encoder,
187
+ transformer=transformer,
188
+ scheduler=scheduler,
189
+ image_processor=image_processor,
190
+ transformer_2=transformer_2,
191
+ )
192
+ self.register_to_config(boundary_ratio=boundary_ratio, expand_timesteps=expand_timesteps)
193
+
194
+ self.vae_scale_factor_temporal = self.vae.config.scale_factor_temporal if getattr(self, "vae", None) else 4
195
+ self.vae_scale_factor_spatial = self.vae.config.scale_factor_spatial if getattr(self, "vae", None) else 8
196
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
197
+ self.image_processor = image_processor
198
+
199
+ def _get_t5_prompt_embeds(
200
+ self,
201
+ prompt: Union[str, List[str]] = None,
202
+ num_videos_per_prompt: int = 1,
203
+ max_sequence_length: int = 512,
204
+ device: Optional[torch.device] = None,
205
+ dtype: Optional[torch.dtype] = None,
206
+ ):
207
+ device = device or self._execution_device
208
+ dtype = dtype or self.text_encoder.dtype
209
+
210
+ prompt = [prompt] if isinstance(prompt, str) else prompt
211
+ prompt = [prompt_clean(u) for u in prompt]
212
+ batch_size = len(prompt)
213
+
214
+ text_inputs = self.tokenizer(
215
+ prompt,
216
+ padding="max_length",
217
+ max_length=max_sequence_length,
218
+ truncation=True,
219
+ add_special_tokens=True,
220
+ return_attention_mask=True,
221
+ return_tensors="pt",
222
+ )
223
+ text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
224
+ seq_lens = mask.gt(0).sum(dim=1).long()
225
+
226
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
227
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
228
+ prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
229
+ prompt_embeds = torch.stack(
230
+ [torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
231
+ )
232
+
233
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
234
+ _, seq_len, _ = prompt_embeds.shape
235
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
236
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
237
+
238
+ return prompt_embeds
239
+
240
+ def encode_image(
241
+ self,
242
+ image: PipelineImageInput,
243
+ device: Optional[torch.device] = None,
244
+ ):
245
+ device = device or self._execution_device
246
+ image = self.image_processor(images=image, return_tensors="pt").to(device)
247
+ image_embeds = self.image_encoder(**image, output_hidden_states=True)
248
+ return image_embeds.hidden_states[-2]
249
+
250
+ # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline.encode_prompt
251
+ def encode_prompt(
252
+ self,
253
+ prompt: Union[str, List[str]],
254
+ negative_prompt: Optional[Union[str, List[str]]] = None,
255
+ do_classifier_free_guidance: bool = True,
256
+ num_videos_per_prompt: int = 1,
257
+ prompt_embeds: Optional[torch.Tensor] = None,
258
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
259
+ max_sequence_length: int = 226,
260
+ device: Optional[torch.device] = None,
261
+ dtype: Optional[torch.dtype] = None,
262
+ ):
263
+ r"""
264
+ Encodes the prompt into text encoder hidden states.
265
+
266
+ Args:
267
+ prompt (`str` or `List[str]`, *optional*):
268
+ prompt to be encoded
269
+ negative_prompt (`str` or `List[str]`, *optional*):
270
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
271
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
272
+ less than `1`).
273
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
274
+ Whether to use classifier free guidance or not.
275
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
276
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
277
+ prompt_embeds (`torch.Tensor`, *optional*):
278
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
279
+ provided, text embeddings will be generated from `prompt` input argument.
280
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
281
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
282
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
283
+ argument.
284
+ device: (`torch.device`, *optional*):
285
+ torch device
286
+ dtype: (`torch.dtype`, *optional*):
287
+ torch dtype
288
+ """
289
+ device = device or self._execution_device
290
+
291
+ prompt = [prompt] if isinstance(prompt, str) else prompt
292
+ if prompt is not None:
293
+ batch_size = len(prompt)
294
+ else:
295
+ batch_size = prompt_embeds.shape[0]
296
+
297
+ if prompt_embeds is None:
298
+ prompt_embeds = self._get_t5_prompt_embeds(
299
+ prompt=prompt,
300
+ num_videos_per_prompt=num_videos_per_prompt,
301
+ max_sequence_length=max_sequence_length,
302
+ device=device,
303
+ dtype=dtype,
304
+ )
305
+
306
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
307
+ negative_prompt = negative_prompt or ""
308
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
309
+
310
+ if prompt is not None and type(prompt) is not type(negative_prompt):
311
+ raise TypeError(
312
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
313
+ f" {type(prompt)}."
314
+ )
315
+ elif batch_size != len(negative_prompt):
316
+ raise ValueError(
317
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
318
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
319
+ " the batch size of `prompt`."
320
+ )
321
+
322
+ negative_prompt_embeds = self._get_t5_prompt_embeds(
323
+ prompt=negative_prompt,
324
+ num_videos_per_prompt=num_videos_per_prompt,
325
+ max_sequence_length=max_sequence_length,
326
+ device=device,
327
+ dtype=dtype,
328
+ )
329
+
330
+ return prompt_embeds, negative_prompt_embeds
331
+
332
+ def check_inputs(
333
+ self,
334
+ prompt,
335
+ negative_prompt,
336
+ image,
337
+ height,
338
+ width,
339
+ prompt_embeds=None,
340
+ negative_prompt_embeds=None,
341
+ image_embeds=None,
342
+ callback_on_step_end_tensor_inputs=None,
343
+ guidance_scale_2=None,
344
+ ):
345
+ if image is not None and image_embeds is not None:
346
+ raise ValueError(
347
+ f"Cannot forward both `image`: {image} and `image_embeds`: {image_embeds}. Please make sure to"
348
+ " only forward one of the two."
349
+ )
350
+ if image is None and image_embeds is None:
351
+ raise ValueError(
352
+ "Provide either `image` or `prompt_embeds`. Cannot leave both `image` and `image_embeds` undefined."
353
+ )
354
+ if image is not None and not isinstance(image, torch.Tensor) and not isinstance(image, PIL.Image.Image):
355
+ raise ValueError(f"`image` has to be of type `torch.Tensor` or `PIL.Image.Image` but is {type(image)}")
356
+ if height % 16 != 0 or width % 16 != 0:
357
+ raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
358
+
359
+ if callback_on_step_end_tensor_inputs is not None and not all(
360
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
361
+ ):
362
+ raise ValueError(
363
+ 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]}"
364
+ )
365
+
366
+ if prompt is not None and prompt_embeds is not None:
367
+ raise ValueError(
368
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
369
+ " only forward one of the two."
370
+ )
371
+ elif negative_prompt is not None and negative_prompt_embeds is not None:
372
+ raise ValueError(
373
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
374
+ " only forward one of the two."
375
+ )
376
+ elif prompt is None and prompt_embeds is None:
377
+ raise ValueError(
378
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
379
+ )
380
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
381
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
382
+ elif negative_prompt is not None and (
383
+ not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
384
+ ):
385
+ raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
386
+
387
+ if self.config.boundary_ratio is None and guidance_scale_2 is not None:
388
+ raise ValueError("`guidance_scale_2` is only supported when the pipeline's `boundary_ratio` is not None.")
389
+
390
+ if self.config.boundary_ratio is not None and image_embeds is not None:
391
+ raise ValueError("Cannot forward `image_embeds` when the pipeline's `boundary_ratio` is not configured.")
392
+
393
+ def prepare_latents(
394
+ self,
395
+ image: PipelineImageInput,
396
+ batch_size: int,
397
+ num_channels_latents: int = 16,
398
+ height: int = 480,
399
+ width: int = 832,
400
+ num_frames: int = 81,
401
+ dtype: Optional[torch.dtype] = None,
402
+ device: Optional[torch.device] = None,
403
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
404
+ latents: Optional[torch.Tensor] = None,
405
+ last_image: Optional[torch.Tensor] = None,
406
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
407
+ num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
408
+ latent_height = height // self.vae_scale_factor_spatial
409
+ latent_width = width // self.vae_scale_factor_spatial
410
+
411
+ shape = (batch_size, num_channels_latents, num_latent_frames, latent_height, latent_width)
412
+ if isinstance(generator, list) and len(generator) != batch_size:
413
+ raise ValueError(
414
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
415
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
416
+ )
417
+
418
+ if latents is None:
419
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
420
+ else:
421
+ latents = latents.to(device=device, dtype=dtype)
422
+
423
+ image = image.unsqueeze(2) # [batch_size, channels, 1, height, width]
424
+
425
+ if self.config.expand_timesteps:
426
+ video_condition = image
427
+
428
+ elif last_image is None:
429
+ video_condition = torch.cat(
430
+ [image, image.new_zeros(image.shape[0], image.shape[1], num_frames - 1, height, width)], dim=2
431
+ )
432
+ else:
433
+ last_image = last_image.unsqueeze(2)
434
+ video_condition = torch.cat(
435
+ [image, image.new_zeros(image.shape[0], image.shape[1], num_frames - 2, height, width), last_image],
436
+ dim=2,
437
+ )
438
+ video_condition = video_condition.to(device=device, dtype=self.vae.dtype)
439
+
440
+ latents_mean = (
441
+ torch.tensor(self.vae.config.latents_mean)
442
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
443
+ .to(latents.device, latents.dtype)
444
+ )
445
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
446
+ latents.device, latents.dtype
447
+ )
448
+
449
+ if isinstance(generator, list):
450
+ latent_condition = [
451
+ retrieve_latents(self.vae.encode(video_condition), sample_mode="argmax") for _ in generator
452
+ ]
453
+ latent_condition = torch.cat(latent_condition)
454
+ else:
455
+ latent_condition = retrieve_latents(self.vae.encode(video_condition), sample_mode="argmax")
456
+ latent_condition = latent_condition.repeat(batch_size, 1, 1, 1, 1)
457
+
458
+ latent_condition = latent_condition.to(dtype)
459
+ latent_condition = (latent_condition - latents_mean) * latents_std
460
+
461
+ if self.config.expand_timesteps:
462
+ first_frame_mask = torch.ones(
463
+ 1, 1, num_latent_frames, latent_height, latent_width, dtype=dtype, device=device
464
+ )
465
+ first_frame_mask[:, :, 0] = 0
466
+ return latents, latent_condition, first_frame_mask
467
+
468
+ mask_lat_size = torch.ones(batch_size, 1, num_frames, latent_height, latent_width)
469
+
470
+ if last_image is None:
471
+ mask_lat_size[:, :, list(range(1, num_frames))] = 0
472
+ else:
473
+ mask_lat_size[:, :, list(range(1, num_frames - 1))] = 0
474
+ first_frame_mask = mask_lat_size[:, :, 0:1]
475
+ first_frame_mask = torch.repeat_interleave(first_frame_mask, dim=2, repeats=self.vae_scale_factor_temporal)
476
+ mask_lat_size = torch.concat([first_frame_mask, mask_lat_size[:, :, 1:, :]], dim=2)
477
+ mask_lat_size = mask_lat_size.view(batch_size, -1, self.vae_scale_factor_temporal, latent_height, latent_width)
478
+ mask_lat_size = mask_lat_size.transpose(1, 2)
479
+ mask_lat_size = mask_lat_size.to(latent_condition.device)
480
+
481
+ return latents, torch.concat([mask_lat_size, latent_condition], dim=1)
482
+
483
+ @property
484
+ def guidance_scale(self):
485
+ return self._guidance_scale
486
+
487
+ @property
488
+ def do_classifier_free_guidance(self):
489
+ return self._guidance_scale > 1
490
+
491
+ @property
492
+ def num_timesteps(self):
493
+ return self._num_timesteps
494
+
495
+ @property
496
+ def current_timestep(self):
497
+ return self._current_timestep
498
+
499
+ @property
500
+ def interrupt(self):
501
+ return self._interrupt
502
+
503
+ @property
504
+ def attention_kwargs(self):
505
+ return self._attention_kwargs
506
+
507
+ @torch.no_grad()
508
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
509
+ def __call__(
510
+ self,
511
+ image: PipelineImageInput,
512
+ prompt: Union[str, List[str]] = None,
513
+ negative_prompt: Union[str, List[str]] = None,
514
+ height: int = 480,
515
+ width: int = 832,
516
+ num_frames: int = 81,
517
+ num_inference_steps: int = 50,
518
+ guidance_scale: float = 5.0,
519
+ guidance_scale_2: Optional[float] = None,
520
+ num_videos_per_prompt: Optional[int] = 1,
521
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
522
+ latents: Optional[torch.Tensor] = None,
523
+ prompt_embeds: Optional[torch.Tensor] = None,
524
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
525
+ image_embeds: Optional[torch.Tensor] = None,
526
+ last_image: Optional[torch.Tensor] = None,
527
+ output_type: Optional[str] = "np",
528
+ return_dict: bool = True,
529
+ attention_kwargs: Optional[Dict[str, Any]] = None,
530
+ callback_on_step_end: Optional[
531
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
532
+ ] = None,
533
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
534
+ max_sequence_length: int = 512,
535
+ ):
536
+ r"""
537
+ The call function to the pipeline for generation.
538
+
539
+ Args:
540
+ image (`PipelineImageInput`):
541
+ The input image to condition the generation on. Must be an image, a list of images or a `torch.Tensor`.
542
+ prompt (`str` or `List[str]`, *optional*):
543
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
544
+ instead.
545
+ negative_prompt (`str` or `List[str]`, *optional*):
546
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
547
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
548
+ less than `1`).
549
+ height (`int`, defaults to `480`):
550
+ The height of the generated video.
551
+ width (`int`, defaults to `832`):
552
+ The width of the generated video.
553
+ num_frames (`int`, defaults to `81`):
554
+ The number of frames in the generated video.
555
+ num_inference_steps (`int`, defaults to `50`):
556
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
557
+ expense of slower inference.
558
+ guidance_scale (`float`, defaults to `5.0`):
559
+ Guidance scale as defined in [Classifier-Free Diffusion
560
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
561
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
562
+ `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
563
+ the text `prompt`, usually at the expense of lower image quality.
564
+ guidance_scale_2 (`float`, *optional*, defaults to `None`):
565
+ Guidance scale for the low-noise stage transformer (`transformer_2`). If `None` and the pipeline's
566
+ `boundary_ratio` is not None, uses the same value as `guidance_scale`. Only used when `transformer_2`
567
+ and the pipeline's `boundary_ratio` are not None.
568
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
569
+ The number of images to generate per prompt.
570
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
571
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
572
+ generation deterministic.
573
+ latents (`torch.Tensor`, *optional*):
574
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
575
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
576
+ tensor is generated by sampling using the supplied random `generator`.
577
+ prompt_embeds (`torch.Tensor`, *optional*):
578
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
579
+ provided, text embeddings are generated from the `prompt` input argument.
580
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
581
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
582
+ provided, text embeddings are generated from the `negative_prompt` input argument.
583
+ image_embeds (`torch.Tensor`, *optional*):
584
+ Pre-generated image embeddings. Can be used to easily tweak image inputs (weighting). If not provided,
585
+ image embeddings are generated from the `image` input argument.
586
+ output_type (`str`, *optional*, defaults to `"np"`):
587
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
588
+ return_dict (`bool`, *optional*, defaults to `True`):
589
+ Whether or not to return a [`WanPipelineOutput`] instead of a plain tuple.
590
+ attention_kwargs (`dict`, *optional*):
591
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
592
+ `self.processor` in
593
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
594
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
595
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
596
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
597
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
598
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
599
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
600
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
601
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
602
+ `._callback_tensor_inputs` attribute of your pipeline class.
603
+ max_sequence_length (`int`, defaults to `512`):
604
+ The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
605
+ truncated. If the prompt is shorter, it will be padded to this length.
606
+
607
+ Examples:
608
+
609
+ Returns:
610
+ [`~WanPipelineOutput`] or `tuple`:
611
+ If `return_dict` is `True`, [`WanPipelineOutput`] is returned, otherwise a `tuple` is returned where
612
+ the first element is a list with the generated images and the second element is a list of `bool`s
613
+ indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
614
+ """
615
+
616
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
617
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
618
+
619
+ # 1. Check inputs. Raise error if not correct
620
+ self.check_inputs(
621
+ prompt,
622
+ negative_prompt,
623
+ image,
624
+ height,
625
+ width,
626
+ prompt_embeds,
627
+ negative_prompt_embeds,
628
+ image_embeds,
629
+ callback_on_step_end_tensor_inputs,
630
+ guidance_scale_2,
631
+ )
632
+
633
+ if num_frames % self.vae_scale_factor_temporal != 1:
634
+ logger.warning(
635
+ f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
636
+ )
637
+ num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
638
+ num_frames = max(num_frames, 1)
639
+
640
+ if self.config.boundary_ratio is not None and guidance_scale_2 is None:
641
+ guidance_scale_2 = guidance_scale
642
+
643
+ self._guidance_scale = guidance_scale
644
+ self._guidance_scale_2 = guidance_scale_2
645
+ self._attention_kwargs = attention_kwargs
646
+ self._current_timestep = None
647
+ self._interrupt = False
648
+
649
+ device = self._execution_device
650
+
651
+ # 2. Define call parameters
652
+ if prompt is not None and isinstance(prompt, str):
653
+ batch_size = 1
654
+ elif prompt is not None and isinstance(prompt, list):
655
+ batch_size = len(prompt)
656
+ else:
657
+ batch_size = prompt_embeds.shape[0]
658
+
659
+ # 3. Encode input prompt
660
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
661
+ prompt=prompt,
662
+ negative_prompt=negative_prompt,
663
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
664
+ num_videos_per_prompt=num_videos_per_prompt,
665
+ prompt_embeds=prompt_embeds,
666
+ negative_prompt_embeds=negative_prompt_embeds,
667
+ max_sequence_length=max_sequence_length,
668
+ device=device,
669
+ )
670
+
671
+ # Encode image embedding
672
+ transformer_dtype = self.transformer.dtype if self.transformer is not None else self.transformer_2.dtype
673
+ prompt_embeds = prompt_embeds.to(transformer_dtype)
674
+ if negative_prompt_embeds is not None:
675
+ negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
676
+
677
+ # only wan 2.1 i2v transformer accepts image_embeds
678
+ if self.transformer is not None and self.transformer.config.image_dim is not None:
679
+ if image_embeds is None:
680
+ if last_image is None:
681
+ image_embeds = self.encode_image(image, device)
682
+ else:
683
+ image_embeds = self.encode_image([image, last_image], device)
684
+ image_embeds = image_embeds.repeat(batch_size, 1, 1)
685
+ image_embeds = image_embeds.to(transformer_dtype)
686
+
687
+ # 4. Prepare timesteps
688
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
689
+ timesteps = self.scheduler.timesteps
690
+
691
+ # 5. Prepare latent variables
692
+ num_channels_latents = self.vae.config.z_dim
693
+ image = self.video_processor.preprocess(image, height=height, width=width).to(device, dtype=torch.float32)
694
+ if last_image is not None:
695
+ last_image = self.video_processor.preprocess(last_image, height=height, width=width).to(
696
+ device, dtype=torch.float32
697
+ )
698
+
699
+ latents_outputs = self.prepare_latents(
700
+ image,
701
+ batch_size * num_videos_per_prompt,
702
+ num_channels_latents,
703
+ height,
704
+ width,
705
+ num_frames,
706
+ torch.float32,
707
+ device,
708
+ generator,
709
+ latents,
710
+ last_image,
711
+ )
712
+ if self.config.expand_timesteps:
713
+ # wan 2.2 5b i2v use firt_frame_mask to mask timesteps
714
+ latents, condition, first_frame_mask = latents_outputs
715
+ else:
716
+ latents, condition = latents_outputs
717
+
718
+ # 6. Denoising loop
719
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
720
+ self._num_timesteps = len(timesteps)
721
+
722
+ if self.config.boundary_ratio is not None:
723
+ boundary_timestep = self.config.boundary_ratio * self.scheduler.config.num_train_timesteps
724
+ else:
725
+ boundary_timestep = None
726
+
727
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
728
+ for i, t in enumerate(timesteps):
729
+ if self.interrupt:
730
+ continue
731
+
732
+ self._current_timestep = t
733
+
734
+ if boundary_timestep is None or t >= boundary_timestep:
735
+ # wan2.1 or high-noise stage in wan2.2
736
+ current_model = self.transformer
737
+ current_guidance_scale = guidance_scale
738
+ else:
739
+ # low-noise stage in wan2.2
740
+ current_model = self.transformer_2
741
+ current_guidance_scale = guidance_scale_2
742
+
743
+ if self.config.expand_timesteps:
744
+ latent_model_input = (1 - first_frame_mask) * condition + first_frame_mask * latents
745
+ latent_model_input = latent_model_input.to(transformer_dtype)
746
+
747
+ # seq_len: num_latent_frames * (latent_height // patch_size) * (latent_width // patch_size)
748
+ temp_ts = (first_frame_mask[0][0][:, ::2, ::2] * t).flatten()
749
+ # batch_size, seq_len
750
+ timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1)
751
+ else:
752
+ latent_model_input = torch.cat([latents, condition], dim=1).to(transformer_dtype)
753
+ timestep = t.expand(latents.shape[0])
754
+
755
+ with current_model.cache_context("cond"):
756
+ noise_pred = current_model(
757
+ hidden_states=latent_model_input,
758
+ timestep=timestep,
759
+ encoder_hidden_states=prompt_embeds,
760
+ encoder_hidden_states_image=image_embeds,
761
+ attention_kwargs=attention_kwargs,
762
+ return_dict=False,
763
+ )[0]
764
+
765
+ if self.do_classifier_free_guidance:
766
+ with current_model.cache_context("uncond"):
767
+ noise_uncond = current_model(
768
+ hidden_states=latent_model_input,
769
+ timestep=timestep,
770
+ encoder_hidden_states=negative_prompt_embeds,
771
+ encoder_hidden_states_image=image_embeds,
772
+ attention_kwargs=attention_kwargs,
773
+ return_dict=False,
774
+ )[0]
775
+ noise_pred = noise_uncond + current_guidance_scale * (noise_pred - noise_uncond)
776
+
777
+ # compute the previous noisy sample x_t -> x_t-1
778
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
779
+
780
+ if callback_on_step_end is not None:
781
+ callback_kwargs = {}
782
+ for k in callback_on_step_end_tensor_inputs:
783
+ callback_kwargs[k] = locals()[k]
784
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
785
+
786
+ latents = callback_outputs.pop("latents", latents)
787
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
788
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
789
+
790
+ # call the callback, if provided
791
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
792
+ progress_bar.update()
793
+
794
+ if XLA_AVAILABLE:
795
+ xm.mark_step()
796
+
797
+ self._current_timestep = None
798
+
799
+ if self.config.expand_timesteps:
800
+ latents = (1 - first_frame_mask) * condition + first_frame_mask * latents
801
+
802
+ if not output_type == "latent":
803
+ latents = latents.to(self.vae.dtype)
804
+ latents_mean = (
805
+ torch.tensor(self.vae.config.latents_mean)
806
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
807
+ .to(latents.device, latents.dtype)
808
+ )
809
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
810
+ latents.device, latents.dtype
811
+ )
812
+ latents = latents / latents_std + latents_mean
813
+ video = self.vae.decode(latents, return_dict=False)[0]
814
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
815
+ else:
816
+ video = latents
817
+
818
+ # Offload all models
819
+ self.maybe_free_model_hooks()
820
+
821
+ if not return_dict:
822
+ return (video,)
823
+
824
+ return WanPipelineOutput(frames=video)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wan/pipeline_wan_vace.py ADDED
@@ -0,0 +1,1045 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The Wan Team and 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 html
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import PIL.Image
19
+ import regex as re
20
+ import torch
21
+ from transformers import AutoTokenizer, UMT5EncoderModel
22
+
23
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
24
+ from ...image_processor import PipelineImageInput
25
+ from ...loaders import WanLoraLoaderMixin
26
+ from ...models import AutoencoderKLWan, WanVACETransformer3DModel
27
+ from ...schedulers import FlowMatchEulerDiscreteScheduler
28
+ from ...utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring
29
+ from ...utils.torch_utils import randn_tensor
30
+ from ...video_processor import VideoProcessor
31
+ from ..pipeline_utils import DiffusionPipeline
32
+ from .pipeline_output import WanPipelineOutput
33
+
34
+
35
+ if is_torch_xla_available():
36
+ import torch_xla.core.xla_model as xm
37
+
38
+ XLA_AVAILABLE = True
39
+ else:
40
+ XLA_AVAILABLE = False
41
+
42
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
43
+
44
+ if is_ftfy_available():
45
+ import ftfy
46
+
47
+
48
+ EXAMPLE_DOC_STRING = """
49
+ Examples:
50
+ ```python
51
+ >>> import torch
52
+ >>> import PIL.Image
53
+ >>> from diffusers import AutoencoderKLWan, WanVACEPipeline
54
+ >>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
55
+ >>> from diffusers.utils import export_to_video, load_image
56
+ def prepare_video_and_mask(first_img: PIL.Image.Image, last_img: PIL.Image.Image, height: int, width: int, num_frames: int):
57
+ first_img = first_img.resize((width, height))
58
+ last_img = last_img.resize((width, height))
59
+ frames = []
60
+ frames.append(first_img)
61
+ # Ideally, this should be 127.5 to match original code, but they perform computation on numpy arrays
62
+ # whereas we are passing PIL images. If you choose to pass numpy arrays, you can set it to 127.5 to
63
+ # match the original code.
64
+ frames.extend([PIL.Image.new("RGB", (width, height), (128, 128, 128))] * (num_frames - 2))
65
+ frames.append(last_img)
66
+ mask_black = PIL.Image.new("L", (width, height), 0)
67
+ mask_white = PIL.Image.new("L", (width, height), 255)
68
+ mask = [mask_black, *[mask_white] * (num_frames - 2), mask_black]
69
+ return frames, mask
70
+
71
+ >>> # Available checkpoints: Wan-AI/Wan2.1-VACE-1.3B-diffusers, Wan-AI/Wan2.1-VACE-14B-diffusers
72
+ >>> model_id = "Wan-AI/Wan2.1-VACE-1.3B-diffusers"
73
+ >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
74
+ >>> pipe = WanVACEPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
75
+ >>> flow_shift = 3.0 # 5.0 for 720P, 3.0 for 480P
76
+ >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
77
+ >>> pipe.to("cuda")
78
+
79
+ >>> prompt = "CG animation style, a small blue bird takes off from the ground, flapping its wings. The bird's feathers are delicate, with a unique pattern on its chest. The background shows a blue sky with white clouds under bright sunshine. The camera follows the bird upward, capturing its flight and the vastness of the sky from a close-up, low-angle perspective."
80
+ >>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
81
+ >>> first_frame = load_image(
82
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_first_frame.png"
83
+ ... )
84
+ >>> last_frame = load_image(
85
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_last_frame.png>>> "
86
+ ... )
87
+
88
+ >>> height = 512
89
+ >>> width = 512
90
+ >>> num_frames = 81
91
+ >>> video, mask = prepare_video_and_mask(first_frame, last_frame, height, width, num_frames)
92
+
93
+ >>> output = pipe(
94
+ ... video=video,
95
+ ... mask=mask,
96
+ ... prompt=prompt,
97
+ ... negative_prompt=negative_prompt,
98
+ ... height=height,
99
+ ... width=width,
100
+ ... num_frames=num_frames,
101
+ ... num_inference_steps=30,
102
+ ... guidance_scale=5.0,
103
+ ... generator=torch.Generator().manual_seed(42),
104
+ ... ).frames[0]
105
+ >>> export_to_video(output, "output.mp4", fps=16)
106
+ ```
107
+ """
108
+
109
+
110
+ def basic_clean(text):
111
+ text = ftfy.fix_text(text)
112
+ text = html.unescape(html.unescape(text))
113
+ return text.strip()
114
+
115
+
116
+ def whitespace_clean(text):
117
+ text = re.sub(r"\s+", " ", text)
118
+ text = text.strip()
119
+ return text
120
+
121
+
122
+ def prompt_clean(text):
123
+ text = whitespace_clean(basic_clean(text))
124
+ return text
125
+
126
+
127
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
128
+ def retrieve_latents(
129
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
130
+ ):
131
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
132
+ return encoder_output.latent_dist.sample(generator)
133
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
134
+ return encoder_output.latent_dist.mode()
135
+ elif hasattr(encoder_output, "latents"):
136
+ return encoder_output.latents
137
+ else:
138
+ raise AttributeError("Could not access latents of provided encoder_output")
139
+
140
+
141
+ class WanVACEPipeline(DiffusionPipeline, WanLoraLoaderMixin):
142
+ r"""
143
+ Pipeline for controllable generation using Wan.
144
+
145
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
146
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
147
+
148
+ Args:
149
+ tokenizer ([`T5Tokenizer`]):
150
+ Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
151
+ specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
152
+ text_encoder ([`T5EncoderModel`]):
153
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
154
+ the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
155
+ vae ([`AutoencoderKLWan`]):
156
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
157
+ scheduler ([`UniPCMultistepScheduler`]):
158
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
159
+ transformer ([`WanVACETransformer3DModel`], *optional*):
160
+ Conditional Transformer to denoise the input latents during the high-noise stage. In two-stage denoising,
161
+ `transformer` handles high-noise stages and `transformer_2` handles low-noise stages. At least one of
162
+ `transformer` or `transformer_2` must be provided.
163
+ transformer_2 ([`WanVACETransformer3DModel`], *optional*):
164
+ Conditional Transformer to denoise the input latents during the low-noise stage. In two-stage denoising,
165
+ `transformer` handles high-noise stages and `transformer_2` handles low-noise stages. At least one of
166
+ `transformer` or `transformer_2` must be provided.
167
+ boundary_ratio (`float`, *optional*, defaults to `None`):
168
+ Ratio of total timesteps to use as the boundary for switching between transformers in two-stage denoising.
169
+ The actual boundary timestep is calculated as `boundary_ratio * num_train_timesteps`. When provided,
170
+ `transformer` handles timesteps >= boundary_timestep and `transformer_2` handles timesteps <
171
+ boundary_timestep. If `None`, only the available transformer is used for the entire denoising process.
172
+ """
173
+
174
+ model_cpu_offload_seq = "text_encoder->transformer->transformer_2->vae"
175
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
176
+ _optional_components = ["transformer", "transformer_2"]
177
+
178
+ def __init__(
179
+ self,
180
+ tokenizer: AutoTokenizer,
181
+ text_encoder: UMT5EncoderModel,
182
+ vae: AutoencoderKLWan,
183
+ scheduler: FlowMatchEulerDiscreteScheduler,
184
+ transformer: WanVACETransformer3DModel = None,
185
+ transformer_2: WanVACETransformer3DModel = None,
186
+ boundary_ratio: Optional[float] = None,
187
+ ):
188
+ super().__init__()
189
+
190
+ self.register_modules(
191
+ vae=vae,
192
+ text_encoder=text_encoder,
193
+ tokenizer=tokenizer,
194
+ transformer=transformer,
195
+ transformer_2=transformer_2,
196
+ scheduler=scheduler,
197
+ )
198
+ self.register_to_config(boundary_ratio=boundary_ratio)
199
+ self.vae_scale_factor_temporal = 2 ** sum(self.vae.temperal_downsample) if getattr(self, "vae", None) else 4
200
+ self.vae_scale_factor_spatial = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8
201
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
202
+
203
+ # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline._get_t5_prompt_embeds
204
+ def _get_t5_prompt_embeds(
205
+ self,
206
+ prompt: Union[str, List[str]] = None,
207
+ num_videos_per_prompt: int = 1,
208
+ max_sequence_length: int = 226,
209
+ device: Optional[torch.device] = None,
210
+ dtype: Optional[torch.dtype] = None,
211
+ ):
212
+ device = device or self._execution_device
213
+ dtype = dtype or self.text_encoder.dtype
214
+
215
+ prompt = [prompt] if isinstance(prompt, str) else prompt
216
+ prompt = [prompt_clean(u) for u in prompt]
217
+ batch_size = len(prompt)
218
+
219
+ text_inputs = self.tokenizer(
220
+ prompt,
221
+ padding="max_length",
222
+ max_length=max_sequence_length,
223
+ truncation=True,
224
+ add_special_tokens=True,
225
+ return_attention_mask=True,
226
+ return_tensors="pt",
227
+ )
228
+ text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
229
+ seq_lens = mask.gt(0).sum(dim=1).long()
230
+
231
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
232
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
233
+ prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
234
+ prompt_embeds = torch.stack(
235
+ [torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
236
+ )
237
+
238
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
239
+ _, seq_len, _ = prompt_embeds.shape
240
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
241
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
242
+
243
+ return prompt_embeds
244
+
245
+ # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline.encode_prompt
246
+ def encode_prompt(
247
+ self,
248
+ prompt: Union[str, List[str]],
249
+ negative_prompt: Optional[Union[str, List[str]]] = None,
250
+ do_classifier_free_guidance: bool = True,
251
+ num_videos_per_prompt: int = 1,
252
+ prompt_embeds: Optional[torch.Tensor] = None,
253
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
254
+ max_sequence_length: int = 226,
255
+ device: Optional[torch.device] = None,
256
+ dtype: Optional[torch.dtype] = None,
257
+ ):
258
+ r"""
259
+ Encodes the prompt into text encoder hidden states.
260
+
261
+ Args:
262
+ prompt (`str` or `List[str]`, *optional*):
263
+ prompt to be encoded
264
+ negative_prompt (`str` or `List[str]`, *optional*):
265
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
266
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
267
+ less than `1`).
268
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
269
+ Whether to use classifier free guidance or not.
270
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
271
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
272
+ prompt_embeds (`torch.Tensor`, *optional*):
273
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
274
+ provided, text embeddings will be generated from `prompt` input argument.
275
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
276
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
277
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
278
+ argument.
279
+ device: (`torch.device`, *optional*):
280
+ torch device
281
+ dtype: (`torch.dtype`, *optional*):
282
+ torch dtype
283
+ """
284
+ device = device or self._execution_device
285
+
286
+ prompt = [prompt] if isinstance(prompt, str) else prompt
287
+ if prompt is not None:
288
+ batch_size = len(prompt)
289
+ else:
290
+ batch_size = prompt_embeds.shape[0]
291
+
292
+ if prompt_embeds is None:
293
+ prompt_embeds = self._get_t5_prompt_embeds(
294
+ prompt=prompt,
295
+ num_videos_per_prompt=num_videos_per_prompt,
296
+ max_sequence_length=max_sequence_length,
297
+ device=device,
298
+ dtype=dtype,
299
+ )
300
+
301
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
302
+ negative_prompt = negative_prompt or ""
303
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
304
+
305
+ if prompt is not None and type(prompt) is not type(negative_prompt):
306
+ raise TypeError(
307
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
308
+ f" {type(prompt)}."
309
+ )
310
+ elif batch_size != len(negative_prompt):
311
+ raise ValueError(
312
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
313
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
314
+ " the batch size of `prompt`."
315
+ )
316
+
317
+ negative_prompt_embeds = self._get_t5_prompt_embeds(
318
+ prompt=negative_prompt,
319
+ num_videos_per_prompt=num_videos_per_prompt,
320
+ max_sequence_length=max_sequence_length,
321
+ device=device,
322
+ dtype=dtype,
323
+ )
324
+
325
+ return prompt_embeds, negative_prompt_embeds
326
+
327
+ def check_inputs(
328
+ self,
329
+ prompt,
330
+ negative_prompt,
331
+ height,
332
+ width,
333
+ prompt_embeds=None,
334
+ negative_prompt_embeds=None,
335
+ callback_on_step_end_tensor_inputs=None,
336
+ video=None,
337
+ mask=None,
338
+ reference_images=None,
339
+ guidance_scale_2=None,
340
+ ):
341
+ if self.transformer is not None:
342
+ base = self.vae_scale_factor_spatial * self.transformer.config.patch_size[1]
343
+ elif self.transformer_2 is not None:
344
+ base = self.vae_scale_factor_spatial * self.transformer_2.config.patch_size[1]
345
+ else:
346
+ raise ValueError(
347
+ "`transformer` or `transformer_2` component must be set in order to run inference with this pipeline"
348
+ )
349
+
350
+ if height % base != 0 or width % base != 0:
351
+ raise ValueError(f"`height` and `width` have to be divisible by {base} but are {height} and {width}.")
352
+
353
+ if callback_on_step_end_tensor_inputs is not None and not all(
354
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
355
+ ):
356
+ raise ValueError(
357
+ 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]}"
358
+ )
359
+ if self.config.boundary_ratio is None and guidance_scale_2 is not None:
360
+ raise ValueError("`guidance_scale_2` is only supported when the pipeline's `boundary_ratio` is not None.")
361
+
362
+ if prompt is not None and prompt_embeds is not None:
363
+ raise ValueError(
364
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
365
+ " only forward one of the two."
366
+ )
367
+ elif negative_prompt is not None and negative_prompt_embeds is not None:
368
+ raise ValueError(
369
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
370
+ " only forward one of the two."
371
+ )
372
+ elif prompt is None and prompt_embeds is None:
373
+ raise ValueError(
374
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
375
+ )
376
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
377
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
378
+ elif negative_prompt is not None and (
379
+ not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
380
+ ):
381
+ raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
382
+
383
+ if video is not None:
384
+ if mask is not None:
385
+ if len(video) != len(mask):
386
+ raise ValueError(
387
+ f"Length of `video` {len(video)} and `mask` {len(mask)} do not match. Please make sure that"
388
+ " they have the same length."
389
+ )
390
+ if reference_images is not None:
391
+ is_pil_image = isinstance(reference_images, PIL.Image.Image)
392
+ is_list_of_pil_images = isinstance(reference_images, list) and all(
393
+ isinstance(ref_img, PIL.Image.Image) for ref_img in reference_images
394
+ )
395
+ is_list_of_list_of_pil_images = isinstance(reference_images, list) and all(
396
+ isinstance(ref_img, list) and all(isinstance(ref_img_, PIL.Image.Image) for ref_img_ in ref_img)
397
+ for ref_img in reference_images
398
+ )
399
+ if not (is_pil_image or is_list_of_pil_images or is_list_of_list_of_pil_images):
400
+ raise ValueError(
401
+ "`reference_images` has to be of type `PIL.Image.Image` or `list` of `PIL.Image.Image`, or "
402
+ "`list` of `list` of `PIL.Image.Image`, but is {type(reference_images)}"
403
+ )
404
+ if is_list_of_list_of_pil_images and len(reference_images) != 1:
405
+ raise ValueError(
406
+ "The pipeline only supports generating one video at a time at the moment. When passing a list "
407
+ "of list of reference images, where the outer list corresponds to the batch size and the inner "
408
+ "list corresponds to list of conditioning images per video, please make sure to only pass "
409
+ "one inner list of reference images (i.e., `[[<image1>, <image2>, ...]]`"
410
+ )
411
+ elif mask is not None:
412
+ raise ValueError("`mask` can only be passed if `video` is passed as well.")
413
+
414
+ def preprocess_conditions(
415
+ self,
416
+ video: Optional[List[PipelineImageInput]] = None,
417
+ mask: Optional[List[PipelineImageInput]] = None,
418
+ reference_images: Optional[Union[PIL.Image.Image, List[PIL.Image.Image], List[List[PIL.Image.Image]]]] = None,
419
+ batch_size: int = 1,
420
+ height: int = 480,
421
+ width: int = 832,
422
+ num_frames: int = 81,
423
+ dtype: Optional[torch.dtype] = None,
424
+ device: Optional[torch.device] = None,
425
+ ):
426
+ if video is not None:
427
+ base = self.vae_scale_factor_spatial * (
428
+ self.transformer.config.patch_size[1]
429
+ if self.transformer is not None
430
+ else self.transformer_2.config.patch_size[1]
431
+ )
432
+ video_height, video_width = self.video_processor.get_default_height_width(video[0])
433
+
434
+ if video_height * video_width > height * width:
435
+ scale = min(width / video_width, height / video_height)
436
+ video_height, video_width = int(video_height * scale), int(video_width * scale)
437
+
438
+ if video_height % base != 0 or video_width % base != 0:
439
+ logger.warning(
440
+ f"Video height and width should be divisible by {base}, but got {video_height} and {video_width}. "
441
+ )
442
+ video_height = (video_height // base) * base
443
+ video_width = (video_width // base) * base
444
+
445
+ assert video_height * video_width <= height * width
446
+
447
+ video = self.video_processor.preprocess_video(video, video_height, video_width)
448
+ image_size = (video_height, video_width) # Use the height/width of video (with possible rescaling)
449
+ else:
450
+ video = torch.zeros(batch_size, 3, num_frames, height, width, dtype=dtype, device=device)
451
+ image_size = (height, width) # Use the height/width provider by user
452
+
453
+ if mask is not None:
454
+ mask = self.video_processor.preprocess_video(mask, image_size[0], image_size[1])
455
+ mask = torch.clamp((mask + 1) / 2, min=0, max=1)
456
+ else:
457
+ mask = torch.ones_like(video)
458
+
459
+ video = video.to(dtype=dtype, device=device)
460
+ mask = mask.to(dtype=dtype, device=device)
461
+
462
+ # Make a list of list of images where the outer list corresponds to video batch size and the inner list
463
+ # corresponds to list of conditioning images per video
464
+ if reference_images is None or isinstance(reference_images, PIL.Image.Image):
465
+ reference_images = [[reference_images] for _ in range(video.shape[0])]
466
+ elif isinstance(reference_images, (list, tuple)) and isinstance(next(iter(reference_images)), PIL.Image.Image):
467
+ reference_images = [reference_images]
468
+ elif (
469
+ isinstance(reference_images, (list, tuple))
470
+ and isinstance(next(iter(reference_images)), list)
471
+ and isinstance(next(iter(reference_images[0])), PIL.Image.Image)
472
+ ):
473
+ reference_images = reference_images
474
+ else:
475
+ raise ValueError(
476
+ "`reference_images` has to be of type `PIL.Image.Image` or `list` of `PIL.Image.Image`, or "
477
+ "`list` of `list` of `PIL.Image.Image`, but is {type(reference_images)}"
478
+ )
479
+
480
+ if video.shape[0] != len(reference_images):
481
+ raise ValueError(
482
+ f"Batch size of `video` {video.shape[0]} and length of `reference_images` {len(reference_images)} does not match."
483
+ )
484
+
485
+ ref_images_lengths = [len(reference_images_batch) for reference_images_batch in reference_images]
486
+ if any(l != ref_images_lengths[0] for l in ref_images_lengths):
487
+ raise ValueError(
488
+ f"All batches of `reference_images` should have the same length, but got {ref_images_lengths}. Support for this "
489
+ "may be added in the future."
490
+ )
491
+
492
+ reference_images_preprocessed = []
493
+ for i, reference_images_batch in enumerate(reference_images):
494
+ preprocessed_images = []
495
+ for j, image in enumerate(reference_images_batch):
496
+ if image is None:
497
+ continue
498
+ image = self.video_processor.preprocess(image, None, None)
499
+ img_height, img_width = image.shape[-2:]
500
+ scale = min(image_size[0] / img_height, image_size[1] / img_width)
501
+ new_height, new_width = int(img_height * scale), int(img_width * scale)
502
+ resized_image = torch.nn.functional.interpolate(
503
+ image, size=(new_height, new_width), mode="bilinear", align_corners=False
504
+ ).squeeze(0) # [C, H, W]
505
+ top = (image_size[0] - new_height) // 2
506
+ left = (image_size[1] - new_width) // 2
507
+ canvas = torch.ones(3, *image_size, device=device, dtype=dtype)
508
+ canvas[:, top : top + new_height, left : left + new_width] = resized_image
509
+ preprocessed_images.append(canvas)
510
+ reference_images_preprocessed.append(preprocessed_images)
511
+
512
+ return video, mask, reference_images_preprocessed
513
+
514
+ def prepare_video_latents(
515
+ self,
516
+ video: torch.Tensor,
517
+ mask: torch.Tensor,
518
+ reference_images: Optional[List[List[torch.Tensor]]] = None,
519
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
520
+ device: Optional[torch.device] = None,
521
+ ) -> torch.Tensor:
522
+ device = device or self._execution_device
523
+
524
+ if isinstance(generator, list):
525
+ # TODO: support this
526
+ raise ValueError("Passing a list of generators is not yet supported. This may be supported in the future.")
527
+
528
+ if reference_images is None:
529
+ # For each batch of video, we set no re
530
+ # ference image (as one or more can be passed by user)
531
+ reference_images = [[None] for _ in range(video.shape[0])]
532
+ else:
533
+ if video.shape[0] != len(reference_images):
534
+ raise ValueError(
535
+ f"Batch size of `video` {video.shape[0]} and length of `reference_images` {len(reference_images)} does not match."
536
+ )
537
+
538
+ if video.shape[0] != 1:
539
+ # TODO: support this
540
+ raise ValueError(
541
+ "Generating with more than one video is not yet supported. This may be supported in the future."
542
+ )
543
+
544
+ vae_dtype = self.vae.dtype
545
+ video = video.to(dtype=vae_dtype)
546
+
547
+ latents_mean = torch.tensor(self.vae.config.latents_mean, device=device, dtype=torch.float32).view(
548
+ 1, self.vae.config.z_dim, 1, 1, 1
549
+ )
550
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std, device=device, dtype=torch.float32).view(
551
+ 1, self.vae.config.z_dim, 1, 1, 1
552
+ )
553
+
554
+ if mask is None:
555
+ latents = retrieve_latents(self.vae.encode(video), generator, sample_mode="argmax").unbind(0)
556
+ latents = ((latents.float() - latents_mean) * latents_std).to(vae_dtype)
557
+ else:
558
+ mask = torch.where(mask > 0.5, 1.0, 0.0).to(dtype=vae_dtype)
559
+ inactive = video * (1 - mask)
560
+ reactive = video * mask
561
+ inactive = retrieve_latents(self.vae.encode(inactive), generator, sample_mode="argmax")
562
+ reactive = retrieve_latents(self.vae.encode(reactive), generator, sample_mode="argmax")
563
+ inactive = ((inactive.float() - latents_mean) * latents_std).to(vae_dtype)
564
+ reactive = ((reactive.float() - latents_mean) * latents_std).to(vae_dtype)
565
+ latents = torch.cat([inactive, reactive], dim=1)
566
+
567
+ latent_list = []
568
+ for latent, reference_images_batch in zip(latents, reference_images):
569
+ for reference_image in reference_images_batch:
570
+ assert reference_image.ndim == 3
571
+ reference_image = reference_image.to(dtype=vae_dtype)
572
+ reference_image = reference_image[None, :, None, :, :] # [1, C, 1, H, W]
573
+ reference_latent = retrieve_latents(self.vae.encode(reference_image), generator, sample_mode="argmax")
574
+ reference_latent = ((reference_latent.float() - latents_mean) * latents_std).to(vae_dtype)
575
+ reference_latent = reference_latent.squeeze(0) # [C, 1, H, W]
576
+ reference_latent = torch.cat([reference_latent, torch.zeros_like(reference_latent)], dim=0)
577
+ latent = torch.cat([reference_latent.squeeze(0), latent], dim=1)
578
+ latent_list.append(latent)
579
+ return torch.stack(latent_list)
580
+
581
+ def prepare_masks(
582
+ self,
583
+ mask: torch.Tensor,
584
+ reference_images: Optional[List[torch.Tensor]] = None,
585
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
586
+ ) -> torch.Tensor:
587
+ if isinstance(generator, list):
588
+ # TODO: support this
589
+ raise ValueError("Passing a list of generators is not yet supported. This may be supported in the future.")
590
+
591
+ if reference_images is None:
592
+ # For each batch of video, we set no reference image (as one or more can be passed by user)
593
+ reference_images = [[None] for _ in range(mask.shape[0])]
594
+ else:
595
+ if mask.shape[0] != len(reference_images):
596
+ raise ValueError(
597
+ f"Batch size of `mask` {mask.shape[0]} and length of `reference_images` {len(reference_images)} does not match."
598
+ )
599
+
600
+ if mask.shape[0] != 1:
601
+ # TODO: support this
602
+ raise ValueError(
603
+ "Generating with more than one video is not yet supported. This may be supported in the future."
604
+ )
605
+
606
+ transformer_patch_size = (
607
+ self.transformer.config.patch_size[1]
608
+ if self.transformer is not None
609
+ else self.transformer_2.config.patch_size[1]
610
+ )
611
+
612
+ mask_list = []
613
+ for mask_, reference_images_batch in zip(mask, reference_images):
614
+ num_channels, num_frames, height, width = mask_.shape
615
+ new_num_frames = (num_frames + self.vae_scale_factor_temporal - 1) // self.vae_scale_factor_temporal
616
+ new_height = height // (self.vae_scale_factor_spatial * transformer_patch_size) * transformer_patch_size
617
+ new_width = width // (self.vae_scale_factor_spatial * transformer_patch_size) * transformer_patch_size
618
+ mask_ = mask_[0, :, :, :]
619
+ mask_ = mask_.view(
620
+ num_frames, new_height, self.vae_scale_factor_spatial, new_width, self.vae_scale_factor_spatial
621
+ )
622
+ mask_ = mask_.permute(2, 4, 0, 1, 3).flatten(0, 1) # [8x8, num_frames, new_height, new_width]
623
+ mask_ = torch.nn.functional.interpolate(
624
+ mask_.unsqueeze(0), size=(new_num_frames, new_height, new_width), mode="nearest-exact"
625
+ ).squeeze(0)
626
+ num_ref_images = len(reference_images_batch)
627
+ if num_ref_images > 0:
628
+ mask_padding = torch.zeros_like(mask_[:, :num_ref_images, :, :])
629
+ mask_ = torch.cat([mask_padding, mask_], dim=1)
630
+ mask_list.append(mask_)
631
+ return torch.stack(mask_list)
632
+
633
+ def prepare_latents(
634
+ self,
635
+ batch_size: int,
636
+ num_channels_latents: int = 16,
637
+ height: int = 480,
638
+ width: int = 832,
639
+ num_frames: int = 81,
640
+ dtype: Optional[torch.dtype] = None,
641
+ device: Optional[torch.device] = None,
642
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
643
+ latents: Optional[torch.Tensor] = None,
644
+ ) -> torch.Tensor:
645
+ if latents is not None:
646
+ return latents.to(device=device, dtype=dtype)
647
+
648
+ num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
649
+ shape = (
650
+ batch_size,
651
+ num_channels_latents,
652
+ num_latent_frames,
653
+ int(height) // self.vae_scale_factor_spatial,
654
+ int(width) // self.vae_scale_factor_spatial,
655
+ )
656
+ if isinstance(generator, list) and len(generator) != batch_size:
657
+ raise ValueError(
658
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
659
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
660
+ )
661
+
662
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
663
+ return latents
664
+
665
+ @property
666
+ def guidance_scale(self):
667
+ return self._guidance_scale
668
+
669
+ @property
670
+ def do_classifier_free_guidance(self):
671
+ return self._guidance_scale > 1.0
672
+
673
+ @property
674
+ def num_timesteps(self):
675
+ return self._num_timesteps
676
+
677
+ @property
678
+ def current_timestep(self):
679
+ return self._current_timestep
680
+
681
+ @property
682
+ def interrupt(self):
683
+ return self._interrupt
684
+
685
+ @property
686
+ def attention_kwargs(self):
687
+ return self._attention_kwargs
688
+
689
+ @torch.no_grad()
690
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
691
+ def __call__(
692
+ self,
693
+ prompt: Union[str, List[str]] = None,
694
+ negative_prompt: Union[str, List[str]] = None,
695
+ video: Optional[List[PipelineImageInput]] = None,
696
+ mask: Optional[List[PipelineImageInput]] = None,
697
+ reference_images: Optional[List[PipelineImageInput]] = None,
698
+ conditioning_scale: Union[float, List[float], torch.Tensor] = 1.0,
699
+ height: int = 480,
700
+ width: int = 832,
701
+ num_frames: int = 81,
702
+ num_inference_steps: int = 50,
703
+ guidance_scale: float = 5.0,
704
+ guidance_scale_2: Optional[float] = None,
705
+ num_videos_per_prompt: Optional[int] = 1,
706
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
707
+ latents: Optional[torch.Tensor] = None,
708
+ prompt_embeds: Optional[torch.Tensor] = None,
709
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
710
+ output_type: Optional[str] = "np",
711
+ return_dict: bool = True,
712
+ attention_kwargs: Optional[Dict[str, Any]] = None,
713
+ callback_on_step_end: Optional[
714
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
715
+ ] = None,
716
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
717
+ max_sequence_length: int = 512,
718
+ ):
719
+ r"""
720
+ The call function to the pipeline for generation.
721
+
722
+ Args:
723
+ prompt (`str` or `List[str]`, *optional*):
724
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`
725
+ instead.
726
+ negative_prompt (`str` or `List[str]`, *optional*):
727
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
728
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
729
+ less than `1`).
730
+ video (`List[PIL.Image.Image]`, *optional*):
731
+ The input video or videos to be used as a starting point for the generation. The video should be a list
732
+ of PIL images, a numpy array, or a torch tensor. Currently, the pipeline only supports generating one
733
+ video at a time.
734
+ mask (`List[PIL.Image.Image]`, *optional*):
735
+ The input mask defines which video regions to condition on and which to generate. Black areas in the
736
+ mask indicate conditioning regions, while white areas indicate regions for generation. The mask should
737
+ be a list of PIL images, a numpy array, or a torch tensor. Currently supports generating a single video
738
+ at a time.
739
+ reference_images (`List[PIL.Image.Image]`, *optional*):
740
+ A list of one or more reference images as extra conditioning for the generation. For example, if you
741
+ are trying to inpaint a video to change the character, you can pass reference images of the new
742
+ character here. Refer to the Diffusers [examples](https://github.com/huggingface/diffusers/pull/11582)
743
+ and original [user
744
+ guide](https://github.com/ali-vilab/VACE/blob/0897c6d055d7d9ea9e191dce763006664d9780f8/UserGuide.md)
745
+ for a full list of supported tasks and use cases.
746
+ conditioning_scale (`float`, `List[float]`, `torch.Tensor`, defaults to `1.0`):
747
+ The conditioning scale to be applied when adding the control conditioning latent stream to the
748
+ denoising latent stream in each control layer of the model. If a float is provided, it will be applied
749
+ uniformly to all layers. If a list or tensor is provided, it should have the same length as the number
750
+ of control layers in the model (`len(transformer.config.vace_layers)`).
751
+ height (`int`, defaults to `480`):
752
+ The height in pixels of the generated image.
753
+ width (`int`, defaults to `832`):
754
+ The width in pixels of the generated image.
755
+ num_frames (`int`, defaults to `81`):
756
+ The number of frames in the generated video.
757
+ num_inference_steps (`int`, defaults to `50`):
758
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
759
+ expense of slower inference.
760
+ guidance_scale (`float`, defaults to `5.0`):
761
+ Guidance scale as defined in [Classifier-Free Diffusion
762
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
763
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
764
+ `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
765
+ the text `prompt`, usually at the expense of lower image quality.
766
+ guidance_scale_2 (`float`, *optional*, defaults to `None`):
767
+ Guidance scale for the low-noise stage transformer (`transformer_2`). If `None` and the pipeline's
768
+ `boundary_ratio` is not None, uses the same value as `guidance_scale`. Only used when `transformer_2`
769
+ and the pipeline's `boundary_ratio` are not None.
770
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
771
+ The number of images to generate per prompt.
772
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
773
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
774
+ generation deterministic.
775
+ latents (`torch.Tensor`, *optional*):
776
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
777
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
778
+ tensor is generated by sampling using the supplied random `generator`.
779
+ prompt_embeds (`torch.Tensor`, *optional*):
780
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
781
+ provided, text embeddings are generated from the `prompt` input argument.
782
+ output_type (`str`, *optional*, defaults to `"np"`):
783
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
784
+ return_dict (`bool`, *optional*, defaults to `True`):
785
+ Whether or not to return a [`WanPipelineOutput`] instead of a plain tuple.
786
+ attention_kwargs (`dict`, *optional*):
787
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
788
+ `self.processor` in
789
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
790
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
791
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
792
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
793
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
794
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
795
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
796
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
797
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
798
+ `._callback_tensor_inputs` attribute of your pipeline class.
799
+ max_sequence_length (`int`, defaults to `512`):
800
+ The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
801
+ truncated. If the prompt is shorter, it will be padded to this length.
802
+
803
+ Examples:
804
+
805
+ Returns:
806
+ [`~WanPipelineOutput`] or `tuple`:
807
+ If `return_dict` is `True`, [`WanPipelineOutput`] is returned, otherwise a `tuple` is returned where
808
+ the first element is a list with the generated images and the second element is a list of `bool`s
809
+ indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
810
+ """
811
+
812
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
813
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
814
+
815
+ # Simplification of implementation for now
816
+ if prompt is not None and not isinstance(prompt, str):
817
+ raise ValueError("Passing a list of prompts is not yet supported. This may be supported in the future.")
818
+ if num_videos_per_prompt != 1:
819
+ raise ValueError(
820
+ "Generating multiple videos per prompt is not yet supported. This may be supported in the future."
821
+ )
822
+
823
+ # 1. Check inputs. Raise error if not correct
824
+ self.check_inputs(
825
+ prompt,
826
+ negative_prompt,
827
+ height,
828
+ width,
829
+ prompt_embeds,
830
+ negative_prompt_embeds,
831
+ callback_on_step_end_tensor_inputs,
832
+ video,
833
+ mask,
834
+ reference_images,
835
+ guidance_scale_2,
836
+ )
837
+
838
+ if num_frames % self.vae_scale_factor_temporal != 1:
839
+ logger.warning(
840
+ f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
841
+ )
842
+ num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
843
+ num_frames = max(num_frames, 1)
844
+
845
+ if self.config.boundary_ratio is not None and guidance_scale_2 is None:
846
+ guidance_scale_2 = guidance_scale
847
+
848
+ self._guidance_scale = guidance_scale
849
+ self._guidance_scale_2 = guidance_scale_2
850
+ self._attention_kwargs = attention_kwargs
851
+ self._current_timestep = None
852
+ self._interrupt = False
853
+
854
+ device = self._execution_device
855
+
856
+ # 2. Define call parameters
857
+ if prompt is not None and isinstance(prompt, str):
858
+ batch_size = 1
859
+ elif prompt is not None and isinstance(prompt, list):
860
+ batch_size = len(prompt)
861
+ else:
862
+ batch_size = prompt_embeds.shape[0]
863
+
864
+ vae_dtype = self.vae.dtype
865
+ transformer_dtype = self.transformer.dtype if self.transformer is not None else self.transformer_2.dtype
866
+
867
+ vace_layers = (
868
+ self.transformer.config.vace_layers
869
+ if self.transformer is not None
870
+ else self.transformer_2.config.vace_layers
871
+ )
872
+ if isinstance(conditioning_scale, (int, float)):
873
+ conditioning_scale = [conditioning_scale] * len(vace_layers)
874
+ if isinstance(conditioning_scale, list):
875
+ if len(conditioning_scale) != len(vace_layers):
876
+ raise ValueError(
877
+ f"Length of `conditioning_scale` {len(conditioning_scale)} does not match number of layers {len(vace_layers)}."
878
+ )
879
+ conditioning_scale = torch.tensor(conditioning_scale)
880
+ if isinstance(conditioning_scale, torch.Tensor):
881
+ if conditioning_scale.size(0) != len(vace_layers):
882
+ raise ValueError(
883
+ f"Length of `conditioning_scale` {conditioning_scale.size(0)} does not match number of layers {len(vace_layers)}."
884
+ )
885
+ conditioning_scale = conditioning_scale.to(device=device, dtype=transformer_dtype)
886
+
887
+ # 3. Encode input prompt
888
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
889
+ prompt=prompt,
890
+ negative_prompt=negative_prompt,
891
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
892
+ num_videos_per_prompt=num_videos_per_prompt,
893
+ prompt_embeds=prompt_embeds,
894
+ negative_prompt_embeds=negative_prompt_embeds,
895
+ max_sequence_length=max_sequence_length,
896
+ device=device,
897
+ )
898
+
899
+ prompt_embeds = prompt_embeds.to(transformer_dtype)
900
+ if negative_prompt_embeds is not None:
901
+ negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
902
+
903
+ # 4. Prepare timesteps
904
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
905
+ timesteps = self.scheduler.timesteps
906
+
907
+ # 5. Prepare latent variables
908
+ video, mask, reference_images = self.preprocess_conditions(
909
+ video,
910
+ mask,
911
+ reference_images,
912
+ batch_size,
913
+ height,
914
+ width,
915
+ num_frames,
916
+ torch.float32,
917
+ device,
918
+ )
919
+ num_reference_images = len(reference_images[0])
920
+
921
+ conditioning_latents = self.prepare_video_latents(video, mask, reference_images, generator, device)
922
+ mask = self.prepare_masks(mask, reference_images, generator)
923
+ conditioning_latents = torch.cat([conditioning_latents, mask], dim=1)
924
+ conditioning_latents = conditioning_latents.to(transformer_dtype)
925
+
926
+ num_channels_latents = (
927
+ self.transformer.config.in_channels
928
+ if self.transformer is not None
929
+ else self.transformer_2.config.in_channels
930
+ )
931
+ latents = self.prepare_latents(
932
+ batch_size * num_videos_per_prompt,
933
+ num_channels_latents,
934
+ height,
935
+ width,
936
+ num_frames + num_reference_images * self.vae_scale_factor_temporal,
937
+ torch.float32,
938
+ device,
939
+ generator,
940
+ latents,
941
+ )
942
+
943
+ if conditioning_latents.shape[2] != latents.shape[2]:
944
+ logger.warning(
945
+ "The number of frames in the conditioning latents does not match the number of frames to be generated. Generation quality may be affected."
946
+ )
947
+
948
+ # 6. Denoising loop
949
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
950
+ self._num_timesteps = len(timesteps)
951
+
952
+ if self.config.boundary_ratio is not None:
953
+ boundary_timestep = self.config.boundary_ratio * self.scheduler.config.num_train_timesteps
954
+ else:
955
+ boundary_timestep = None
956
+
957
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
958
+ for i, t in enumerate(timesteps):
959
+ if self.interrupt:
960
+ continue
961
+
962
+ self._current_timestep = t
963
+
964
+ if boundary_timestep is None or t >= boundary_timestep:
965
+ # wan2.1 or high-noise stage in wan2.2
966
+ current_model = self.transformer
967
+ current_guidance_scale = guidance_scale
968
+ else:
969
+ # low-noise stage in wan2.2
970
+ current_model = self.transformer_2
971
+ current_guidance_scale = guidance_scale_2
972
+
973
+ latent_model_input = latents.to(transformer_dtype)
974
+ timestep = t.expand(latents.shape[0])
975
+
976
+ with current_model.cache_context("cond"):
977
+ noise_pred = current_model(
978
+ hidden_states=latent_model_input,
979
+ timestep=timestep,
980
+ encoder_hidden_states=prompt_embeds,
981
+ control_hidden_states=conditioning_latents,
982
+ control_hidden_states_scale=conditioning_scale,
983
+ attention_kwargs=attention_kwargs,
984
+ return_dict=False,
985
+ )[0]
986
+
987
+ if self.do_classifier_free_guidance:
988
+ with current_model.cache_context("uncond"):
989
+ noise_uncond = current_model(
990
+ hidden_states=latent_model_input,
991
+ timestep=timestep,
992
+ encoder_hidden_states=negative_prompt_embeds,
993
+ control_hidden_states=conditioning_latents,
994
+ control_hidden_states_scale=conditioning_scale,
995
+ attention_kwargs=attention_kwargs,
996
+ return_dict=False,
997
+ )[0]
998
+ noise_pred = noise_uncond + current_guidance_scale * (noise_pred - noise_uncond)
999
+
1000
+ # compute the previous noisy sample x_t -> x_t-1
1001
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
1002
+
1003
+ if callback_on_step_end is not None:
1004
+ callback_kwargs = {}
1005
+ for k in callback_on_step_end_tensor_inputs:
1006
+ callback_kwargs[k] = locals()[k]
1007
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1008
+
1009
+ latents = callback_outputs.pop("latents", latents)
1010
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1011
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1012
+
1013
+ # call the callback, if provided
1014
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1015
+ progress_bar.update()
1016
+
1017
+ if XLA_AVAILABLE:
1018
+ xm.mark_step()
1019
+
1020
+ self._current_timestep = None
1021
+
1022
+ if not output_type == "latent":
1023
+ latents = latents[:, :, num_reference_images:]
1024
+ latents = latents.to(vae_dtype)
1025
+ latents_mean = (
1026
+ torch.tensor(self.vae.config.latents_mean)
1027
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
1028
+ .to(latents.device, latents.dtype)
1029
+ )
1030
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
1031
+ latents.device, latents.dtype
1032
+ )
1033
+ latents = latents / latents_std + latents_mean
1034
+ video = self.vae.decode(latents, return_dict=False)[0]
1035
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
1036
+ else:
1037
+ video = latents
1038
+
1039
+ # Offload all models
1040
+ self.maybe_free_model_hooks()
1041
+
1042
+ if not return_dict:
1043
+ return (video,)
1044
+
1045
+ return WanPipelineOutput(frames=video)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wan/pipeline_wan_video2video.py ADDED
@@ -0,0 +1,725 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The Wan Team and 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 html
16
+ import inspect
17
+ from typing import Any, Callable, Dict, List, Optional, Union
18
+
19
+ import regex as re
20
+ import torch
21
+ from PIL import Image
22
+ from transformers import AutoTokenizer, UMT5EncoderModel
23
+
24
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
25
+ from ...loaders import WanLoraLoaderMixin
26
+ from ...models import AutoencoderKLWan, WanTransformer3DModel
27
+ from ...schedulers import FlowMatchEulerDiscreteScheduler
28
+ from ...utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring
29
+ from ...utils.torch_utils import randn_tensor
30
+ from ...video_processor import VideoProcessor
31
+ from ..pipeline_utils import DiffusionPipeline
32
+ from .pipeline_output import WanPipelineOutput
33
+
34
+
35
+ if is_torch_xla_available():
36
+ import torch_xla.core.xla_model as xm
37
+
38
+ XLA_AVAILABLE = True
39
+ else:
40
+ XLA_AVAILABLE = False
41
+
42
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
43
+
44
+ if is_ftfy_available():
45
+ import ftfy
46
+
47
+
48
+ EXAMPLE_DOC_STRING = """
49
+ Examples:
50
+ ```python
51
+ >>> import torch
52
+ >>> from diffusers.utils import export_to_video, load_video
53
+ >>> from diffusers import AutoencoderKLWan, WanVideoToVideoPipeline
54
+ >>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
55
+
56
+ >>> # Available models: Wan-AI/Wan2.1-T2V-14B-Diffusers, Wan-AI/Wan2.1-T2V-1.3B-Diffusers
57
+ >>> model_id = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"
58
+ >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
59
+ >>> pipe = WanVideoToVideoPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
60
+ >>> flow_shift = 3.0 # 5.0 for 720P, 3.0 for 480P
61
+ >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
62
+ >>> pipe.to("cuda")
63
+
64
+ >>> prompt = "A robot standing on a mountain top. The sun is setting in the background"
65
+ >>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
66
+ >>> video = load_video(
67
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/hiker.mp4"
68
+ ... )
69
+ >>> output = pipe(
70
+ ... video=video,
71
+ ... prompt=prompt,
72
+ ... negative_prompt=negative_prompt,
73
+ ... height=480,
74
+ ... width=720,
75
+ ... guidance_scale=5.0,
76
+ ... strength=0.7,
77
+ ... ).frames[0]
78
+ >>> export_to_video(output, "output.mp4", fps=16)
79
+ ```
80
+ """
81
+
82
+
83
+ def basic_clean(text):
84
+ text = ftfy.fix_text(text)
85
+ text = html.unescape(html.unescape(text))
86
+ return text.strip()
87
+
88
+
89
+ def whitespace_clean(text):
90
+ text = re.sub(r"\s+", " ", text)
91
+ text = text.strip()
92
+ return text
93
+
94
+
95
+ def prompt_clean(text):
96
+ text = whitespace_clean(basic_clean(text))
97
+ return text
98
+
99
+
100
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
101
+ def retrieve_timesteps(
102
+ scheduler,
103
+ num_inference_steps: Optional[int] = None,
104
+ device: Optional[Union[str, torch.device]] = None,
105
+ timesteps: Optional[List[int]] = None,
106
+ sigmas: Optional[List[float]] = None,
107
+ **kwargs,
108
+ ):
109
+ r"""
110
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
111
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
112
+
113
+ Args:
114
+ scheduler (`SchedulerMixin`):
115
+ The scheduler to get timesteps from.
116
+ num_inference_steps (`int`):
117
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
118
+ must be `None`.
119
+ device (`str` or `torch.device`, *optional*):
120
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
121
+ timesteps (`List[int]`, *optional*):
122
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
123
+ `num_inference_steps` and `sigmas` must be `None`.
124
+ sigmas (`List[float]`, *optional*):
125
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
126
+ `num_inference_steps` and `timesteps` must be `None`.
127
+
128
+ Returns:
129
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
130
+ second element is the number of inference steps.
131
+ """
132
+ if timesteps is not None and sigmas is not None:
133
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
134
+ if timesteps is not None:
135
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
136
+ if not accepts_timesteps:
137
+ raise ValueError(
138
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
139
+ f" timestep schedules. Please check whether you are using the correct scheduler."
140
+ )
141
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
142
+ timesteps = scheduler.timesteps
143
+ num_inference_steps = len(timesteps)
144
+ elif sigmas is not None:
145
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
146
+ if not accept_sigmas:
147
+ raise ValueError(
148
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
149
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
150
+ )
151
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
152
+ timesteps = scheduler.timesteps
153
+ num_inference_steps = len(timesteps)
154
+ else:
155
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
156
+ timesteps = scheduler.timesteps
157
+ return timesteps, num_inference_steps
158
+
159
+
160
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
161
+ def retrieve_latents(
162
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
163
+ ):
164
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
165
+ return encoder_output.latent_dist.sample(generator)
166
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
167
+ return encoder_output.latent_dist.mode()
168
+ elif hasattr(encoder_output, "latents"):
169
+ return encoder_output.latents
170
+ else:
171
+ raise AttributeError("Could not access latents of provided encoder_output")
172
+
173
+
174
+ class WanVideoToVideoPipeline(DiffusionPipeline, WanLoraLoaderMixin):
175
+ r"""
176
+ Pipeline for video-to-video generation using Wan.
177
+
178
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
179
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
180
+
181
+ Args:
182
+ tokenizer ([`T5Tokenizer`]):
183
+ Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
184
+ specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
185
+ text_encoder ([`T5EncoderModel`]):
186
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
187
+ the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
188
+ transformer ([`WanTransformer3DModel`]):
189
+ Conditional Transformer to denoise the input latents.
190
+ scheduler ([`UniPCMultistepScheduler`]):
191
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
192
+ vae ([`AutoencoderKLWan`]):
193
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
194
+ """
195
+
196
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
197
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
198
+
199
+ def __init__(
200
+ self,
201
+ tokenizer: AutoTokenizer,
202
+ text_encoder: UMT5EncoderModel,
203
+ transformer: WanTransformer3DModel,
204
+ vae: AutoencoderKLWan,
205
+ scheduler: FlowMatchEulerDiscreteScheduler,
206
+ ):
207
+ super().__init__()
208
+
209
+ self.register_modules(
210
+ vae=vae,
211
+ text_encoder=text_encoder,
212
+ tokenizer=tokenizer,
213
+ transformer=transformer,
214
+ scheduler=scheduler,
215
+ )
216
+
217
+ self.vae_scale_factor_temporal = 2 ** sum(self.vae.temperal_downsample) if getattr(self, "vae", None) else 4
218
+ self.vae_scale_factor_spatial = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8
219
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
220
+
221
+ # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline._get_t5_prompt_embeds
222
+ def _get_t5_prompt_embeds(
223
+ self,
224
+ prompt: Union[str, List[str]] = None,
225
+ num_videos_per_prompt: int = 1,
226
+ max_sequence_length: int = 226,
227
+ device: Optional[torch.device] = None,
228
+ dtype: Optional[torch.dtype] = None,
229
+ ):
230
+ device = device or self._execution_device
231
+ dtype = dtype or self.text_encoder.dtype
232
+
233
+ prompt = [prompt] if isinstance(prompt, str) else prompt
234
+ prompt = [prompt_clean(u) for u in prompt]
235
+ batch_size = len(prompt)
236
+
237
+ text_inputs = self.tokenizer(
238
+ prompt,
239
+ padding="max_length",
240
+ max_length=max_sequence_length,
241
+ truncation=True,
242
+ add_special_tokens=True,
243
+ return_attention_mask=True,
244
+ return_tensors="pt",
245
+ )
246
+ text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
247
+ seq_lens = mask.gt(0).sum(dim=1).long()
248
+
249
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
250
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
251
+ prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
252
+ prompt_embeds = torch.stack(
253
+ [torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
254
+ )
255
+
256
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
257
+ _, seq_len, _ = prompt_embeds.shape
258
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
259
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
260
+
261
+ return prompt_embeds
262
+
263
+ # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline.encode_prompt
264
+ def encode_prompt(
265
+ self,
266
+ prompt: Union[str, List[str]],
267
+ negative_prompt: Optional[Union[str, List[str]]] = None,
268
+ do_classifier_free_guidance: bool = True,
269
+ num_videos_per_prompt: int = 1,
270
+ prompt_embeds: Optional[torch.Tensor] = None,
271
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
272
+ max_sequence_length: int = 226,
273
+ device: Optional[torch.device] = None,
274
+ dtype: Optional[torch.dtype] = None,
275
+ ):
276
+ r"""
277
+ Encodes the prompt into text encoder hidden states.
278
+
279
+ Args:
280
+ prompt (`str` or `List[str]`, *optional*):
281
+ prompt to be encoded
282
+ negative_prompt (`str` or `List[str]`, *optional*):
283
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
284
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
285
+ less than `1`).
286
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
287
+ Whether to use classifier free guidance or not.
288
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
289
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
290
+ prompt_embeds (`torch.Tensor`, *optional*):
291
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
292
+ provided, text embeddings will be generated from `prompt` input argument.
293
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
294
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
295
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
296
+ argument.
297
+ device: (`torch.device`, *optional*):
298
+ torch device
299
+ dtype: (`torch.dtype`, *optional*):
300
+ torch dtype
301
+ """
302
+ device = device or self._execution_device
303
+
304
+ prompt = [prompt] if isinstance(prompt, str) else prompt
305
+ if prompt is not None:
306
+ batch_size = len(prompt)
307
+ else:
308
+ batch_size = prompt_embeds.shape[0]
309
+
310
+ if prompt_embeds is None:
311
+ prompt_embeds = self._get_t5_prompt_embeds(
312
+ prompt=prompt,
313
+ num_videos_per_prompt=num_videos_per_prompt,
314
+ max_sequence_length=max_sequence_length,
315
+ device=device,
316
+ dtype=dtype,
317
+ )
318
+
319
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
320
+ negative_prompt = negative_prompt or ""
321
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
322
+
323
+ if prompt is not None and type(prompt) is not type(negative_prompt):
324
+ raise TypeError(
325
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
326
+ f" {type(prompt)}."
327
+ )
328
+ elif batch_size != len(negative_prompt):
329
+ raise ValueError(
330
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
331
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
332
+ " the batch size of `prompt`."
333
+ )
334
+
335
+ negative_prompt_embeds = self._get_t5_prompt_embeds(
336
+ prompt=negative_prompt,
337
+ num_videos_per_prompt=num_videos_per_prompt,
338
+ max_sequence_length=max_sequence_length,
339
+ device=device,
340
+ dtype=dtype,
341
+ )
342
+
343
+ return prompt_embeds, negative_prompt_embeds
344
+
345
+ def check_inputs(
346
+ self,
347
+ prompt,
348
+ negative_prompt,
349
+ height,
350
+ width,
351
+ video=None,
352
+ latents=None,
353
+ prompt_embeds=None,
354
+ negative_prompt_embeds=None,
355
+ callback_on_step_end_tensor_inputs=None,
356
+ ):
357
+ if height % 16 != 0 or width % 16 != 0:
358
+ raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
359
+
360
+ if callback_on_step_end_tensor_inputs is not None and not all(
361
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
362
+ ):
363
+ raise ValueError(
364
+ 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]}"
365
+ )
366
+
367
+ if prompt is not None and prompt_embeds is not None:
368
+ raise ValueError(
369
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
370
+ " only forward one of the two."
371
+ )
372
+ elif negative_prompt is not None and negative_prompt_embeds is not None:
373
+ raise ValueError(
374
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
375
+ " only forward one of the two."
376
+ )
377
+ elif prompt is None and prompt_embeds is None:
378
+ raise ValueError(
379
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
380
+ )
381
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
382
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
383
+ elif negative_prompt is not None and (
384
+ not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
385
+ ):
386
+ raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
387
+
388
+ if video is not None and latents is not None:
389
+ raise ValueError("Only one of `video` or `latents` should be provided")
390
+
391
+ def prepare_latents(
392
+ self,
393
+ video: Optional[torch.Tensor] = None,
394
+ batch_size: int = 1,
395
+ num_channels_latents: int = 16,
396
+ height: int = 480,
397
+ width: int = 832,
398
+ dtype: Optional[torch.dtype] = None,
399
+ device: Optional[torch.device] = None,
400
+ generator: Optional[torch.Generator] = None,
401
+ latents: Optional[torch.Tensor] = None,
402
+ timestep: Optional[torch.Tensor] = None,
403
+ ):
404
+ if isinstance(generator, list) and len(generator) != batch_size:
405
+ raise ValueError(
406
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
407
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
408
+ )
409
+
410
+ num_latent_frames = (
411
+ (video.size(2) - 1) // self.vae_scale_factor_temporal + 1 if latents is None else latents.size(1)
412
+ )
413
+ shape = (
414
+ batch_size,
415
+ num_channels_latents,
416
+ num_latent_frames,
417
+ height // self.vae_scale_factor_spatial,
418
+ width // self.vae_scale_factor_spatial,
419
+ )
420
+
421
+ if latents is None:
422
+ init_latents = [retrieve_latents(self.vae.encode(vid.unsqueeze(0)), sample_mode="argmax") for vid in video]
423
+
424
+ init_latents = torch.cat(init_latents, dim=0).to(dtype)
425
+
426
+ latents_mean = (
427
+ torch.tensor(self.vae.config.latents_mean).view(1, self.vae.config.z_dim, 1, 1, 1).to(device, dtype)
428
+ )
429
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
430
+ device, dtype
431
+ )
432
+
433
+ init_latents = (init_latents - latents_mean) * latents_std
434
+
435
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
436
+ if hasattr(self.scheduler, "add_noise"):
437
+ latents = self.scheduler.add_noise(init_latents, noise, timestep)
438
+ else:
439
+ latents = self.scheduler.scale_noise(init_latents, timestep, noise)
440
+ else:
441
+ latents = latents.to(device)
442
+
443
+ return latents
444
+
445
+ # Copied from diffusers.pipelines.animatediff.pipeline_animatediff_video2video.AnimateDiffVideoToVideoPipeline.get_timesteps
446
+ def get_timesteps(self, num_inference_steps, timesteps, strength, device):
447
+ # get the original timestep using init_timestep
448
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
449
+
450
+ t_start = max(num_inference_steps - init_timestep, 0)
451
+ timesteps = timesteps[t_start * self.scheduler.order :]
452
+
453
+ return timesteps, num_inference_steps - t_start
454
+
455
+ @property
456
+ def guidance_scale(self):
457
+ return self._guidance_scale
458
+
459
+ @property
460
+ def do_classifier_free_guidance(self):
461
+ return self._guidance_scale > 1.0
462
+
463
+ @property
464
+ def num_timesteps(self):
465
+ return self._num_timesteps
466
+
467
+ @property
468
+ def current_timestep(self):
469
+ return self._current_timestep
470
+
471
+ @property
472
+ def interrupt(self):
473
+ return self._interrupt
474
+
475
+ @property
476
+ def attention_kwargs(self):
477
+ return self._attention_kwargs
478
+
479
+ @torch.no_grad()
480
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
481
+ def __call__(
482
+ self,
483
+ video: List[Image.Image] = None,
484
+ prompt: Union[str, List[str]] = None,
485
+ negative_prompt: Union[str, List[str]] = None,
486
+ height: int = 480,
487
+ width: int = 832,
488
+ num_inference_steps: int = 50,
489
+ timesteps: Optional[List[int]] = None,
490
+ guidance_scale: float = 5.0,
491
+ strength: float = 0.8,
492
+ num_videos_per_prompt: Optional[int] = 1,
493
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
494
+ latents: Optional[torch.Tensor] = None,
495
+ prompt_embeds: Optional[torch.Tensor] = None,
496
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
497
+ output_type: Optional[str] = "np",
498
+ return_dict: bool = True,
499
+ attention_kwargs: Optional[Dict[str, Any]] = None,
500
+ callback_on_step_end: Optional[
501
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
502
+ ] = None,
503
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
504
+ max_sequence_length: int = 512,
505
+ ):
506
+ r"""
507
+ The call function to the pipeline for generation.
508
+
509
+ Args:
510
+ prompt (`str` or `List[str]`, *optional*):
511
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`
512
+ instead.
513
+ height (`int`, defaults to `480`):
514
+ The height in pixels of the generated image.
515
+ width (`int`, defaults to `832`):
516
+ The width in pixels of the generated image.
517
+ num_frames (`int`, defaults to `81`):
518
+ The number of frames in the generated video.
519
+ num_inference_steps (`int`, defaults to `50`):
520
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
521
+ expense of slower inference.
522
+ guidance_scale (`float`, defaults to `5.0`):
523
+ Guidance scale as defined in [Classifier-Free Diffusion
524
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
525
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
526
+ `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
527
+ the text `prompt`, usually at the expense of lower image quality.
528
+ strength (`float`, defaults to `0.8`):
529
+ Higher strength leads to more differences between original image and generated video.
530
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
531
+ The number of images to generate per prompt.
532
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
533
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
534
+ generation deterministic.
535
+ latents (`torch.Tensor`, *optional*):
536
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
537
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
538
+ tensor is generated by sampling using the supplied random `generator`.
539
+ prompt_embeds (`torch.Tensor`, *optional*):
540
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
541
+ provided, text embeddings are generated from the `prompt` input argument.
542
+ output_type (`str`, *optional*, defaults to `"np"`):
543
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
544
+ return_dict (`bool`, *optional*, defaults to `True`):
545
+ Whether or not to return a [`WanPipelineOutput`] instead of a plain tuple.
546
+ attention_kwargs (`dict`, *optional*):
547
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
548
+ `self.processor` in
549
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
550
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
551
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
552
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
553
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
554
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
555
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
556
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
557
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
558
+ `._callback_tensor_inputs` attribute of your pipeline class.
559
+ max_sequence_length (`int`, defaults to `512`):
560
+ The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
561
+ truncated. If the prompt is shorter, it will be padded to this length.
562
+
563
+ Examples:
564
+
565
+ Returns:
566
+ [`~WanPipelineOutput`] or `tuple`:
567
+ If `return_dict` is `True`, [`WanPipelineOutput`] is returned, otherwise a `tuple` is returned where
568
+ the first element is a list with the generated images and the second element is a list of `bool`s
569
+ indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
570
+ """
571
+
572
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
573
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
574
+
575
+ height = height or self.transformer.config.sample_height * self.vae_scale_factor_spatial
576
+ width = width or self.transformer.config.sample_width * self.vae_scale_factor_spatial
577
+ num_videos_per_prompt = 1
578
+
579
+ # 1. Check inputs. Raise error if not correct
580
+ self.check_inputs(
581
+ prompt,
582
+ negative_prompt,
583
+ height,
584
+ width,
585
+ video,
586
+ latents,
587
+ prompt_embeds,
588
+ negative_prompt_embeds,
589
+ callback_on_step_end_tensor_inputs,
590
+ )
591
+
592
+ self._guidance_scale = guidance_scale
593
+ self._attention_kwargs = attention_kwargs
594
+ self._current_timestep = None
595
+ self._interrupt = False
596
+
597
+ device = self._execution_device
598
+
599
+ # 2. Define call parameters
600
+ if prompt is not None and isinstance(prompt, str):
601
+ batch_size = 1
602
+ elif prompt is not None and isinstance(prompt, list):
603
+ batch_size = len(prompt)
604
+ else:
605
+ batch_size = prompt_embeds.shape[0]
606
+
607
+ # 3. Encode input prompt
608
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
609
+ prompt=prompt,
610
+ negative_prompt=negative_prompt,
611
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
612
+ num_videos_per_prompt=num_videos_per_prompt,
613
+ prompt_embeds=prompt_embeds,
614
+ negative_prompt_embeds=negative_prompt_embeds,
615
+ max_sequence_length=max_sequence_length,
616
+ device=device,
617
+ )
618
+
619
+ transformer_dtype = self.transformer.dtype
620
+ prompt_embeds = prompt_embeds.to(transformer_dtype)
621
+ if negative_prompt_embeds is not None:
622
+ negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
623
+
624
+ # 4. Prepare timesteps
625
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
626
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, timesteps, strength, device)
627
+ latent_timestep = timesteps[:1].repeat(batch_size * num_videos_per_prompt)
628
+ self._num_timesteps = len(timesteps)
629
+
630
+ if latents is None:
631
+ video = self.video_processor.preprocess_video(video, height=height, width=width).to(
632
+ device, dtype=torch.float32
633
+ )
634
+
635
+ # 5. Prepare latent variables
636
+ num_channels_latents = self.transformer.config.in_channels
637
+ latents = self.prepare_latents(
638
+ video,
639
+ batch_size * num_videos_per_prompt,
640
+ num_channels_latents,
641
+ height,
642
+ width,
643
+ torch.float32,
644
+ device,
645
+ generator,
646
+ latents,
647
+ latent_timestep,
648
+ )
649
+
650
+ # 6. Denoising loop
651
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
652
+ self._num_timesteps = len(timesteps)
653
+
654
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
655
+ for i, t in enumerate(timesteps):
656
+ if self.interrupt:
657
+ continue
658
+
659
+ self._current_timestep = t
660
+ latent_model_input = latents.to(transformer_dtype)
661
+ timestep = t.expand(latents.shape[0])
662
+
663
+ noise_pred = self.transformer(
664
+ hidden_states=latent_model_input,
665
+ timestep=timestep,
666
+ encoder_hidden_states=prompt_embeds,
667
+ attention_kwargs=attention_kwargs,
668
+ return_dict=False,
669
+ )[0]
670
+
671
+ if self.do_classifier_free_guidance:
672
+ noise_uncond = self.transformer(
673
+ hidden_states=latent_model_input,
674
+ timestep=timestep,
675
+ encoder_hidden_states=negative_prompt_embeds,
676
+ attention_kwargs=attention_kwargs,
677
+ return_dict=False,
678
+ )[0]
679
+ noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)
680
+
681
+ # compute the previous noisy sample x_t -> x_t-1
682
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
683
+
684
+ if callback_on_step_end is not None:
685
+ callback_kwargs = {}
686
+ for k in callback_on_step_end_tensor_inputs:
687
+ callback_kwargs[k] = locals()[k]
688
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
689
+
690
+ latents = callback_outputs.pop("latents", latents)
691
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
692
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
693
+
694
+ # call the callback, if provided
695
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
696
+ progress_bar.update()
697
+
698
+ if XLA_AVAILABLE:
699
+ xm.mark_step()
700
+
701
+ self._current_timestep = None
702
+
703
+ if not output_type == "latent":
704
+ latents = latents.to(self.vae.dtype)
705
+ latents_mean = (
706
+ torch.tensor(self.vae.config.latents_mean)
707
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
708
+ .to(latents.device, latents.dtype)
709
+ )
710
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
711
+ latents.device, latents.dtype
712
+ )
713
+ latents = latents / latents_std + latents_mean
714
+ video = self.vae.decode(latents, return_dict=False)[0]
715
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
716
+ else:
717
+ video = latents
718
+
719
+ # Offload all models
720
+ self.maybe_free_model_hooks()
721
+
722
+ if not return_dict:
723
+ return (video,)
724
+
725
+ return WanPipelineOutput(frames=video)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wuerstchen/__init__.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING
2
+
3
+ from ...utils import (
4
+ DIFFUSERS_SLOW_IMPORT,
5
+ OptionalDependencyNotAvailable,
6
+ _LazyModule,
7
+ get_objects_from_module,
8
+ is_torch_available,
9
+ is_transformers_available,
10
+ )
11
+
12
+
13
+ _dummy_objects = {}
14
+ _import_structure = {}
15
+
16
+ try:
17
+ if not (is_transformers_available() and is_torch_available()):
18
+ raise OptionalDependencyNotAvailable()
19
+ except OptionalDependencyNotAvailable:
20
+ from ...utils import dummy_torch_and_transformers_objects
21
+
22
+ _dummy_objects.update(get_objects_from_module(dummy_torch_and_transformers_objects))
23
+ else:
24
+ _import_structure["modeling_paella_vq_model"] = ["PaellaVQModel"]
25
+ _import_structure["modeling_wuerstchen_diffnext"] = ["WuerstchenDiffNeXt"]
26
+ _import_structure["modeling_wuerstchen_prior"] = ["WuerstchenPrior"]
27
+ _import_structure["pipeline_wuerstchen"] = ["WuerstchenDecoderPipeline"]
28
+ _import_structure["pipeline_wuerstchen_combined"] = ["WuerstchenCombinedPipeline"]
29
+ _import_structure["pipeline_wuerstchen_prior"] = ["DEFAULT_STAGE_C_TIMESTEPS", "WuerstchenPriorPipeline"]
30
+
31
+
32
+ if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
33
+ try:
34
+ if not (is_transformers_available() and is_torch_available()):
35
+ raise OptionalDependencyNotAvailable()
36
+ except OptionalDependencyNotAvailable:
37
+ from ...utils.dummy_torch_and_transformers_objects import * # noqa F403
38
+ else:
39
+ from .modeling_paella_vq_model import PaellaVQModel
40
+ from .modeling_wuerstchen_diffnext import WuerstchenDiffNeXt
41
+ from .modeling_wuerstchen_prior import WuerstchenPrior
42
+ from .pipeline_wuerstchen import WuerstchenDecoderPipeline
43
+ from .pipeline_wuerstchen_combined import WuerstchenCombinedPipeline
44
+ from .pipeline_wuerstchen_prior import DEFAULT_STAGE_C_TIMESTEPS, WuerstchenPriorPipeline
45
+ else:
46
+ import sys
47
+
48
+ sys.modules[__name__] = _LazyModule(
49
+ __name__,
50
+ globals()["__file__"],
51
+ _import_structure,
52
+ module_spec=__spec__,
53
+ )
54
+
55
+ for name, value in _dummy_objects.items():
56
+ setattr(sys.modules[__name__], name, value)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 Dominic Rampas MIT License
2
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ from ...configuration_utils import ConfigMixin, register_to_config
22
+ from ...models.autoencoders.vae import DecoderOutput, VectorQuantizer
23
+ from ...models.modeling_utils import ModelMixin
24
+ from ...models.vq_model import VQEncoderOutput
25
+ from ...utils.accelerate_utils import apply_forward_hook
26
+
27
+
28
+ class MixingResidualBlock(nn.Module):
29
+ """
30
+ Residual block with mixing used by Paella's VQ-VAE.
31
+ """
32
+
33
+ def __init__(self, inp_channels, embed_dim):
34
+ super().__init__()
35
+ # depthwise
36
+ self.norm1 = nn.LayerNorm(inp_channels, elementwise_affine=False, eps=1e-6)
37
+ self.depthwise = nn.Sequential(
38
+ nn.ReplicationPad2d(1), nn.Conv2d(inp_channels, inp_channels, kernel_size=3, groups=inp_channels)
39
+ )
40
+
41
+ # channelwise
42
+ self.norm2 = nn.LayerNorm(inp_channels, elementwise_affine=False, eps=1e-6)
43
+ self.channelwise = nn.Sequential(
44
+ nn.Linear(inp_channels, embed_dim), nn.GELU(), nn.Linear(embed_dim, inp_channels)
45
+ )
46
+
47
+ self.gammas = nn.Parameter(torch.zeros(6), requires_grad=True)
48
+
49
+ def forward(self, x):
50
+ mods = self.gammas
51
+ x_temp = self.norm1(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) * (1 + mods[0]) + mods[1]
52
+ x = x + self.depthwise(x_temp) * mods[2]
53
+ x_temp = self.norm2(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) * (1 + mods[3]) + mods[4]
54
+ x = x + self.channelwise(x_temp.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) * mods[5]
55
+ return x
56
+
57
+
58
+ class PaellaVQModel(ModelMixin, ConfigMixin):
59
+ r"""VQ-VAE model from Paella model.
60
+
61
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for the generic methods the library
62
+ implements for all the model (such as downloading or saving, etc.)
63
+
64
+ Parameters:
65
+ in_channels (int, *optional*, defaults to 3): Number of channels in the input image.
66
+ out_channels (int, *optional*, defaults to 3): Number of channels in the output.
67
+ up_down_scale_factor (int, *optional*, defaults to 2): Up and Downscale factor of the input image.
68
+ levels (int, *optional*, defaults to 2): Number of levels in the model.
69
+ bottleneck_blocks (int, *optional*, defaults to 12): Number of bottleneck blocks in the model.
70
+ embed_dim (int, *optional*, defaults to 384): Number of hidden channels in the model.
71
+ latent_channels (int, *optional*, defaults to 4): Number of latent channels in the VQ-VAE model.
72
+ num_vq_embeddings (int, *optional*, defaults to 8192): Number of codebook vectors in the VQ-VAE.
73
+ scale_factor (float, *optional*, defaults to 0.3764): Scaling factor of the latent space.
74
+ """
75
+
76
+ @register_to_config
77
+ def __init__(
78
+ self,
79
+ in_channels: int = 3,
80
+ out_channels: int = 3,
81
+ up_down_scale_factor: int = 2,
82
+ levels: int = 2,
83
+ bottleneck_blocks: int = 12,
84
+ embed_dim: int = 384,
85
+ latent_channels: int = 4,
86
+ num_vq_embeddings: int = 8192,
87
+ scale_factor: float = 0.3764,
88
+ ):
89
+ super().__init__()
90
+
91
+ c_levels = [embed_dim // (2**i) for i in reversed(range(levels))]
92
+ # Encoder blocks
93
+ self.in_block = nn.Sequential(
94
+ nn.PixelUnshuffle(up_down_scale_factor),
95
+ nn.Conv2d(in_channels * up_down_scale_factor**2, c_levels[0], kernel_size=1),
96
+ )
97
+ down_blocks = []
98
+ for i in range(levels):
99
+ if i > 0:
100
+ down_blocks.append(nn.Conv2d(c_levels[i - 1], c_levels[i], kernel_size=4, stride=2, padding=1))
101
+ block = MixingResidualBlock(c_levels[i], c_levels[i] * 4)
102
+ down_blocks.append(block)
103
+ down_blocks.append(
104
+ nn.Sequential(
105
+ nn.Conv2d(c_levels[-1], latent_channels, kernel_size=1, bias=False),
106
+ nn.BatchNorm2d(latent_channels), # then normalize them to have mean 0 and std 1
107
+ )
108
+ )
109
+ self.down_blocks = nn.Sequential(*down_blocks)
110
+
111
+ # Vector Quantizer
112
+ self.vquantizer = VectorQuantizer(num_vq_embeddings, vq_embed_dim=latent_channels, legacy=False, beta=0.25)
113
+
114
+ # Decoder blocks
115
+ up_blocks = [nn.Sequential(nn.Conv2d(latent_channels, c_levels[-1], kernel_size=1))]
116
+ for i in range(levels):
117
+ for j in range(bottleneck_blocks if i == 0 else 1):
118
+ block = MixingResidualBlock(c_levels[levels - 1 - i], c_levels[levels - 1 - i] * 4)
119
+ up_blocks.append(block)
120
+ if i < levels - 1:
121
+ up_blocks.append(
122
+ nn.ConvTranspose2d(
123
+ c_levels[levels - 1 - i], c_levels[levels - 2 - i], kernel_size=4, stride=2, padding=1
124
+ )
125
+ )
126
+ self.up_blocks = nn.Sequential(*up_blocks)
127
+ self.out_block = nn.Sequential(
128
+ nn.Conv2d(c_levels[0], out_channels * up_down_scale_factor**2, kernel_size=1),
129
+ nn.PixelShuffle(up_down_scale_factor),
130
+ )
131
+
132
+ @apply_forward_hook
133
+ def encode(self, x: torch.Tensor, return_dict: bool = True) -> VQEncoderOutput:
134
+ h = self.in_block(x)
135
+ h = self.down_blocks(h)
136
+
137
+ if not return_dict:
138
+ return (h,)
139
+
140
+ return VQEncoderOutput(latents=h)
141
+
142
+ @apply_forward_hook
143
+ def decode(
144
+ self, h: torch.Tensor, force_not_quantize: bool = True, return_dict: bool = True
145
+ ) -> Union[DecoderOutput, torch.Tensor]:
146
+ if not force_not_quantize:
147
+ quant, _, _ = self.vquantizer(h)
148
+ else:
149
+ quant = h
150
+
151
+ x = self.up_blocks(quant)
152
+ dec = self.out_block(x)
153
+ if not return_dict:
154
+ return (dec,)
155
+
156
+ return DecoderOutput(sample=dec)
157
+
158
+ def forward(self, sample: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]:
159
+ r"""
160
+ Args:
161
+ sample (`torch.Tensor`): Input sample.
162
+ return_dict (`bool`, *optional*, defaults to `True`):
163
+ Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
164
+ """
165
+ x = sample
166
+ h = self.encode(x).latents
167
+ dec = self.decode(h).sample
168
+
169
+ if not return_dict:
170
+ return (dec,)
171
+
172
+ return DecoderOutput(sample=dec)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from ...models.attention_processor import Attention
5
+
6
+
7
+ class WuerstchenLayerNorm(nn.LayerNorm):
8
+ def __init__(self, *args, **kwargs):
9
+ super().__init__(*args, **kwargs)
10
+
11
+ def forward(self, x):
12
+ x = x.permute(0, 2, 3, 1)
13
+ x = super().forward(x)
14
+ return x.permute(0, 3, 1, 2)
15
+
16
+
17
+ class TimestepBlock(nn.Module):
18
+ def __init__(self, c, c_timestep):
19
+ super().__init__()
20
+
21
+ self.mapper = nn.Linear(c_timestep, c * 2)
22
+
23
+ def forward(self, x, t):
24
+ a, b = self.mapper(t)[:, :, None, None].chunk(2, dim=1)
25
+ return x * (1 + a) + b
26
+
27
+
28
+ class ResBlock(nn.Module):
29
+ def __init__(self, c, c_skip=0, kernel_size=3, dropout=0.0):
30
+ super().__init__()
31
+
32
+ self.depthwise = nn.Conv2d(c + c_skip, c, kernel_size=kernel_size, padding=kernel_size // 2, groups=c)
33
+ self.norm = WuerstchenLayerNorm(c, elementwise_affine=False, eps=1e-6)
34
+ self.channelwise = nn.Sequential(
35
+ nn.Linear(c, c * 4), nn.GELU(), GlobalResponseNorm(c * 4), nn.Dropout(dropout), nn.Linear(c * 4, c)
36
+ )
37
+
38
+ def forward(self, x, x_skip=None):
39
+ x_res = x
40
+ if x_skip is not None:
41
+ x = torch.cat([x, x_skip], dim=1)
42
+ x = self.norm(self.depthwise(x)).permute(0, 2, 3, 1)
43
+ x = self.channelwise(x).permute(0, 3, 1, 2)
44
+ return x + x_res
45
+
46
+
47
+ # from https://github.com/facebookresearch/ConvNeXt-V2/blob/3608f67cc1dae164790c5d0aead7bf2d73d9719b/models/utils.py#L105
48
+ class GlobalResponseNorm(nn.Module):
49
+ def __init__(self, dim):
50
+ super().__init__()
51
+ self.gamma = nn.Parameter(torch.zeros(1, 1, 1, dim))
52
+ self.beta = nn.Parameter(torch.zeros(1, 1, 1, dim))
53
+
54
+ def forward(self, x):
55
+ agg_norm = torch.norm(x, p=2, dim=(1, 2), keepdim=True)
56
+ stand_div_norm = agg_norm / (agg_norm.mean(dim=-1, keepdim=True) + 1e-6)
57
+ return self.gamma * (x * stand_div_norm) + self.beta + x
58
+
59
+
60
+ class AttnBlock(nn.Module):
61
+ def __init__(self, c, c_cond, nhead, self_attn=True, dropout=0.0):
62
+ super().__init__()
63
+
64
+ self.self_attn = self_attn
65
+ self.norm = WuerstchenLayerNorm(c, elementwise_affine=False, eps=1e-6)
66
+ self.attention = Attention(query_dim=c, heads=nhead, dim_head=c // nhead, dropout=dropout, bias=True)
67
+ self.kv_mapper = nn.Sequential(nn.SiLU(), nn.Linear(c_cond, c))
68
+
69
+ def forward(self, x, kv):
70
+ kv = self.kv_mapper(kv)
71
+ norm_x = self.norm(x)
72
+ if self.self_attn:
73
+ batch_size, channel, _, _ = x.shape
74
+ kv = torch.cat([norm_x.view(batch_size, channel, -1).transpose(1, 2), kv], dim=1)
75
+ x = x + self.attention(norm_x, encoder_hidden_states=kv)
76
+ return x
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Dominic Rampas MIT License
2
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import math
17
+
18
+ import numpy as np
19
+ import torch
20
+ import torch.nn as nn
21
+
22
+ from ...configuration_utils import ConfigMixin, register_to_config
23
+ from ...models.modeling_utils import ModelMixin
24
+ from .modeling_wuerstchen_common import AttnBlock, GlobalResponseNorm, TimestepBlock, WuerstchenLayerNorm
25
+
26
+
27
+ class WuerstchenDiffNeXt(ModelMixin, ConfigMixin):
28
+ @register_to_config
29
+ def __init__(
30
+ self,
31
+ c_in=4,
32
+ c_out=4,
33
+ c_r=64,
34
+ patch_size=2,
35
+ c_cond=1024,
36
+ c_hidden=[320, 640, 1280, 1280],
37
+ nhead=[-1, 10, 20, 20],
38
+ blocks=[4, 4, 14, 4],
39
+ level_config=["CT", "CTA", "CTA", "CTA"],
40
+ inject_effnet=[False, True, True, True],
41
+ effnet_embd=16,
42
+ clip_embd=1024,
43
+ kernel_size=3,
44
+ dropout=0.1,
45
+ ):
46
+ super().__init__()
47
+ self.c_r = c_r
48
+ self.c_cond = c_cond
49
+ if not isinstance(dropout, list):
50
+ dropout = [dropout] * len(c_hidden)
51
+
52
+ # CONDITIONING
53
+ self.clip_mapper = nn.Linear(clip_embd, c_cond)
54
+ self.effnet_mappers = nn.ModuleList(
55
+ [
56
+ nn.Conv2d(effnet_embd, c_cond, kernel_size=1) if inject else None
57
+ for inject in inject_effnet + list(reversed(inject_effnet))
58
+ ]
59
+ )
60
+ self.seq_norm = nn.LayerNorm(c_cond, elementwise_affine=False, eps=1e-6)
61
+
62
+ self.embedding = nn.Sequential(
63
+ nn.PixelUnshuffle(patch_size),
64
+ nn.Conv2d(c_in * (patch_size**2), c_hidden[0], kernel_size=1),
65
+ WuerstchenLayerNorm(c_hidden[0], elementwise_affine=False, eps=1e-6),
66
+ )
67
+
68
+ def get_block(block_type, c_hidden, nhead, c_skip=0, dropout=0):
69
+ if block_type == "C":
70
+ return ResBlockStageB(c_hidden, c_skip, kernel_size=kernel_size, dropout=dropout)
71
+ elif block_type == "A":
72
+ return AttnBlock(c_hidden, c_cond, nhead, self_attn=True, dropout=dropout)
73
+ elif block_type == "T":
74
+ return TimestepBlock(c_hidden, c_r)
75
+ else:
76
+ raise ValueError(f"Block type {block_type} not supported")
77
+
78
+ # BLOCKS
79
+ # -- down blocks
80
+ self.down_blocks = nn.ModuleList()
81
+ for i in range(len(c_hidden)):
82
+ down_block = nn.ModuleList()
83
+ if i > 0:
84
+ down_block.append(
85
+ nn.Sequential(
86
+ WuerstchenLayerNorm(c_hidden[i - 1], elementwise_affine=False, eps=1e-6),
87
+ nn.Conv2d(c_hidden[i - 1], c_hidden[i], kernel_size=2, stride=2),
88
+ )
89
+ )
90
+ for _ in range(blocks[i]):
91
+ for block_type in level_config[i]:
92
+ c_skip = c_cond if inject_effnet[i] else 0
93
+ down_block.append(get_block(block_type, c_hidden[i], nhead[i], c_skip=c_skip, dropout=dropout[i]))
94
+ self.down_blocks.append(down_block)
95
+
96
+ # -- up blocks
97
+ self.up_blocks = nn.ModuleList()
98
+ for i in reversed(range(len(c_hidden))):
99
+ up_block = nn.ModuleList()
100
+ for j in range(blocks[i]):
101
+ for k, block_type in enumerate(level_config[i]):
102
+ c_skip = c_hidden[i] if i < len(c_hidden) - 1 and j == k == 0 else 0
103
+ c_skip += c_cond if inject_effnet[i] else 0
104
+ up_block.append(get_block(block_type, c_hidden[i], nhead[i], c_skip=c_skip, dropout=dropout[i]))
105
+ if i > 0:
106
+ up_block.append(
107
+ nn.Sequential(
108
+ WuerstchenLayerNorm(c_hidden[i], elementwise_affine=False, eps=1e-6),
109
+ nn.ConvTranspose2d(c_hidden[i], c_hidden[i - 1], kernel_size=2, stride=2),
110
+ )
111
+ )
112
+ self.up_blocks.append(up_block)
113
+
114
+ # OUTPUT
115
+ self.clf = nn.Sequential(
116
+ WuerstchenLayerNorm(c_hidden[0], elementwise_affine=False, eps=1e-6),
117
+ nn.Conv2d(c_hidden[0], 2 * c_out * (patch_size**2), kernel_size=1),
118
+ nn.PixelShuffle(patch_size),
119
+ )
120
+
121
+ # --- WEIGHT INIT ---
122
+ self.apply(self._init_weights)
123
+
124
+ def _init_weights(self, m):
125
+ # General init
126
+ if isinstance(m, (nn.Conv2d, nn.Linear)):
127
+ nn.init.xavier_uniform_(m.weight)
128
+ if m.bias is not None:
129
+ nn.init.constant_(m.bias, 0)
130
+
131
+ for mapper in self.effnet_mappers:
132
+ if mapper is not None:
133
+ nn.init.normal_(mapper.weight, std=0.02) # conditionings
134
+ nn.init.normal_(self.clip_mapper.weight, std=0.02) # conditionings
135
+ nn.init.xavier_uniform_(self.embedding[1].weight, 0.02) # inputs
136
+ nn.init.constant_(self.clf[1].weight, 0) # outputs
137
+
138
+ # blocks
139
+ for level_block in self.down_blocks + self.up_blocks:
140
+ for block in level_block:
141
+ if isinstance(block, ResBlockStageB):
142
+ block.channelwise[-1].weight.data *= np.sqrt(1 / sum(self.config.blocks))
143
+ elif isinstance(block, TimestepBlock):
144
+ nn.init.constant_(block.mapper.weight, 0)
145
+
146
+ def gen_r_embedding(self, r, max_positions=10000):
147
+ r = r * max_positions
148
+ half_dim = self.c_r // 2
149
+ emb = math.log(max_positions) / (half_dim - 1)
150
+ emb = torch.arange(half_dim, device=r.device).float().mul(-emb).exp()
151
+ emb = r[:, None] * emb[None, :]
152
+ emb = torch.cat([emb.sin(), emb.cos()], dim=1)
153
+ if self.c_r % 2 == 1: # zero pad
154
+ emb = nn.functional.pad(emb, (0, 1), mode="constant")
155
+ return emb.to(dtype=r.dtype)
156
+
157
+ def gen_c_embeddings(self, clip):
158
+ clip = self.clip_mapper(clip)
159
+ clip = self.seq_norm(clip)
160
+ return clip
161
+
162
+ def _down_encode(self, x, r_embed, effnet, clip=None):
163
+ level_outputs = []
164
+ for i, down_block in enumerate(self.down_blocks):
165
+ effnet_c = None
166
+ for block in down_block:
167
+ if isinstance(block, ResBlockStageB):
168
+ if effnet_c is None and self.effnet_mappers[i] is not None:
169
+ dtype = effnet.dtype
170
+ effnet_c = self.effnet_mappers[i](
171
+ nn.functional.interpolate(
172
+ effnet.float(), size=x.shape[-2:], mode="bicubic", antialias=True, align_corners=True
173
+ ).to(dtype)
174
+ )
175
+ skip = effnet_c if self.effnet_mappers[i] is not None else None
176
+ x = block(x, skip)
177
+ elif isinstance(block, AttnBlock):
178
+ x = block(x, clip)
179
+ elif isinstance(block, TimestepBlock):
180
+ x = block(x, r_embed)
181
+ else:
182
+ x = block(x)
183
+ level_outputs.insert(0, x)
184
+ return level_outputs
185
+
186
+ def _up_decode(self, level_outputs, r_embed, effnet, clip=None):
187
+ x = level_outputs[0]
188
+ for i, up_block in enumerate(self.up_blocks):
189
+ effnet_c = None
190
+ for j, block in enumerate(up_block):
191
+ if isinstance(block, ResBlockStageB):
192
+ if effnet_c is None and self.effnet_mappers[len(self.down_blocks) + i] is not None:
193
+ dtype = effnet.dtype
194
+ effnet_c = self.effnet_mappers[len(self.down_blocks) + i](
195
+ nn.functional.interpolate(
196
+ effnet.float(), size=x.shape[-2:], mode="bicubic", antialias=True, align_corners=True
197
+ ).to(dtype)
198
+ )
199
+ skip = level_outputs[i] if j == 0 and i > 0 else None
200
+ if effnet_c is not None:
201
+ if skip is not None:
202
+ skip = torch.cat([skip, effnet_c], dim=1)
203
+ else:
204
+ skip = effnet_c
205
+ x = block(x, skip)
206
+ elif isinstance(block, AttnBlock):
207
+ x = block(x, clip)
208
+ elif isinstance(block, TimestepBlock):
209
+ x = block(x, r_embed)
210
+ else:
211
+ x = block(x)
212
+ return x
213
+
214
+ def forward(self, x, r, effnet, clip=None, x_cat=None, eps=1e-3, return_noise=True):
215
+ if x_cat is not None:
216
+ x = torch.cat([x, x_cat], dim=1)
217
+ # Process the conditioning embeddings
218
+ r_embed = self.gen_r_embedding(r)
219
+ if clip is not None:
220
+ clip = self.gen_c_embeddings(clip)
221
+
222
+ # Model Blocks
223
+ x_in = x
224
+ x = self.embedding(x)
225
+ level_outputs = self._down_encode(x, r_embed, effnet, clip)
226
+ x = self._up_decode(level_outputs, r_embed, effnet, clip)
227
+ a, b = self.clf(x).chunk(2, dim=1)
228
+ b = b.sigmoid() * (1 - eps * 2) + eps
229
+ if return_noise:
230
+ return (x_in - a) / b
231
+ else:
232
+ return a, b
233
+
234
+
235
+ class ResBlockStageB(nn.Module):
236
+ def __init__(self, c, c_skip=0, kernel_size=3, dropout=0.0):
237
+ super().__init__()
238
+ self.depthwise = nn.Conv2d(c, c, kernel_size=kernel_size, padding=kernel_size // 2, groups=c)
239
+ self.norm = WuerstchenLayerNorm(c, elementwise_affine=False, eps=1e-6)
240
+ self.channelwise = nn.Sequential(
241
+ nn.Linear(c + c_skip, c * 4),
242
+ nn.GELU(),
243
+ GlobalResponseNorm(c * 4),
244
+ nn.Dropout(dropout),
245
+ nn.Linear(c * 4, c),
246
+ )
247
+
248
+ def forward(self, x, x_skip=None):
249
+ x_res = x
250
+ x = self.norm(self.depthwise(x))
251
+ if x_skip is not None:
252
+ x = torch.cat([x, x_skip], dim=1)
253
+ x = self.channelwise(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
254
+ return x + x_res
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Dominic Rampas MIT License
2
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import math
17
+ from typing import Dict, Union
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+
22
+ from ...configuration_utils import ConfigMixin, register_to_config
23
+ from ...loaders import PeftAdapterMixin, UNet2DConditionLoadersMixin
24
+ from ...models.attention_processor import (
25
+ ADDED_KV_ATTENTION_PROCESSORS,
26
+ CROSS_ATTENTION_PROCESSORS,
27
+ AttentionProcessor,
28
+ AttnAddedKVProcessor,
29
+ AttnProcessor,
30
+ )
31
+ from ...models.modeling_utils import ModelMixin
32
+ from .modeling_wuerstchen_common import AttnBlock, ResBlock, TimestepBlock, WuerstchenLayerNorm
33
+
34
+
35
+ class WuerstchenPrior(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin, PeftAdapterMixin):
36
+ unet_name = "prior"
37
+ _supports_gradient_checkpointing = True
38
+
39
+ @register_to_config
40
+ def __init__(self, c_in=16, c=1280, c_cond=1024, c_r=64, depth=16, nhead=16, dropout=0.1):
41
+ super().__init__()
42
+
43
+ self.c_r = c_r
44
+ self.projection = nn.Conv2d(c_in, c, kernel_size=1)
45
+ self.cond_mapper = nn.Sequential(
46
+ nn.Linear(c_cond, c),
47
+ nn.LeakyReLU(0.2),
48
+ nn.Linear(c, c),
49
+ )
50
+
51
+ self.blocks = nn.ModuleList()
52
+ for _ in range(depth):
53
+ self.blocks.append(ResBlock(c, dropout=dropout))
54
+ self.blocks.append(TimestepBlock(c, c_r))
55
+ self.blocks.append(AttnBlock(c, c, nhead, self_attn=True, dropout=dropout))
56
+ self.out = nn.Sequential(
57
+ WuerstchenLayerNorm(c, elementwise_affine=False, eps=1e-6),
58
+ nn.Conv2d(c, c_in * 2, kernel_size=1),
59
+ )
60
+
61
+ self.gradient_checkpointing = False
62
+ self.set_default_attn_processor()
63
+
64
+ @property
65
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
66
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
67
+ r"""
68
+ Returns:
69
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
70
+ indexed by its weight name.
71
+ """
72
+ # set recursively
73
+ processors = {}
74
+
75
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
76
+ if hasattr(module, "get_processor"):
77
+ processors[f"{name}.processor"] = module.get_processor()
78
+
79
+ for sub_name, child in module.named_children():
80
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
81
+
82
+ return processors
83
+
84
+ for name, module in self.named_children():
85
+ fn_recursive_add_processors(name, module, processors)
86
+
87
+ return processors
88
+
89
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
90
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
91
+ r"""
92
+ Sets the attention processor to use to compute attention.
93
+
94
+ Parameters:
95
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
96
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
97
+ for **all** `Attention` layers.
98
+
99
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
100
+ processor. This is strongly recommended when setting trainable attention processors.
101
+
102
+ """
103
+ count = len(self.attn_processors.keys())
104
+
105
+ if isinstance(processor, dict) and len(processor) != count:
106
+ raise ValueError(
107
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
108
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
109
+ )
110
+
111
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
112
+ if hasattr(module, "set_processor"):
113
+ if not isinstance(processor, dict):
114
+ module.set_processor(processor)
115
+ else:
116
+ module.set_processor(processor.pop(f"{name}.processor"))
117
+
118
+ for sub_name, child in module.named_children():
119
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
120
+
121
+ for name, module in self.named_children():
122
+ fn_recursive_attn_processor(name, module, processor)
123
+
124
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
125
+ def set_default_attn_processor(self):
126
+ """
127
+ Disables custom attention processors and sets the default attention implementation.
128
+ """
129
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
130
+ processor = AttnAddedKVProcessor()
131
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
132
+ processor = AttnProcessor()
133
+ else:
134
+ raise ValueError(
135
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
136
+ )
137
+
138
+ self.set_attn_processor(processor)
139
+
140
+ def gen_r_embedding(self, r, max_positions=10000):
141
+ r = r * max_positions
142
+ half_dim = self.c_r // 2
143
+ emb = math.log(max_positions) / (half_dim - 1)
144
+ emb = torch.arange(half_dim, device=r.device).float().mul(-emb).exp()
145
+ emb = r[:, None] * emb[None, :]
146
+ emb = torch.cat([emb.sin(), emb.cos()], dim=1)
147
+ if self.c_r % 2 == 1: # zero pad
148
+ emb = nn.functional.pad(emb, (0, 1), mode="constant")
149
+ return emb.to(dtype=r.dtype)
150
+
151
+ def forward(self, x, r, c):
152
+ x_in = x
153
+ x = self.projection(x)
154
+ c_embed = self.cond_mapper(c)
155
+ r_embed = self.gen_r_embedding(r)
156
+
157
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
158
+ for block in self.blocks:
159
+ if isinstance(block, AttnBlock):
160
+ x = self._gradient_checkpointing_func(block, x, c_embed)
161
+ elif isinstance(block, TimestepBlock):
162
+ x = self._gradient_checkpointing_func(block, x, r_embed)
163
+ else:
164
+ x = self._gradient_checkpointing_func(block, x)
165
+ else:
166
+ for block in self.blocks:
167
+ if isinstance(block, AttnBlock):
168
+ x = block(x, c_embed)
169
+ elif isinstance(block, TimestepBlock):
170
+ x = block(x, r_embed)
171
+ else:
172
+ x = block(x)
173
+ a, b = self.out(x).chunk(2, dim=1)
174
+ return (x_in - a) / ((1 - b).abs() + 1e-5)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py ADDED
@@ -0,0 +1,449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+ from typing import Callable, Dict, List, Optional, Union
16
+
17
+ import numpy as np
18
+ import torch
19
+ from transformers import CLIPTextModel, CLIPTokenizer
20
+
21
+ from ...schedulers import DDPMWuerstchenScheduler
22
+ from ...utils import deprecate, is_torch_xla_available, logging, replace_example_docstring
23
+ from ...utils.torch_utils import randn_tensor
24
+ from ..pipeline_utils import DeprecatedPipelineMixin, DiffusionPipeline, ImagePipelineOutput
25
+ from .modeling_paella_vq_model import PaellaVQModel
26
+ from .modeling_wuerstchen_diffnext import WuerstchenDiffNeXt
27
+
28
+
29
+ if is_torch_xla_available():
30
+ import torch_xla.core.xla_model as xm
31
+
32
+ XLA_AVAILABLE = True
33
+ else:
34
+ XLA_AVAILABLE = False
35
+
36
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
37
+
38
+
39
+ EXAMPLE_DOC_STRING = """
40
+ Examples:
41
+ ```py
42
+ >>> import torch
43
+ >>> from diffusers import WuerstchenPriorPipeline, WuerstchenDecoderPipeline
44
+
45
+ >>> prior_pipe = WuerstchenPriorPipeline.from_pretrained(
46
+ ... "warp-ai/wuerstchen-prior", torch_dtype=torch.float16
47
+ ... ).to("cuda")
48
+ >>> gen_pipe = WuerstchenDecoderPipeline.from_pretrain("warp-ai/wuerstchen", torch_dtype=torch.float16).to(
49
+ ... "cuda"
50
+ ... )
51
+
52
+ >>> prompt = "an image of a shiba inu, donning a spacesuit and helmet"
53
+ >>> prior_output = pipe(prompt)
54
+ >>> images = gen_pipe(prior_output.image_embeddings, prompt=prompt)
55
+ ```
56
+ """
57
+
58
+
59
+ class WuerstchenDecoderPipeline(DeprecatedPipelineMixin, DiffusionPipeline):
60
+ """
61
+ Pipeline for generating images from the Wuerstchen model.
62
+
63
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
64
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
65
+
66
+ Args:
67
+ tokenizer (`CLIPTokenizer`):
68
+ The CLIP tokenizer.
69
+ text_encoder (`CLIPTextModel`):
70
+ The CLIP text encoder.
71
+ decoder ([`WuerstchenDiffNeXt`]):
72
+ The WuerstchenDiffNeXt unet decoder.
73
+ vqgan ([`PaellaVQModel`]):
74
+ The VQGAN model.
75
+ scheduler ([`DDPMWuerstchenScheduler`]):
76
+ A scheduler to be used in combination with `prior` to generate image embedding.
77
+ latent_dim_scale (float, `optional`, defaults to 10.67):
78
+ Multiplier to determine the VQ latent space size from the image embeddings. If the image embeddings are
79
+ height=24 and width=24, the VQ latent shape needs to be height=int(24*10.67)=256 and
80
+ width=int(24*10.67)=256 in order to match the training conditions.
81
+ """
82
+
83
+ model_cpu_offload_seq = "text_encoder->decoder->vqgan"
84
+ _callback_tensor_inputs = [
85
+ "latents",
86
+ "text_encoder_hidden_states",
87
+ "negative_prompt_embeds",
88
+ "image_embeddings",
89
+ ]
90
+
91
+ def __init__(
92
+ self,
93
+ tokenizer: CLIPTokenizer,
94
+ text_encoder: CLIPTextModel,
95
+ decoder: WuerstchenDiffNeXt,
96
+ scheduler: DDPMWuerstchenScheduler,
97
+ vqgan: PaellaVQModel,
98
+ latent_dim_scale: float = 10.67,
99
+ ) -> None:
100
+ super().__init__()
101
+ self.register_modules(
102
+ tokenizer=tokenizer,
103
+ text_encoder=text_encoder,
104
+ decoder=decoder,
105
+ scheduler=scheduler,
106
+ vqgan=vqgan,
107
+ )
108
+ self.register_to_config(latent_dim_scale=latent_dim_scale)
109
+
110
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip.UnCLIPPipeline.prepare_latents
111
+ def prepare_latents(self, shape, dtype, device, generator, latents, scheduler):
112
+ if latents is None:
113
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
114
+ else:
115
+ if latents.shape != shape:
116
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
117
+ latents = latents.to(device)
118
+
119
+ latents = latents * scheduler.init_noise_sigma
120
+ return latents
121
+
122
+ def encode_prompt(
123
+ self,
124
+ prompt,
125
+ device,
126
+ num_images_per_prompt,
127
+ do_classifier_free_guidance,
128
+ negative_prompt=None,
129
+ ):
130
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
131
+ # get prompt text embeddings
132
+ text_inputs = self.tokenizer(
133
+ prompt,
134
+ padding="max_length",
135
+ max_length=self.tokenizer.model_max_length,
136
+ truncation=True,
137
+ return_tensors="pt",
138
+ )
139
+ text_input_ids = text_inputs.input_ids
140
+ attention_mask = text_inputs.attention_mask
141
+
142
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
143
+
144
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
145
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
146
+ logger.warning(
147
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
148
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
149
+ )
150
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
151
+ attention_mask = attention_mask[:, : self.tokenizer.model_max_length]
152
+
153
+ text_encoder_output = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask.to(device))
154
+ text_encoder_hidden_states = text_encoder_output.last_hidden_state
155
+ text_encoder_hidden_states = text_encoder_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
156
+
157
+ uncond_text_encoder_hidden_states = None
158
+ if do_classifier_free_guidance:
159
+ uncond_tokens: List[str]
160
+ if negative_prompt is None:
161
+ uncond_tokens = [""] * batch_size
162
+ elif type(prompt) is not type(negative_prompt):
163
+ raise TypeError(
164
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
165
+ f" {type(prompt)}."
166
+ )
167
+ elif isinstance(negative_prompt, str):
168
+ uncond_tokens = [negative_prompt]
169
+ elif batch_size != len(negative_prompt):
170
+ raise ValueError(
171
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
172
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
173
+ " the batch size of `prompt`."
174
+ )
175
+ else:
176
+ uncond_tokens = negative_prompt
177
+
178
+ uncond_input = self.tokenizer(
179
+ uncond_tokens,
180
+ padding="max_length",
181
+ max_length=self.tokenizer.model_max_length,
182
+ truncation=True,
183
+ return_tensors="pt",
184
+ )
185
+ negative_prompt_embeds_text_encoder_output = self.text_encoder(
186
+ uncond_input.input_ids.to(device), attention_mask=uncond_input.attention_mask.to(device)
187
+ )
188
+
189
+ uncond_text_encoder_hidden_states = negative_prompt_embeds_text_encoder_output.last_hidden_state
190
+
191
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
192
+ seq_len = uncond_text_encoder_hidden_states.shape[1]
193
+ uncond_text_encoder_hidden_states = uncond_text_encoder_hidden_states.repeat(1, num_images_per_prompt, 1)
194
+ uncond_text_encoder_hidden_states = uncond_text_encoder_hidden_states.view(
195
+ batch_size * num_images_per_prompt, seq_len, -1
196
+ )
197
+ # done duplicates
198
+
199
+ # For classifier free guidance, we need to do two forward passes.
200
+ # Here we concatenate the unconditional and text embeddings into a single batch
201
+ # to avoid doing two forward passes
202
+ return text_encoder_hidden_states, uncond_text_encoder_hidden_states
203
+
204
+ @property
205
+ def guidance_scale(self):
206
+ return self._guidance_scale
207
+
208
+ @property
209
+ def do_classifier_free_guidance(self):
210
+ return self._guidance_scale > 1
211
+
212
+ @property
213
+ def num_timesteps(self):
214
+ return self._num_timesteps
215
+
216
+ @torch.no_grad()
217
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
218
+ def __call__(
219
+ self,
220
+ image_embeddings: Union[torch.Tensor, List[torch.Tensor]],
221
+ prompt: Union[str, List[str]] = None,
222
+ num_inference_steps: int = 12,
223
+ timesteps: Optional[List[float]] = None,
224
+ guidance_scale: float = 0.0,
225
+ negative_prompt: Optional[Union[str, List[str]]] = None,
226
+ num_images_per_prompt: int = 1,
227
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
228
+ latents: Optional[torch.Tensor] = None,
229
+ output_type: Optional[str] = "pil",
230
+ return_dict: bool = True,
231
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
232
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
233
+ **kwargs,
234
+ ):
235
+ """
236
+ Function invoked when calling the pipeline for generation.
237
+
238
+ Args:
239
+ image_embedding (`torch.Tensor` or `List[torch.Tensor]`):
240
+ Image Embeddings either extracted from an image or generated by a Prior Model.
241
+ prompt (`str` or `List[str]`):
242
+ The prompt or prompts to guide the image generation.
243
+ num_inference_steps (`int`, *optional*, defaults to 12):
244
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
245
+ expense of slower inference.
246
+ timesteps (`List[int]`, *optional*):
247
+ Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
248
+ timesteps are used. Must be in descending order.
249
+ guidance_scale (`float`, *optional*, defaults to 0.0):
250
+ Guidance scale as defined in [Classifier-Free Diffusion
251
+ Guidance](https://huggingface.co/papers/2207.12598). `decoder_guidance_scale` is defined as `w` of
252
+ equation 2. of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by
253
+ setting `decoder_guidance_scale > 1`. Higher guidance scale encourages to generate images that are
254
+ closely linked to the text `prompt`, usually at the expense of lower image quality.
255
+ negative_prompt (`str` or `List[str]`, *optional*):
256
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
257
+ if `decoder_guidance_scale` is less than `1`).
258
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
259
+ The number of images to generate per prompt.
260
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
261
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
262
+ to make generation deterministic.
263
+ latents (`torch.Tensor`, *optional*):
264
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
265
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
266
+ tensor will be generated by sampling using the supplied random `generator`.
267
+ output_type (`str`, *optional*, defaults to `"pil"`):
268
+ The output format of the generate image. Choose between: `"pil"` (`PIL.Image.Image`), `"np"`
269
+ (`np.array`) or `"pt"` (`torch.Tensor`).
270
+ return_dict (`bool`, *optional*, defaults to `True`):
271
+ Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
272
+ callback_on_step_end (`Callable`, *optional*):
273
+ A function that calls at the end of each denoising steps during the inference. The function is called
274
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
275
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
276
+ `callback_on_step_end_tensor_inputs`.
277
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
278
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
279
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
280
+ `._callback_tensor_inputs` attribute of your pipeline class.
281
+
282
+ Examples:
283
+
284
+ Returns:
285
+ [`~pipelines.ImagePipelineOutput`] or `tuple` [`~pipelines.ImagePipelineOutput`] if `return_dict` is True,
286
+ otherwise a `tuple`. When returning a tuple, the first element is a list with the generated image
287
+ embeddings.
288
+ """
289
+
290
+ callback = kwargs.pop("callback", None)
291
+ callback_steps = kwargs.pop("callback_steps", None)
292
+
293
+ if callback is not None:
294
+ deprecate(
295
+ "callback",
296
+ "1.0.0",
297
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
298
+ )
299
+ if callback_steps is not None:
300
+ deprecate(
301
+ "callback_steps",
302
+ "1.0.0",
303
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
304
+ )
305
+
306
+ if callback_on_step_end_tensor_inputs is not None and not all(
307
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
308
+ ):
309
+ raise ValueError(
310
+ 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]}"
311
+ )
312
+
313
+ # 0. Define commonly used variables
314
+ device = self._execution_device
315
+ dtype = self.decoder.dtype
316
+ self._guidance_scale = guidance_scale
317
+
318
+ # 1. Check inputs. Raise error if not correct
319
+ if not isinstance(prompt, list):
320
+ if isinstance(prompt, str):
321
+ prompt = [prompt]
322
+ else:
323
+ raise TypeError(f"'prompt' must be of type 'list' or 'str', but got {type(prompt)}.")
324
+
325
+ if self.do_classifier_free_guidance:
326
+ if negative_prompt is not None and not isinstance(negative_prompt, list):
327
+ if isinstance(negative_prompt, str):
328
+ negative_prompt = [negative_prompt]
329
+ else:
330
+ raise TypeError(
331
+ f"'negative_prompt' must be of type 'list' or 'str', but got {type(negative_prompt)}."
332
+ )
333
+
334
+ if isinstance(image_embeddings, list):
335
+ image_embeddings = torch.cat(image_embeddings, dim=0)
336
+ if isinstance(image_embeddings, np.ndarray):
337
+ image_embeddings = torch.Tensor(image_embeddings, device=device).to(dtype=dtype)
338
+ if not isinstance(image_embeddings, torch.Tensor):
339
+ raise TypeError(
340
+ f"'image_embeddings' must be of type 'torch.Tensor' or 'np.array', but got {type(image_embeddings)}."
341
+ )
342
+
343
+ if not isinstance(num_inference_steps, int):
344
+ raise TypeError(
345
+ f"'num_inference_steps' must be of type 'int', but got {type(num_inference_steps)}\
346
+ In Case you want to provide explicit timesteps, please use the 'timesteps' argument."
347
+ )
348
+
349
+ # 2. Encode caption
350
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
351
+ prompt,
352
+ device,
353
+ image_embeddings.size(0) * num_images_per_prompt,
354
+ self.do_classifier_free_guidance,
355
+ negative_prompt,
356
+ )
357
+ text_encoder_hidden_states = (
358
+ torch.cat([prompt_embeds, negative_prompt_embeds]) if negative_prompt_embeds is not None else prompt_embeds
359
+ )
360
+ effnet = (
361
+ torch.cat([image_embeddings, torch.zeros_like(image_embeddings)])
362
+ if self.do_classifier_free_guidance
363
+ else image_embeddings
364
+ )
365
+
366
+ # 3. Determine latent shape of latents
367
+ latent_height = int(image_embeddings.size(2) * self.config.latent_dim_scale)
368
+ latent_width = int(image_embeddings.size(3) * self.config.latent_dim_scale)
369
+ latent_features_shape = (image_embeddings.size(0) * num_images_per_prompt, 4, latent_height, latent_width)
370
+
371
+ # 4. Prepare and set timesteps
372
+ if timesteps is not None:
373
+ self.scheduler.set_timesteps(timesteps=timesteps, device=device)
374
+ timesteps = self.scheduler.timesteps
375
+ num_inference_steps = len(timesteps)
376
+ else:
377
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
378
+ timesteps = self.scheduler.timesteps
379
+
380
+ # 5. Prepare latents
381
+ latents = self.prepare_latents(latent_features_shape, dtype, device, generator, latents, self.scheduler)
382
+
383
+ # 6. Run denoising loop
384
+ self._num_timesteps = len(timesteps[:-1])
385
+ for i, t in enumerate(self.progress_bar(timesteps[:-1])):
386
+ ratio = t.expand(latents.size(0)).to(dtype)
387
+ # 7. Denoise latents
388
+ predicted_latents = self.decoder(
389
+ torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents,
390
+ r=torch.cat([ratio] * 2) if self.do_classifier_free_guidance else ratio,
391
+ effnet=effnet,
392
+ clip=text_encoder_hidden_states,
393
+ )
394
+
395
+ # 8. Check for classifier free guidance and apply it
396
+ if self.do_classifier_free_guidance:
397
+ predicted_latents_text, predicted_latents_uncond = predicted_latents.chunk(2)
398
+ predicted_latents = torch.lerp(predicted_latents_uncond, predicted_latents_text, self.guidance_scale)
399
+
400
+ # 9. Renoise latents to next timestep
401
+ latents = self.scheduler.step(
402
+ model_output=predicted_latents,
403
+ timestep=ratio,
404
+ sample=latents,
405
+ generator=generator,
406
+ ).prev_sample
407
+
408
+ if callback_on_step_end is not None:
409
+ callback_kwargs = {}
410
+ for k in callback_on_step_end_tensor_inputs:
411
+ callback_kwargs[k] = locals()[k]
412
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
413
+
414
+ latents = callback_outputs.pop("latents", latents)
415
+ image_embeddings = callback_outputs.pop("image_embeddings", image_embeddings)
416
+ text_encoder_hidden_states = callback_outputs.pop(
417
+ "text_encoder_hidden_states", text_encoder_hidden_states
418
+ )
419
+
420
+ if callback is not None and i % callback_steps == 0:
421
+ step_idx = i // getattr(self.scheduler, "order", 1)
422
+ callback(step_idx, t, latents)
423
+
424
+ if XLA_AVAILABLE:
425
+ xm.mark_step()
426
+
427
+ if output_type not in ["pt", "np", "pil", "latent"]:
428
+ raise ValueError(
429
+ f"Only the output types `pt`, `np`, `pil` and `latent` are supported not output_type={output_type}"
430
+ )
431
+
432
+ if not output_type == "latent":
433
+ # 10. Scale and decode the image latents with vq-vae
434
+ latents = self.vqgan.config.scale_factor * latents
435
+ images = self.vqgan.decode(latents).sample.clamp(0, 1)
436
+ if output_type == "np":
437
+ images = images.permute(0, 2, 3, 1).cpu().float().numpy()
438
+ elif output_type == "pil":
439
+ images = images.permute(0, 2, 3, 1).cpu().float().numpy()
440
+ images = self.numpy_to_pil(images)
441
+ else:
442
+ images = latents
443
+
444
+ # Offload all models
445
+ self.maybe_free_model_hooks()
446
+
447
+ if not return_dict:
448
+ return images
449
+ return ImagePipelineOutput(images)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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 Callable, Dict, List, Optional, Union
15
+
16
+ import torch
17
+ from transformers import CLIPTextModel, CLIPTokenizer
18
+
19
+ from ...schedulers import DDPMWuerstchenScheduler
20
+ from ...utils import deprecate, replace_example_docstring
21
+ from ..pipeline_utils import DeprecatedPipelineMixin, DiffusionPipeline
22
+ from .modeling_paella_vq_model import PaellaVQModel
23
+ from .modeling_wuerstchen_diffnext import WuerstchenDiffNeXt
24
+ from .modeling_wuerstchen_prior import WuerstchenPrior
25
+ from .pipeline_wuerstchen import WuerstchenDecoderPipeline
26
+ from .pipeline_wuerstchen_prior import WuerstchenPriorPipeline
27
+
28
+
29
+ TEXT2IMAGE_EXAMPLE_DOC_STRING = """
30
+ Examples:
31
+ ```py
32
+ >>> from diffusions import WuerstchenCombinedPipeline
33
+
34
+ >>> pipe = WuerstchenCombinedPipeline.from_pretrained("warp-ai/Wuerstchen", torch_dtype=torch.float16).to(
35
+ ... "cuda"
36
+ ... )
37
+ >>> prompt = "an image of a shiba inu, donning a spacesuit and helmet"
38
+ >>> images = pipe(prompt=prompt)
39
+ ```
40
+ """
41
+
42
+
43
+ class WuerstchenCombinedPipeline(DeprecatedPipelineMixin, DiffusionPipeline):
44
+ """
45
+ Combined Pipeline for text-to-image generation using Wuerstchen
46
+
47
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
48
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
49
+
50
+ Args:
51
+ tokenizer (`CLIPTokenizer`):
52
+ The decoder tokenizer to be used for text inputs.
53
+ text_encoder (`CLIPTextModel`):
54
+ The decoder text encoder to be used for text inputs.
55
+ decoder (`WuerstchenDiffNeXt`):
56
+ The decoder model to be used for decoder image generation pipeline.
57
+ scheduler (`DDPMWuerstchenScheduler`):
58
+ The scheduler to be used for decoder image generation pipeline.
59
+ vqgan (`PaellaVQModel`):
60
+ The VQGAN model to be used for decoder image generation pipeline.
61
+ prior_tokenizer (`CLIPTokenizer`):
62
+ The prior tokenizer to be used for text inputs.
63
+ prior_text_encoder (`CLIPTextModel`):
64
+ The prior text encoder to be used for text inputs.
65
+ prior_prior (`WuerstchenPrior`):
66
+ The prior model to be used for prior pipeline.
67
+ prior_scheduler (`DDPMWuerstchenScheduler`):
68
+ The scheduler to be used for prior pipeline.
69
+ """
70
+
71
+ _last_supported_version = "0.33.1"
72
+ _load_connected_pipes = True
73
+
74
+ def __init__(
75
+ self,
76
+ tokenizer: CLIPTokenizer,
77
+ text_encoder: CLIPTextModel,
78
+ decoder: WuerstchenDiffNeXt,
79
+ scheduler: DDPMWuerstchenScheduler,
80
+ vqgan: PaellaVQModel,
81
+ prior_tokenizer: CLIPTokenizer,
82
+ prior_text_encoder: CLIPTextModel,
83
+ prior_prior: WuerstchenPrior,
84
+ prior_scheduler: DDPMWuerstchenScheduler,
85
+ ):
86
+ super().__init__()
87
+
88
+ self.register_modules(
89
+ text_encoder=text_encoder,
90
+ tokenizer=tokenizer,
91
+ decoder=decoder,
92
+ scheduler=scheduler,
93
+ vqgan=vqgan,
94
+ prior_prior=prior_prior,
95
+ prior_text_encoder=prior_text_encoder,
96
+ prior_tokenizer=prior_tokenizer,
97
+ prior_scheduler=prior_scheduler,
98
+ )
99
+ self.prior_pipe = WuerstchenPriorPipeline(
100
+ prior=prior_prior,
101
+ text_encoder=prior_text_encoder,
102
+ tokenizer=prior_tokenizer,
103
+ scheduler=prior_scheduler,
104
+ )
105
+ self.decoder_pipe = WuerstchenDecoderPipeline(
106
+ text_encoder=text_encoder,
107
+ tokenizer=tokenizer,
108
+ decoder=decoder,
109
+ scheduler=scheduler,
110
+ vqgan=vqgan,
111
+ )
112
+
113
+ def enable_xformers_memory_efficient_attention(self, attention_op: Optional[Callable] = None):
114
+ self.decoder_pipe.enable_xformers_memory_efficient_attention(attention_op)
115
+
116
+ def enable_model_cpu_offload(self, gpu_id: Optional[int] = None, device: Union[torch.device, str] = None):
117
+ r"""
118
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
119
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
120
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
121
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
122
+ """
123
+ self.prior_pipe.enable_model_cpu_offload(gpu_id=gpu_id, device=device)
124
+ self.decoder_pipe.enable_model_cpu_offload(gpu_id=gpu_id, device=device)
125
+
126
+ def enable_sequential_cpu_offload(self, gpu_id: Optional[int] = None, device: Union[torch.device, str] = None):
127
+ r"""
128
+ Offloads all models (`unet`, `text_encoder`, `vae`, and `safety checker` state dicts) to CPU using 🤗
129
+ Accelerate, significantly reducing memory usage. Models are moved to a `torch.device('meta')` and loaded on a
130
+ GPU only when their specific submodule's `forward` method is called. Offloading happens on a submodule basis.
131
+ Memory savings are higher than using `enable_model_cpu_offload`, but performance is lower.
132
+ """
133
+ self.prior_pipe.enable_sequential_cpu_offload(gpu_id=gpu_id, device=device)
134
+ self.decoder_pipe.enable_sequential_cpu_offload(gpu_id=gpu_id, device=device)
135
+
136
+ def progress_bar(self, iterable=None, total=None):
137
+ self.prior_pipe.progress_bar(iterable=iterable, total=total)
138
+ self.decoder_pipe.progress_bar(iterable=iterable, total=total)
139
+
140
+ def set_progress_bar_config(self, **kwargs):
141
+ self.prior_pipe.set_progress_bar_config(**kwargs)
142
+ self.decoder_pipe.set_progress_bar_config(**kwargs)
143
+
144
+ @torch.no_grad()
145
+ @replace_example_docstring(TEXT2IMAGE_EXAMPLE_DOC_STRING)
146
+ def __call__(
147
+ self,
148
+ prompt: Optional[Union[str, List[str]]] = None,
149
+ height: int = 512,
150
+ width: int = 512,
151
+ prior_num_inference_steps: int = 60,
152
+ prior_timesteps: Optional[List[float]] = None,
153
+ prior_guidance_scale: float = 4.0,
154
+ num_inference_steps: int = 12,
155
+ decoder_timesteps: Optional[List[float]] = None,
156
+ decoder_guidance_scale: float = 0.0,
157
+ negative_prompt: Optional[Union[str, List[str]]] = None,
158
+ prompt_embeds: Optional[torch.Tensor] = None,
159
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
160
+ num_images_per_prompt: int = 1,
161
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
162
+ latents: Optional[torch.Tensor] = None,
163
+ output_type: Optional[str] = "pil",
164
+ return_dict: bool = True,
165
+ prior_callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
166
+ prior_callback_on_step_end_tensor_inputs: List[str] = ["latents"],
167
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
168
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
169
+ **kwargs,
170
+ ):
171
+ """
172
+ Function invoked when calling the pipeline for generation.
173
+
174
+ Args:
175
+ prompt (`str` or `List[str]`):
176
+ The prompt or prompts to guide the image generation for the prior and decoder.
177
+ negative_prompt (`str` or `List[str]`, *optional*):
178
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
179
+ if `guidance_scale` is less than `1`).
180
+ prompt_embeds (`torch.Tensor`, *optional*):
181
+ Pre-generated text embeddings for the prior. Can be used to easily tweak text inputs, *e.g.* prompt
182
+ weighting. If not provided, text embeddings will be generated from `prompt` input argument.
183
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
184
+ Pre-generated negative text embeddings for the prior. Can be used to easily tweak text inputs, *e.g.*
185
+ prompt weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt`
186
+ input argument.
187
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
188
+ The number of images to generate per prompt.
189
+ height (`int`, *optional*, defaults to 512):
190
+ The height in pixels of the generated image.
191
+ width (`int`, *optional*, defaults to 512):
192
+ The width in pixels of the generated image.
193
+ prior_guidance_scale (`float`, *optional*, defaults to 4.0):
194
+ Guidance scale as defined in [Classifier-Free Diffusion
195
+ Guidance](https://huggingface.co/papers/2207.12598). `prior_guidance_scale` is defined as `w` of
196
+ equation 2. of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by
197
+ setting `prior_guidance_scale > 1`. Higher guidance scale encourages to generate images that are
198
+ closely linked to the text `prompt`, usually at the expense of lower image quality.
199
+ prior_num_inference_steps (`Union[int, Dict[float, int]]`, *optional*, defaults to 60):
200
+ The number of prior denoising steps. More denoising steps usually lead to a higher quality image at the
201
+ expense of slower inference. For more specific timestep spacing, you can pass customized
202
+ `prior_timesteps`
203
+ num_inference_steps (`int`, *optional*, defaults to 12):
204
+ The number of decoder denoising steps. More denoising steps usually lead to a higher quality image at
205
+ the expense of slower inference. For more specific timestep spacing, you can pass customized
206
+ `timesteps`
207
+ prior_timesteps (`List[float]`, *optional*):
208
+ Custom timesteps to use for the denoising process for the prior. If not defined, equal spaced
209
+ `prior_num_inference_steps` timesteps are used. Must be in descending order.
210
+ decoder_timesteps (`List[float]`, *optional*):
211
+ Custom timesteps to use for the denoising process for the decoder. If not defined, equal spaced
212
+ `num_inference_steps` timesteps are used. Must be in descending order.
213
+ decoder_guidance_scale (`float`, *optional*, defaults to 0.0):
214
+ Guidance scale as defined in [Classifier-Free Diffusion
215
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
216
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
217
+ `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
218
+ the text `prompt`, usually at the expense of lower image quality.
219
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
220
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
221
+ to make generation deterministic.
222
+ latents (`torch.Tensor`, *optional*):
223
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
224
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
225
+ tensor will be generated by sampling using the supplied random `generator`.
226
+ output_type (`str`, *optional*, defaults to `"pil"`):
227
+ The output format of the generate image. Choose between: `"pil"` (`PIL.Image.Image`), `"np"`
228
+ (`np.array`) or `"pt"` (`torch.Tensor`).
229
+ return_dict (`bool`, *optional*, defaults to `True`):
230
+ Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
231
+ prior_callback_on_step_end (`Callable`, *optional*):
232
+ A function that calls at the end of each denoising steps during the inference. The function is called
233
+ with the following arguments: `prior_callback_on_step_end(self: DiffusionPipeline, step: int, timestep:
234
+ int, callback_kwargs: Dict)`.
235
+ prior_callback_on_step_end_tensor_inputs (`List`, *optional*):
236
+ The list of tensor inputs for the `prior_callback_on_step_end` function. The tensors specified in the
237
+ list will be passed as `callback_kwargs` argument. You will only be able to include variables listed in
238
+ the `._callback_tensor_inputs` attribute of your pipeline class.
239
+ callback_on_step_end (`Callable`, *optional*):
240
+ A function that calls at the end of each denoising steps during the inference. The function is called
241
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
242
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
243
+ `callback_on_step_end_tensor_inputs`.
244
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
245
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
246
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
247
+ `._callback_tensor_inputs` attribute of your pipeline class.
248
+
249
+ Examples:
250
+
251
+ Returns:
252
+ [`~pipelines.ImagePipelineOutput`] or `tuple` [`~pipelines.ImagePipelineOutput`] if `return_dict` is True,
253
+ otherwise a `tuple`. When returning a tuple, the first element is a list with the generated images.
254
+ """
255
+ prior_kwargs = {}
256
+ if kwargs.get("prior_callback", None) is not None:
257
+ prior_kwargs["callback"] = kwargs.pop("prior_callback")
258
+ deprecate(
259
+ "prior_callback",
260
+ "1.0.0",
261
+ "Passing `prior_callback` as an input argument to `__call__` is deprecated, consider use `prior_callback_on_step_end`",
262
+ )
263
+ if kwargs.get("prior_callback_steps", None) is not None:
264
+ deprecate(
265
+ "prior_callback_steps",
266
+ "1.0.0",
267
+ "Passing `prior_callback_steps` as an input argument to `__call__` is deprecated, consider use `prior_callback_on_step_end`",
268
+ )
269
+ prior_kwargs["callback_steps"] = kwargs.pop("prior_callback_steps")
270
+
271
+ prior_outputs = self.prior_pipe(
272
+ prompt=prompt if prompt_embeds is None else None,
273
+ height=height,
274
+ width=width,
275
+ num_inference_steps=prior_num_inference_steps,
276
+ timesteps=prior_timesteps,
277
+ guidance_scale=prior_guidance_scale,
278
+ negative_prompt=negative_prompt if negative_prompt_embeds is None else None,
279
+ prompt_embeds=prompt_embeds,
280
+ negative_prompt_embeds=negative_prompt_embeds,
281
+ num_images_per_prompt=num_images_per_prompt,
282
+ generator=generator,
283
+ latents=latents,
284
+ output_type="pt",
285
+ return_dict=False,
286
+ callback_on_step_end=prior_callback_on_step_end,
287
+ callback_on_step_end_tensor_inputs=prior_callback_on_step_end_tensor_inputs,
288
+ **prior_kwargs,
289
+ )
290
+ image_embeddings = prior_outputs[0]
291
+
292
+ outputs = self.decoder_pipe(
293
+ image_embeddings=image_embeddings,
294
+ prompt=prompt if prompt is not None else "",
295
+ num_inference_steps=num_inference_steps,
296
+ timesteps=decoder_timesteps,
297
+ guidance_scale=decoder_guidance_scale,
298
+ negative_prompt=negative_prompt,
299
+ generator=generator,
300
+ output_type=output_type,
301
+ return_dict=return_dict,
302
+ callback_on_step_end=callback_on_step_end,
303
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
304
+ **kwargs,
305
+ )
306
+
307
+ return outputs
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+ from dataclasses import dataclass
16
+ from math import ceil
17
+ from typing import Callable, Dict, List, Optional, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+ from transformers import CLIPTextModel, CLIPTokenizer
22
+
23
+ from ...loaders import StableDiffusionLoraLoaderMixin
24
+ from ...schedulers import DDPMWuerstchenScheduler
25
+ from ...utils import BaseOutput, deprecate, is_torch_xla_available, logging, replace_example_docstring
26
+ from ...utils.torch_utils import randn_tensor
27
+ from ..pipeline_utils import DiffusionPipeline
28
+ from .modeling_wuerstchen_prior import WuerstchenPrior
29
+
30
+
31
+ if is_torch_xla_available():
32
+ import torch_xla.core.xla_model as xm
33
+
34
+ XLA_AVAILABLE = True
35
+ else:
36
+ XLA_AVAILABLE = False
37
+
38
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
39
+
40
+
41
+ DEFAULT_STAGE_C_TIMESTEPS = list(np.linspace(1.0, 2 / 3, 20)) + list(np.linspace(2 / 3, 0.0, 11))[1:]
42
+
43
+ EXAMPLE_DOC_STRING = """
44
+ Examples:
45
+ ```py
46
+ >>> import torch
47
+ >>> from diffusers import WuerstchenPriorPipeline
48
+
49
+ >>> prior_pipe = WuerstchenPriorPipeline.from_pretrained(
50
+ ... "warp-ai/wuerstchen-prior", torch_dtype=torch.float16
51
+ ... ).to("cuda")
52
+
53
+ >>> prompt = "an image of a shiba inu, donning a spacesuit and helmet"
54
+ >>> prior_output = pipe(prompt)
55
+ ```
56
+ """
57
+
58
+
59
+ @dataclass
60
+ class WuerstchenPriorPipelineOutput(BaseOutput):
61
+ """
62
+ Output class for WuerstchenPriorPipeline.
63
+
64
+ Args:
65
+ image_embeddings (`torch.Tensor` or `np.ndarray`)
66
+ Prior image embeddings for text prompt
67
+
68
+ """
69
+
70
+ image_embeddings: Union[torch.Tensor, np.ndarray]
71
+
72
+
73
+ class WuerstchenPriorPipeline(DiffusionPipeline, StableDiffusionLoraLoaderMixin):
74
+ """
75
+ Pipeline for generating image prior for Wuerstchen.
76
+
77
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
78
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
79
+
80
+ The pipeline also inherits the following loading methods:
81
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
82
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
83
+
84
+ Args:
85
+ prior ([`Prior`]):
86
+ The canonical unCLIP prior to approximate the image embedding from the text embedding.
87
+ text_encoder ([`CLIPTextModelWithProjection`]):
88
+ Frozen text-encoder.
89
+ tokenizer (`CLIPTokenizer`):
90
+ Tokenizer of class
91
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
92
+ scheduler ([`DDPMWuerstchenScheduler`]):
93
+ A scheduler to be used in combination with `prior` to generate image embedding.
94
+ latent_mean ('float', *optional*, defaults to 42.0):
95
+ Mean value for latent diffusers.
96
+ latent_std ('float', *optional*, defaults to 1.0):
97
+ Standard value for latent diffusers.
98
+ resolution_multiple ('float', *optional*, defaults to 42.67):
99
+ Default resolution for multiple images generated.
100
+ """
101
+
102
+ unet_name = "prior"
103
+ text_encoder_name = "text_encoder"
104
+ model_cpu_offload_seq = "text_encoder->prior"
105
+ _callback_tensor_inputs = ["latents", "text_encoder_hidden_states", "negative_prompt_embeds"]
106
+ _lora_loadable_modules = ["prior", "text_encoder"]
107
+
108
+ def __init__(
109
+ self,
110
+ tokenizer: CLIPTokenizer,
111
+ text_encoder: CLIPTextModel,
112
+ prior: WuerstchenPrior,
113
+ scheduler: DDPMWuerstchenScheduler,
114
+ latent_mean: float = 42.0,
115
+ latent_std: float = 1.0,
116
+ resolution_multiple: float = 42.67,
117
+ ) -> None:
118
+ super().__init__()
119
+ self.register_modules(
120
+ tokenizer=tokenizer,
121
+ text_encoder=text_encoder,
122
+ prior=prior,
123
+ scheduler=scheduler,
124
+ )
125
+ self.register_to_config(
126
+ latent_mean=latent_mean, latent_std=latent_std, resolution_multiple=resolution_multiple
127
+ )
128
+
129
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip.UnCLIPPipeline.prepare_latents
130
+ def prepare_latents(self, shape, dtype, device, generator, latents, scheduler):
131
+ if latents is None:
132
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
133
+ else:
134
+ if latents.shape != shape:
135
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
136
+ latents = latents.to(device)
137
+
138
+ latents = latents * scheduler.init_noise_sigma
139
+ return latents
140
+
141
+ def encode_prompt(
142
+ self,
143
+ device,
144
+ num_images_per_prompt,
145
+ do_classifier_free_guidance,
146
+ prompt=None,
147
+ negative_prompt=None,
148
+ prompt_embeds: Optional[torch.Tensor] = None,
149
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
150
+ ):
151
+ if prompt is not None and isinstance(prompt, str):
152
+ batch_size = 1
153
+ elif prompt is not None and isinstance(prompt, list):
154
+ batch_size = len(prompt)
155
+ else:
156
+ batch_size = prompt_embeds.shape[0]
157
+
158
+ if prompt_embeds is None:
159
+ # get prompt text embeddings
160
+ text_inputs = self.tokenizer(
161
+ prompt,
162
+ padding="max_length",
163
+ max_length=self.tokenizer.model_max_length,
164
+ truncation=True,
165
+ return_tensors="pt",
166
+ )
167
+ text_input_ids = text_inputs.input_ids
168
+ attention_mask = text_inputs.attention_mask
169
+
170
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
171
+
172
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
173
+ text_input_ids, untruncated_ids
174
+ ):
175
+ removed_text = self.tokenizer.batch_decode(
176
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
177
+ )
178
+ logger.warning(
179
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
180
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
181
+ )
182
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
183
+ attention_mask = attention_mask[:, : self.tokenizer.model_max_length]
184
+
185
+ text_encoder_output = self.text_encoder(
186
+ text_input_ids.to(device), attention_mask=attention_mask.to(device)
187
+ )
188
+ prompt_embeds = text_encoder_output.last_hidden_state
189
+
190
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
191
+ prompt_embeds = prompt_embeds.repeat_interleave(num_images_per_prompt, dim=0)
192
+
193
+ if negative_prompt_embeds is None and do_classifier_free_guidance:
194
+ uncond_tokens: List[str]
195
+ if negative_prompt is None:
196
+ uncond_tokens = [""] * batch_size
197
+ elif type(prompt) is not type(negative_prompt):
198
+ raise TypeError(
199
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
200
+ f" {type(prompt)}."
201
+ )
202
+ elif isinstance(negative_prompt, str):
203
+ uncond_tokens = [negative_prompt]
204
+ elif batch_size != len(negative_prompt):
205
+ raise ValueError(
206
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
207
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
208
+ " the batch size of `prompt`."
209
+ )
210
+ else:
211
+ uncond_tokens = negative_prompt
212
+
213
+ uncond_input = self.tokenizer(
214
+ uncond_tokens,
215
+ padding="max_length",
216
+ max_length=self.tokenizer.model_max_length,
217
+ truncation=True,
218
+ return_tensors="pt",
219
+ )
220
+ negative_prompt_embeds_text_encoder_output = self.text_encoder(
221
+ uncond_input.input_ids.to(device), attention_mask=uncond_input.attention_mask.to(device)
222
+ )
223
+
224
+ negative_prompt_embeds = negative_prompt_embeds_text_encoder_output.last_hidden_state
225
+
226
+ if do_classifier_free_guidance:
227
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
228
+ seq_len = negative_prompt_embeds.shape[1]
229
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
230
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
231
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
232
+ # done duplicates
233
+
234
+ return prompt_embeds, negative_prompt_embeds
235
+
236
+ def check_inputs(
237
+ self,
238
+ prompt,
239
+ negative_prompt,
240
+ num_inference_steps,
241
+ do_classifier_free_guidance,
242
+ prompt_embeds=None,
243
+ negative_prompt_embeds=None,
244
+ ):
245
+ if prompt is not None and prompt_embeds is not None:
246
+ raise ValueError(
247
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
248
+ " only forward one of the two."
249
+ )
250
+ elif prompt is None and prompt_embeds is None:
251
+ raise ValueError(
252
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
253
+ )
254
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
255
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
256
+
257
+ if negative_prompt is not None and negative_prompt_embeds is not None:
258
+ raise ValueError(
259
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
260
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
261
+ )
262
+
263
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
264
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
265
+ raise ValueError(
266
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
267
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
268
+ f" {negative_prompt_embeds.shape}."
269
+ )
270
+
271
+ if not isinstance(num_inference_steps, int):
272
+ raise TypeError(
273
+ f"'num_inference_steps' must be of type 'int', but got {type(num_inference_steps)}\
274
+ In Case you want to provide explicit timesteps, please use the 'timesteps' argument."
275
+ )
276
+
277
+ @property
278
+ def guidance_scale(self):
279
+ return self._guidance_scale
280
+
281
+ @property
282
+ def do_classifier_free_guidance(self):
283
+ return self._guidance_scale > 1
284
+
285
+ @property
286
+ def num_timesteps(self):
287
+ return self._num_timesteps
288
+
289
+ @torch.no_grad()
290
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
291
+ def __call__(
292
+ self,
293
+ prompt: Optional[Union[str, List[str]]] = None,
294
+ height: int = 1024,
295
+ width: int = 1024,
296
+ num_inference_steps: int = 60,
297
+ timesteps: List[float] = None,
298
+ guidance_scale: float = 8.0,
299
+ negative_prompt: Optional[Union[str, List[str]]] = None,
300
+ prompt_embeds: Optional[torch.Tensor] = None,
301
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
302
+ num_images_per_prompt: Optional[int] = 1,
303
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
304
+ latents: Optional[torch.Tensor] = None,
305
+ output_type: Optional[str] = "pt",
306
+ return_dict: bool = True,
307
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
308
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
309
+ **kwargs,
310
+ ):
311
+ """
312
+ Function invoked when calling the pipeline for generation.
313
+
314
+ Args:
315
+ prompt (`str` or `List[str]`):
316
+ The prompt or prompts to guide the image generation.
317
+ height (`int`, *optional*, defaults to 1024):
318
+ The height in pixels of the generated image.
319
+ width (`int`, *optional*, defaults to 1024):
320
+ The width in pixels of the generated image.
321
+ num_inference_steps (`int`, *optional*, defaults to 60):
322
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
323
+ expense of slower inference.
324
+ timesteps (`List[int]`, *optional*):
325
+ Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
326
+ timesteps are used. Must be in descending order.
327
+ guidance_scale (`float`, *optional*, defaults to 8.0):
328
+ Guidance scale as defined in [Classifier-Free Diffusion
329
+ Guidance](https://huggingface.co/papers/2207.12598). `decoder_guidance_scale` is defined as `w` of
330
+ equation 2. of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by
331
+ setting `decoder_guidance_scale > 1`. Higher guidance scale encourages to generate images that are
332
+ closely linked to the text `prompt`, usually at the expense of lower image quality.
333
+ negative_prompt (`str` or `List[str]`, *optional*):
334
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
335
+ if `decoder_guidance_scale` is less than `1`).
336
+ prompt_embeds (`torch.Tensor`, *optional*):
337
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
338
+ provided, text embeddings will be generated from `prompt` input argument.
339
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
340
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
341
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
342
+ argument.
343
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
344
+ The number of images to generate per prompt.
345
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
346
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
347
+ to make generation deterministic.
348
+ latents (`torch.Tensor`, *optional*):
349
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
350
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
351
+ tensor will be generated by sampling using the supplied random `generator`.
352
+ output_type (`str`, *optional*, defaults to `"pil"`):
353
+ The output format of the generate image. Choose between: `"pil"` (`PIL.Image.Image`), `"np"`
354
+ (`np.array`) or `"pt"` (`torch.Tensor`).
355
+ return_dict (`bool`, *optional*, defaults to `True`):
356
+ Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
357
+ callback_on_step_end (`Callable`, *optional*):
358
+ A function that calls at the end of each denoising steps during the inference. The function is called
359
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
360
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
361
+ `callback_on_step_end_tensor_inputs`.
362
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
363
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
364
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
365
+ `._callback_tensor_inputs` attribute of your pipeline class.
366
+
367
+ Examples:
368
+
369
+ Returns:
370
+ [`~pipelines.WuerstchenPriorPipelineOutput`] or `tuple` [`~pipelines.WuerstchenPriorPipelineOutput`] if
371
+ `return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the
372
+ generated image embeddings.
373
+ """
374
+
375
+ callback = kwargs.pop("callback", None)
376
+ callback_steps = kwargs.pop("callback_steps", None)
377
+
378
+ if callback is not None:
379
+ deprecate(
380
+ "callback",
381
+ "1.0.0",
382
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
383
+ )
384
+ if callback_steps is not None:
385
+ deprecate(
386
+ "callback_steps",
387
+ "1.0.0",
388
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
389
+ )
390
+
391
+ if callback_on_step_end_tensor_inputs is not None and not all(
392
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
393
+ ):
394
+ raise ValueError(
395
+ 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]}"
396
+ )
397
+
398
+ # 0. Define commonly used variables
399
+ device = self._execution_device
400
+ self._guidance_scale = guidance_scale
401
+ if prompt is not None and isinstance(prompt, str):
402
+ batch_size = 1
403
+ elif prompt is not None and isinstance(prompt, list):
404
+ batch_size = len(prompt)
405
+ else:
406
+ batch_size = prompt_embeds.shape[0]
407
+
408
+ # 1. Check inputs. Raise error if not correct
409
+ if prompt is not None and not isinstance(prompt, list):
410
+ if isinstance(prompt, str):
411
+ prompt = [prompt]
412
+ else:
413
+ raise TypeError(f"'prompt' must be of type 'list' or 'str', but got {type(prompt)}.")
414
+
415
+ if self.do_classifier_free_guidance:
416
+ if negative_prompt is not None and not isinstance(negative_prompt, list):
417
+ if isinstance(negative_prompt, str):
418
+ negative_prompt = [negative_prompt]
419
+ else:
420
+ raise TypeError(
421
+ f"'negative_prompt' must be of type 'list' or 'str', but got {type(negative_prompt)}."
422
+ )
423
+
424
+ self.check_inputs(
425
+ prompt,
426
+ negative_prompt,
427
+ num_inference_steps,
428
+ self.do_classifier_free_guidance,
429
+ prompt_embeds=prompt_embeds,
430
+ negative_prompt_embeds=negative_prompt_embeds,
431
+ )
432
+
433
+ # 2. Encode caption
434
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
435
+ prompt=prompt,
436
+ device=device,
437
+ num_images_per_prompt=num_images_per_prompt,
438
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
439
+ negative_prompt=negative_prompt,
440
+ prompt_embeds=prompt_embeds,
441
+ negative_prompt_embeds=negative_prompt_embeds,
442
+ )
443
+
444
+ # For classifier free guidance, we need to do two forward passes.
445
+ # Here we concatenate the unconditional and text embeddings into a single batch
446
+ # to avoid doing two forward passes
447
+ text_encoder_hidden_states = (
448
+ torch.cat([prompt_embeds, negative_prompt_embeds]) if negative_prompt_embeds is not None else prompt_embeds
449
+ )
450
+
451
+ # 3. Determine latent shape of image embeddings
452
+ dtype = text_encoder_hidden_states.dtype
453
+ latent_height = ceil(height / self.config.resolution_multiple)
454
+ latent_width = ceil(width / self.config.resolution_multiple)
455
+ num_channels = self.prior.config.c_in
456
+ effnet_features_shape = (num_images_per_prompt * batch_size, num_channels, latent_height, latent_width)
457
+
458
+ # 4. Prepare and set timesteps
459
+ if timesteps is not None:
460
+ self.scheduler.set_timesteps(timesteps=timesteps, device=device)
461
+ timesteps = self.scheduler.timesteps
462
+ num_inference_steps = len(timesteps)
463
+ else:
464
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
465
+ timesteps = self.scheduler.timesteps
466
+
467
+ # 5. Prepare latents
468
+ latents = self.prepare_latents(effnet_features_shape, dtype, device, generator, latents, self.scheduler)
469
+
470
+ # 6. Run denoising loop
471
+ self._num_timesteps = len(timesteps[:-1])
472
+ for i, t in enumerate(self.progress_bar(timesteps[:-1])):
473
+ ratio = t.expand(latents.size(0)).to(dtype)
474
+
475
+ # 7. Denoise image embeddings
476
+ predicted_image_embedding = self.prior(
477
+ torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents,
478
+ r=torch.cat([ratio] * 2) if self.do_classifier_free_guidance else ratio,
479
+ c=text_encoder_hidden_states,
480
+ )
481
+
482
+ # 8. Check for classifier free guidance and apply it
483
+ if self.do_classifier_free_guidance:
484
+ predicted_image_embedding_text, predicted_image_embedding_uncond = predicted_image_embedding.chunk(2)
485
+ predicted_image_embedding = torch.lerp(
486
+ predicted_image_embedding_uncond, predicted_image_embedding_text, self.guidance_scale
487
+ )
488
+
489
+ # 9. Renoise latents to next timestep
490
+ latents = self.scheduler.step(
491
+ model_output=predicted_image_embedding,
492
+ timestep=ratio,
493
+ sample=latents,
494
+ generator=generator,
495
+ ).prev_sample
496
+
497
+ if callback_on_step_end is not None:
498
+ callback_kwargs = {}
499
+ for k in callback_on_step_end_tensor_inputs:
500
+ callback_kwargs[k] = locals()[k]
501
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
502
+
503
+ latents = callback_outputs.pop("latents", latents)
504
+ text_encoder_hidden_states = callback_outputs.pop(
505
+ "text_encoder_hidden_states", text_encoder_hidden_states
506
+ )
507
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
508
+
509
+ if callback is not None and i % callback_steps == 0:
510
+ step_idx = i // getattr(self.scheduler, "order", 1)
511
+ callback(step_idx, t, latents)
512
+
513
+ if XLA_AVAILABLE:
514
+ xm.mark_step()
515
+
516
+ # 10. Denormalize the latents
517
+ latents = latents * self.config.latent_mean - self.config.latent_std
518
+
519
+ # Offload all models
520
+ self.maybe_free_model_hooks()
521
+
522
+ if output_type == "np":
523
+ latents = latents.cpu().float().numpy()
524
+
525
+ if not return_dict:
526
+ return (latents,)
527
+
528
+ return WuerstchenPriorPipelineOutput(latents)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/py.typed ADDED
File without changes
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from .auto import DiffusersAutoQuantizer
17
+ from .base import DiffusersQuantizer
18
+ from .pipe_quant_config import PipelineQuantizationConfig
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/auto.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. 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
+ Adapted from
16
+ https://github.com/huggingface/transformers/blob/c409cd81777fb27aadc043ed3d8339dbc020fb3b/src/transformers/quantizers/auto.py
17
+ """
18
+
19
+ import warnings
20
+ from typing import Dict, Optional, Union
21
+
22
+ from .bitsandbytes import BnB4BitDiffusersQuantizer, BnB8BitDiffusersQuantizer
23
+ from .gguf import GGUFQuantizer
24
+ from .modelopt import NVIDIAModelOptQuantizer
25
+ from .quantization_config import (
26
+ BitsAndBytesConfig,
27
+ GGUFQuantizationConfig,
28
+ NVIDIAModelOptConfig,
29
+ QuantizationConfigMixin,
30
+ QuantizationMethod,
31
+ QuantoConfig,
32
+ TorchAoConfig,
33
+ )
34
+ from .quanto import QuantoQuantizer
35
+ from .torchao import TorchAoHfQuantizer
36
+
37
+
38
+ AUTO_QUANTIZER_MAPPING = {
39
+ "bitsandbytes_4bit": BnB4BitDiffusersQuantizer,
40
+ "bitsandbytes_8bit": BnB8BitDiffusersQuantizer,
41
+ "gguf": GGUFQuantizer,
42
+ "quanto": QuantoQuantizer,
43
+ "torchao": TorchAoHfQuantizer,
44
+ "modelopt": NVIDIAModelOptQuantizer,
45
+ }
46
+
47
+ AUTO_QUANTIZATION_CONFIG_MAPPING = {
48
+ "bitsandbytes_4bit": BitsAndBytesConfig,
49
+ "bitsandbytes_8bit": BitsAndBytesConfig,
50
+ "gguf": GGUFQuantizationConfig,
51
+ "quanto": QuantoConfig,
52
+ "torchao": TorchAoConfig,
53
+ "modelopt": NVIDIAModelOptConfig,
54
+ }
55
+
56
+
57
+ class DiffusersAutoQuantizer:
58
+ """
59
+ The auto diffusers quantizer class that takes care of automatically instantiating to the correct
60
+ `DiffusersQuantizer` given the `QuantizationConfig`.
61
+ """
62
+
63
+ @classmethod
64
+ def from_dict(cls, quantization_config_dict: Dict):
65
+ quant_method = quantization_config_dict.get("quant_method", None)
66
+ # We need a special care for bnb models to make sure everything is BC ..
67
+ if quantization_config_dict.get("load_in_8bit", False) or quantization_config_dict.get("load_in_4bit", False):
68
+ suffix = "_4bit" if quantization_config_dict.get("load_in_4bit", False) else "_8bit"
69
+ quant_method = QuantizationMethod.BITS_AND_BYTES + suffix
70
+ elif quant_method is None:
71
+ raise ValueError(
72
+ "The model's quantization config from the arguments has no `quant_method` attribute. Make sure that the model has been correctly quantized"
73
+ )
74
+
75
+ if quant_method not in AUTO_QUANTIZATION_CONFIG_MAPPING.keys():
76
+ raise ValueError(
77
+ f"Unknown quantization type, got {quant_method} - supported types are:"
78
+ f" {list(AUTO_QUANTIZER_MAPPING.keys())}"
79
+ )
80
+
81
+ target_cls = AUTO_QUANTIZATION_CONFIG_MAPPING[quant_method]
82
+ return target_cls.from_dict(quantization_config_dict)
83
+
84
+ @classmethod
85
+ def from_config(cls, quantization_config: Union[QuantizationConfigMixin, Dict], **kwargs):
86
+ # Convert it to a QuantizationConfig if the q_config is a dict
87
+ if isinstance(quantization_config, dict):
88
+ quantization_config = cls.from_dict(quantization_config)
89
+
90
+ quant_method = quantization_config.quant_method
91
+
92
+ # Again, we need a special care for bnb as we have a single quantization config
93
+ # class for both 4-bit and 8-bit quantization
94
+ if quant_method == QuantizationMethod.BITS_AND_BYTES:
95
+ if quantization_config.load_in_8bit:
96
+ quant_method += "_8bit"
97
+ else:
98
+ quant_method += "_4bit"
99
+
100
+ if quant_method not in AUTO_QUANTIZER_MAPPING.keys():
101
+ raise ValueError(
102
+ f"Unknown quantization type, got {quant_method} - supported types are:"
103
+ f" {list(AUTO_QUANTIZER_MAPPING.keys())}"
104
+ )
105
+
106
+ target_cls = AUTO_QUANTIZER_MAPPING[quant_method]
107
+ return target_cls(quantization_config, **kwargs)
108
+
109
+ @classmethod
110
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
111
+ model_config = cls.load_config(pretrained_model_name_or_path, **kwargs)
112
+ if getattr(model_config, "quantization_config", None) is None:
113
+ raise ValueError(
114
+ f"Did not found a `quantization_config` in {pretrained_model_name_or_path}. Make sure that the model is correctly quantized."
115
+ )
116
+ quantization_config_dict = model_config.quantization_config
117
+ quantization_config = cls.from_dict(quantization_config_dict)
118
+ # Update with potential kwargs that are passed through from_pretrained.
119
+ quantization_config.update(kwargs)
120
+
121
+ return cls.from_config(quantization_config)
122
+
123
+ @classmethod
124
+ def merge_quantization_configs(
125
+ cls,
126
+ quantization_config: Union[dict, QuantizationConfigMixin],
127
+ quantization_config_from_args: Optional[QuantizationConfigMixin],
128
+ ):
129
+ """
130
+ handles situations where both quantization_config from args and quantization_config from model config are
131
+ present.
132
+ """
133
+ if quantization_config_from_args is not None:
134
+ warning_msg = (
135
+ "You passed `quantization_config` or equivalent parameters to `from_pretrained` but the model you're loading"
136
+ " already has a `quantization_config` attribute. The `quantization_config` from the model will be used."
137
+ )
138
+ else:
139
+ warning_msg = ""
140
+
141
+ if isinstance(quantization_config, dict):
142
+ quantization_config = cls.from_dict(quantization_config)
143
+
144
+ if isinstance(quantization_config, NVIDIAModelOptConfig):
145
+ quantization_config.check_model_patching()
146
+
147
+ if warning_msg != "":
148
+ warnings.warn(warning_msg)
149
+
150
+ return quantization_config
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/base.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Adapted from
17
+ https://github.com/huggingface/transformers/blob/52cb4034ada381fe1ffe8d428a1076e5411a8026/src/transformers/quantizers/base.py
18
+ """
19
+
20
+ from abc import ABC, abstractmethod
21
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
22
+
23
+ from ..utils import is_torch_available
24
+ from .quantization_config import QuantizationConfigMixin
25
+
26
+
27
+ if TYPE_CHECKING:
28
+ from ..models.modeling_utils import ModelMixin
29
+
30
+ if is_torch_available():
31
+ import torch
32
+
33
+
34
+ class DiffusersQuantizer(ABC):
35
+ """
36
+ Abstract class of the HuggingFace quantizer. Supports for now quantizing HF diffusers models for inference and/or
37
+ quantization. This class is used only for diffusers.models.modeling_utils.ModelMixin.from_pretrained and cannot be
38
+ easily used outside the scope of that method yet.
39
+
40
+ Attributes
41
+ quantization_config (`diffusers.quantizers.quantization_config.QuantizationConfigMixin`):
42
+ The quantization config that defines the quantization parameters of your model that you want to quantize.
43
+ modules_to_not_convert (`List[str]`, *optional*):
44
+ The list of module names to not convert when quantizing the model.
45
+ required_packages (`List[str]`, *optional*):
46
+ The list of required pip packages to install prior to using the quantizer
47
+ requires_calibration (`bool`):
48
+ Whether the quantization method requires to calibrate the model before using it.
49
+ """
50
+
51
+ requires_calibration = False
52
+ required_packages = None
53
+
54
+ def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
55
+ self.quantization_config = quantization_config
56
+
57
+ # -- Handle extra kwargs below --
58
+ self.modules_to_not_convert = kwargs.pop("modules_to_not_convert", [])
59
+ self.pre_quantized = kwargs.pop("pre_quantized", True)
60
+
61
+ if not self.pre_quantized and self.requires_calibration:
62
+ raise ValueError(
63
+ f"The quantization method {quantization_config.quant_method} does require the model to be pre-quantized."
64
+ f" You explicitly passed `pre_quantized=False` meaning your model weights are not quantized. Make sure to "
65
+ f"pass `pre_quantized=True` while knowing what you are doing."
66
+ )
67
+
68
+ def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
69
+ """
70
+ Some quantization methods require to explicitly set the dtype of the model to a target dtype. You need to
71
+ override this method in case you want to make sure that behavior is preserved
72
+
73
+ Args:
74
+ torch_dtype (`torch.dtype`):
75
+ The input dtype that is passed in `from_pretrained`
76
+ """
77
+ return torch_dtype
78
+
79
+ def update_device_map(self, device_map: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
80
+ """
81
+ Override this method if you want to pass a override the existing device map with a new one. E.g. for
82
+ bitsandbytes, since `accelerate` is a hard requirement, if no device_map is passed, the device_map is set to
83
+ `"auto"``
84
+
85
+ Args:
86
+ device_map (`Union[dict, str]`, *optional*):
87
+ The device_map that is passed through the `from_pretrained` method.
88
+ """
89
+ return device_map
90
+
91
+ def adjust_target_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
92
+ """
93
+ Override this method if you want to adjust the `target_dtype` variable used in `from_pretrained` to compute the
94
+ device_map in case the device_map is a `str`. E.g. for bitsandbytes we force-set `target_dtype` to `torch.int8`
95
+ and for 4-bit we pass a custom enum `accelerate.CustomDtype.int4`.
96
+
97
+ Args:
98
+ torch_dtype (`torch.dtype`, *optional*):
99
+ The torch_dtype that is used to compute the device_map.
100
+ """
101
+ return torch_dtype
102
+
103
+ def update_missing_keys(self, model, missing_keys: List[str], prefix: str) -> List[str]:
104
+ """
105
+ Override this method if you want to adjust the `missing_keys`.
106
+
107
+ Args:
108
+ missing_keys (`List[str]`, *optional*):
109
+ The list of missing keys in the checkpoint compared to the state dict of the model
110
+ """
111
+ return missing_keys
112
+
113
+ def get_special_dtypes_update(self, model, torch_dtype: "torch.dtype") -> Dict[str, "torch.dtype"]:
114
+ """
115
+ returns dtypes for modules that are not quantized - used for the computation of the device_map in case one
116
+ passes a str as a device_map. The method will use the `modules_to_not_convert` that is modified in
117
+ `_process_model_before_weight_loading`. `diffusers` models don't have any `modules_to_not_convert` attributes
118
+ yet but this can change soon in the future.
119
+
120
+ Args:
121
+ model (`~diffusers.models.modeling_utils.ModelMixin`):
122
+ The model to quantize
123
+ torch_dtype (`torch.dtype`):
124
+ The dtype passed in `from_pretrained` method.
125
+ """
126
+
127
+ return {
128
+ name: torch_dtype
129
+ for name, _ in model.named_parameters()
130
+ if any(m in name for m in self.modules_to_not_convert)
131
+ }
132
+
133
+ def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]:
134
+ """adjust max_memory argument for infer_auto_device_map() if extra memory is needed for quantization"""
135
+ return max_memory
136
+
137
+ def check_if_quantized_param(
138
+ self,
139
+ model: "ModelMixin",
140
+ param_value: "torch.Tensor",
141
+ param_name: str,
142
+ state_dict: Dict[str, Any],
143
+ **kwargs,
144
+ ) -> bool:
145
+ """
146
+ checks if a loaded state_dict component is part of quantized param + some validation; only defined for
147
+ quantization methods that require to create a new parameters for quantization.
148
+ """
149
+ return False
150
+
151
+ def create_quantized_param(self, *args, **kwargs) -> "torch.nn.Parameter":
152
+ """
153
+ takes needed components from state_dict and creates quantized param.
154
+ """
155
+ return
156
+
157
+ def check_quantized_param_shape(self, *args, **kwargs):
158
+ """
159
+ checks if the quantized param has expected shape.
160
+ """
161
+ return True
162
+
163
+ def validate_environment(self, *args, **kwargs):
164
+ """
165
+ This method is used to potentially check for potential conflicts with arguments that are passed in
166
+ `from_pretrained`. You need to define it for all future quantizers that are integrated with diffusers. If no
167
+ explicit check are needed, simply return nothing.
168
+ """
169
+ return
170
+
171
+ def preprocess_model(self, model: "ModelMixin", **kwargs):
172
+ """
173
+ Setting model attributes and/or converting model before weights loading. At this point the model should be
174
+ initialized on the meta device so you can freely manipulate the skeleton of the model in order to replace
175
+ modules in-place. Make sure to override the abstract method `_process_model_before_weight_loading`.
176
+
177
+ Args:
178
+ model (`~diffusers.models.modeling_utils.ModelMixin`):
179
+ The model to quantize
180
+ kwargs (`dict`, *optional*):
181
+ The keyword arguments that are passed along `_process_model_before_weight_loading`.
182
+ """
183
+ model.is_quantized = True
184
+ model.quantization_method = self.quantization_config.quant_method
185
+ return self._process_model_before_weight_loading(model, **kwargs)
186
+
187
+ def postprocess_model(self, model: "ModelMixin", **kwargs):
188
+ """
189
+ Post-process the model post weights loading. Make sure to override the abstract method
190
+ `_process_model_after_weight_loading`.
191
+
192
+ Args:
193
+ model (`~diffusers.models.modeling_utils.ModelMixin`):
194
+ The model to quantize
195
+ kwargs (`dict`, *optional*):
196
+ The keyword arguments that are passed along `_process_model_after_weight_loading`.
197
+ """
198
+ return self._process_model_after_weight_loading(model, **kwargs)
199
+
200
+ def dequantize(self, model):
201
+ """
202
+ Potentially dequantize the model to retrieve the original model, with some loss in accuracy / performance. Note
203
+ not all quantization schemes support this.
204
+ """
205
+ model = self._dequantize(model)
206
+
207
+ # Delete quantizer and quantization config
208
+ del model.hf_quantizer
209
+
210
+ return model
211
+
212
+ def get_cuda_warm_up_factor(self):
213
+ """
214
+ The factor to be used in `caching_allocator_warmup` to get the number of bytes to pre-allocate to warm up cuda.
215
+ A factor of 2 means we allocate all bytes in the empty model (since we allocate in fp16), a factor of 4 means
216
+ we allocate half the memory of the weights residing in the empty model, etc...
217
+ """
218
+ # By default we return 4, i.e. half the model size (this corresponds to the case where the model is not
219
+ # really pre-processed, i.e. we do not have the info that weights are going to be 8 bits before actual
220
+ # weight loading)
221
+ return 4
222
+
223
+ def _dequantize(self, model):
224
+ raise NotImplementedError(
225
+ f"{self.quantization_config.quant_method} has no implementation of `dequantize`, please raise an issue on GitHub."
226
+ )
227
+
228
+ @abstractmethod
229
+ def _process_model_before_weight_loading(self, model, **kwargs): ...
230
+
231
+ @abstractmethod
232
+ def _process_model_after_weight_loading(self, model, **kwargs): ...
233
+
234
+ @property
235
+ @abstractmethod
236
+ def is_serializable(self): ...
237
+
238
+ @property
239
+ @abstractmethod
240
+ def is_trainable(self): ...
241
+
242
+ @property
243
+ def is_compileable(self) -> bool:
244
+ """Flag indicating whether the quantized model can be compiled"""
245
+ return False
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/bitsandbytes/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .bnb_quantizer import BnB4BitDiffusersQuantizer, BnB8BitDiffusersQuantizer
2
+ from .utils import dequantize_and_replace, dequantize_bnb_weight, replace_with_bnb_linear
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py ADDED
@@ -0,0 +1,577 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. 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
+ Adapted from
16
+ https://github.com/huggingface/transformers/blob/c409cd81777fb27aadc043ed3d8339dbc020fb3b/src/transformers/quantizers/quantizer_bnb_4bit.py
17
+ """
18
+
19
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
20
+
21
+ from ...utils import get_module_from_name
22
+ from ..base import DiffusersQuantizer
23
+
24
+
25
+ if TYPE_CHECKING:
26
+ from ...models.modeling_utils import ModelMixin
27
+
28
+ from ...utils import (
29
+ is_accelerate_available,
30
+ is_accelerate_version,
31
+ is_bitsandbytes_available,
32
+ is_bitsandbytes_version,
33
+ is_torch_available,
34
+ logging,
35
+ )
36
+
37
+
38
+ if is_torch_available():
39
+ import torch
40
+
41
+ logger = logging.get_logger(__name__)
42
+
43
+
44
+ class BnB4BitDiffusersQuantizer(DiffusersQuantizer):
45
+ """
46
+ 4-bit quantization from bitsandbytes.py quantization method:
47
+ before loading: converts transformer layers into Linear4bit during loading: load 16bit weight and pass to the
48
+ layer object after: quantizes individual weights in Linear4bit into 4bit at the first .cuda() call saving:
49
+ from state dict, as usual; saves weights and `quant_state` components
50
+ loading:
51
+ need to locate `quant_state` components and pass to Param4bit constructor
52
+ """
53
+
54
+ use_keep_in_fp32_modules = True
55
+ requires_calibration = False
56
+
57
+ def __init__(self, quantization_config, **kwargs):
58
+ super().__init__(quantization_config, **kwargs)
59
+
60
+ if self.quantization_config.llm_int8_skip_modules is not None:
61
+ self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules
62
+
63
+ def validate_environment(self, *args, **kwargs):
64
+ if not (torch.cuda.is_available() or torch.xpu.is_available()):
65
+ raise RuntimeError("No GPU found. A GPU is needed for quantization.")
66
+ if not is_accelerate_available() or is_accelerate_version("<", "0.26.0"):
67
+ raise ImportError(
68
+ "Using `bitsandbytes` 4-bit quantization requires Accelerate: `pip install 'accelerate>=0.26.0'`"
69
+ )
70
+ if not is_bitsandbytes_available() or is_bitsandbytes_version("<", "0.43.3"):
71
+ raise ImportError(
72
+ "Using `bitsandbytes` 4-bit quantization requires the latest version of bitsandbytes: `pip install -U bitsandbytes`"
73
+ )
74
+
75
+ if kwargs.get("from_flax", False):
76
+ raise ValueError(
77
+ "Converting into 4-bit weights from flax weights is currently not supported, please make"
78
+ " sure the weights are in PyTorch format."
79
+ )
80
+
81
+ device_map = kwargs.get("device_map", None)
82
+ if (
83
+ device_map is not None
84
+ and isinstance(device_map, dict)
85
+ and not self.quantization_config.llm_int8_enable_fp32_cpu_offload
86
+ ):
87
+ device_map_without_no_convert = {
88
+ key: device_map[key] for key in device_map.keys() if key not in self.modules_to_not_convert
89
+ }
90
+ if "cpu" in device_map_without_no_convert.values() or "disk" in device_map_without_no_convert.values():
91
+ raise ValueError(
92
+ "Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the "
93
+ "quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules "
94
+ "in 32-bit, you need to set `load_in_8bit_fp32_cpu_offload=True` and pass a custom `device_map` to "
95
+ "`from_pretrained`. Check "
96
+ "https://huggingface.co/docs/transformers/main/en/main_classes/quantization#offload-between-cpu-and-gpu "
97
+ "for more details. "
98
+ )
99
+
100
+ def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype":
101
+ if target_dtype != torch.int8:
102
+ from accelerate.utils import CustomDtype
103
+
104
+ logger.info("target_dtype {target_dtype} is replaced by `CustomDtype.INT4` for 4-bit BnB quantization")
105
+ return CustomDtype.INT4
106
+ else:
107
+ raise ValueError(f"Wrong `target_dtype` ({target_dtype}) provided.")
108
+
109
+ def check_if_quantized_param(
110
+ self,
111
+ model: "ModelMixin",
112
+ param_value: "torch.Tensor",
113
+ param_name: str,
114
+ state_dict: Dict[str, Any],
115
+ **kwargs,
116
+ ) -> bool:
117
+ import bitsandbytes as bnb
118
+
119
+ module, tensor_name = get_module_from_name(model, param_name)
120
+ if isinstance(module._parameters.get(tensor_name, None), bnb.nn.Params4bit):
121
+ # Add here check for loaded components' dtypes once serialization is implemented
122
+ return True
123
+ elif isinstance(module, bnb.nn.Linear4bit) and tensor_name == "bias":
124
+ # bias could be loaded by regular set_module_tensor_to_device() from accelerate,
125
+ # but it would wrongly use uninitialized weight there.
126
+ return True
127
+ else:
128
+ return False
129
+
130
+ def create_quantized_param(
131
+ self,
132
+ model: "ModelMixin",
133
+ param_value: "torch.Tensor",
134
+ param_name: str,
135
+ target_device: "torch.device",
136
+ state_dict: Dict[str, Any],
137
+ unexpected_keys: Optional[List[str]] = None,
138
+ **kwargs,
139
+ ):
140
+ import bitsandbytes as bnb
141
+
142
+ module, tensor_name = get_module_from_name(model, param_name)
143
+
144
+ if tensor_name not in module._parameters:
145
+ raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.")
146
+
147
+ old_value = getattr(module, tensor_name)
148
+
149
+ if tensor_name == "bias":
150
+ if param_value is None:
151
+ new_value = old_value.to(target_device)
152
+ else:
153
+ new_value = param_value.to(target_device)
154
+
155
+ new_value = torch.nn.Parameter(new_value, requires_grad=old_value.requires_grad)
156
+ module._parameters[tensor_name] = new_value
157
+ return
158
+
159
+ if not isinstance(module._parameters[tensor_name], bnb.nn.Params4bit):
160
+ raise ValueError("this function only loads `Linear4bit components`")
161
+ if (
162
+ old_value.device == torch.device("meta")
163
+ and target_device not in ["meta", torch.device("meta")]
164
+ and param_value is None
165
+ ):
166
+ raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {target_device}.")
167
+
168
+ # construct `new_value` for the module._parameters[tensor_name]:
169
+ if self.pre_quantized:
170
+ # 4bit loading. Collecting components for restoring quantized weight
171
+ # This can be expanded to make a universal call for any quantized weight loading
172
+
173
+ if not self.is_serializable:
174
+ raise ValueError(
175
+ "Detected int4 weights but the version of bitsandbytes is not compatible with int4 serialization. "
176
+ "Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."
177
+ )
178
+
179
+ if (param_name + ".quant_state.bitsandbytes__fp4" not in state_dict) and (
180
+ param_name + ".quant_state.bitsandbytes__nf4" not in state_dict
181
+ ):
182
+ raise ValueError(
183
+ f"Supplied state dict for {param_name} does not contain `bitsandbytes__*` and possibly other `quantized_stats` components."
184
+ )
185
+
186
+ quantized_stats = {}
187
+ for k, v in state_dict.items():
188
+ # `startswith` to counter for edge cases where `param_name`
189
+ # substring can be present in multiple places in the `state_dict`
190
+ if param_name + "." in k and k.startswith(param_name):
191
+ quantized_stats[k] = v
192
+ if unexpected_keys is not None and k in unexpected_keys:
193
+ unexpected_keys.remove(k)
194
+
195
+ new_value = bnb.nn.Params4bit.from_prequantized(
196
+ data=param_value,
197
+ quantized_stats=quantized_stats,
198
+ requires_grad=False,
199
+ device=target_device,
200
+ )
201
+ else:
202
+ new_value = param_value.to("cpu")
203
+ kwargs = old_value.__dict__
204
+ new_value = bnb.nn.Params4bit(new_value, requires_grad=False, **kwargs).to(target_device)
205
+
206
+ module._parameters[tensor_name] = new_value
207
+
208
+ def check_quantized_param_shape(self, param_name, current_param, loaded_param):
209
+ current_param_shape = current_param.shape
210
+ loaded_param_shape = loaded_param.shape
211
+
212
+ n = current_param_shape.numel()
213
+ inferred_shape = (n,) if "bias" in param_name else ((n + 1) // 2, 1)
214
+ if loaded_param_shape != inferred_shape:
215
+ raise ValueError(
216
+ f"Expected the flattened shape of the current param ({param_name}) to be {loaded_param_shape} but is {inferred_shape}."
217
+ )
218
+ else:
219
+ return True
220
+
221
+ def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]:
222
+ # need more space for buffers that are created during quantization
223
+ max_memory = {key: val * 0.90 for key, val in max_memory.items()}
224
+ return max_memory
225
+
226
+ def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
227
+ if torch_dtype is None:
228
+ # We force the `dtype` to be float16, this is a requirement from `bitsandbytes`
229
+ logger.info(
230
+ "Overriding torch_dtype=%s with `torch_dtype=torch.float16` due to "
231
+ "requirements of `bitsandbytes` to enable model loading in 8-bit or 4-bit. "
232
+ "Pass your own torch_dtype to specify the dtype of the remaining non-linear layers or pass"
233
+ " torch_dtype=torch.float16 to remove this warning.",
234
+ torch_dtype,
235
+ )
236
+ torch_dtype = torch.float16
237
+ return torch_dtype
238
+
239
+ def update_device_map(self, device_map):
240
+ if device_map is None:
241
+ if torch.xpu.is_available():
242
+ current_device = f"xpu:{torch.xpu.current_device()}"
243
+ else:
244
+ current_device = f"cuda:{torch.cuda.current_device()}"
245
+ device_map = {"": current_device}
246
+ logger.info(
247
+ "The device_map was not initialized. "
248
+ "Setting device_map to {"
249
+ ": {current_device}}. "
250
+ "If you want to use the model for inference, please set device_map ='auto' "
251
+ )
252
+ return device_map
253
+
254
+ def _process_model_before_weight_loading(
255
+ self,
256
+ model: "ModelMixin",
257
+ device_map,
258
+ keep_in_fp32_modules: List[str] = [],
259
+ **kwargs,
260
+ ):
261
+ from .utils import replace_with_bnb_linear
262
+
263
+ load_in_8bit_fp32_cpu_offload = self.quantization_config.llm_int8_enable_fp32_cpu_offload
264
+
265
+ # We may keep some modules such as the `proj_out` in their original dtype for numerical stability reasons
266
+ self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules
267
+
268
+ if not isinstance(self.modules_to_not_convert, list):
269
+ self.modules_to_not_convert = [self.modules_to_not_convert]
270
+
271
+ self.modules_to_not_convert.extend(keep_in_fp32_modules)
272
+
273
+ # Extend `self.modules_to_not_convert` to keys that are supposed to be offloaded to `cpu` or `disk`
274
+ if isinstance(device_map, dict) and len(device_map.keys()) > 1:
275
+ keys_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]]
276
+
277
+ if len(keys_on_cpu) > 0 and not load_in_8bit_fp32_cpu_offload:
278
+ raise ValueError(
279
+ "If you want to offload some keys to `cpu` or `disk`, you need to set "
280
+ "`llm_int8_enable_fp32_cpu_offload=True`. Note that these modules will not be "
281
+ " converted to 8-bit but kept in 32-bit."
282
+ )
283
+ self.modules_to_not_convert.extend(keys_on_cpu)
284
+
285
+ # Purge `None`.
286
+ # Unlike `transformers`, we don't know if we should always keep certain modules in FP32
287
+ # in case of diffusion transformer models. For language models and others alike, `lm_head`
288
+ # and tied modules are usually kept in FP32.
289
+ self.modules_to_not_convert = [module for module in self.modules_to_not_convert if module is not None]
290
+
291
+ model = replace_with_bnb_linear(
292
+ model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config
293
+ )
294
+ model.config.quantization_config = self.quantization_config
295
+ model.is_loaded_in_4bit = True
296
+
297
+ def _process_model_after_weight_loading(self, model: "ModelMixin", **kwargs):
298
+ model.is_4bit_serializable = self.is_serializable
299
+ return model
300
+
301
+ @property
302
+ def is_serializable(self):
303
+ # Because we're mandating `bitsandbytes` 0.43.3.
304
+ return True
305
+
306
+ @property
307
+ def is_trainable(self) -> bool:
308
+ # Because we're mandating `bitsandbytes` 0.43.3.
309
+ return True
310
+
311
+ def _dequantize(self, model):
312
+ from .utils import dequantize_and_replace
313
+
314
+ is_model_on_cpu = model.device.type == "cpu"
315
+ if is_model_on_cpu:
316
+ logger.info(
317
+ "Model was found to be on CPU (could happen as a result of `enable_model_cpu_offload()`). So, moving it to GPU. After dequantization, will move the model back to CPU again to preserve the previous device."
318
+ )
319
+ if torch.xpu.is_available():
320
+ model.to(torch.xpu.current_device())
321
+ else:
322
+ model.to(torch.cuda.current_device())
323
+
324
+ model = dequantize_and_replace(
325
+ model, self.modules_to_not_convert, quantization_config=self.quantization_config
326
+ )
327
+ if is_model_on_cpu:
328
+ model.to("cpu")
329
+ return model
330
+
331
+
332
+ class BnB8BitDiffusersQuantizer(DiffusersQuantizer):
333
+ """
334
+ 8-bit quantization from bitsandbytes quantization method:
335
+ before loading: converts transformer layers into Linear8bitLt during loading: load 16bit weight and pass to the
336
+ layer object after: quantizes individual weights in Linear8bitLt into 8bit at fitst .cuda() call
337
+ saving:
338
+ from state dict, as usual; saves weights and 'SCB' component
339
+ loading:
340
+ need to locate SCB component and pass to the Linear8bitLt object
341
+ """
342
+
343
+ use_keep_in_fp32_modules = True
344
+ requires_calibration = False
345
+
346
+ def __init__(self, quantization_config, **kwargs):
347
+ super().__init__(quantization_config, **kwargs)
348
+
349
+ if self.quantization_config.llm_int8_skip_modules is not None:
350
+ self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules
351
+
352
+ def validate_environment(self, *args, **kwargs):
353
+ if not (torch.cuda.is_available() or torch.xpu.is_available()):
354
+ raise RuntimeError("No GPU found. A GPU is needed for quantization.")
355
+ if not is_accelerate_available() or is_accelerate_version("<", "0.26.0"):
356
+ raise ImportError(
357
+ "Using `bitsandbytes` 8-bit quantization requires Accelerate: `pip install 'accelerate>=0.26.0'`"
358
+ )
359
+ if not is_bitsandbytes_available() or is_bitsandbytes_version("<", "0.43.3"):
360
+ raise ImportError(
361
+ "Using `bitsandbytes` 8-bit quantization requires the latest version of bitsandbytes: `pip install -U bitsandbytes`"
362
+ )
363
+
364
+ if kwargs.get("from_flax", False):
365
+ raise ValueError(
366
+ "Converting into 8-bit weights from flax weights is currently not supported, please make"
367
+ " sure the weights are in PyTorch format."
368
+ )
369
+
370
+ device_map = kwargs.get("device_map", None)
371
+ if (
372
+ device_map is not None
373
+ and isinstance(device_map, dict)
374
+ and not self.quantization_config.llm_int8_enable_fp32_cpu_offload
375
+ ):
376
+ device_map_without_no_convert = {
377
+ key: device_map[key] for key in device_map.keys() if key not in self.modules_to_not_convert
378
+ }
379
+ if "cpu" in device_map_without_no_convert.values() or "disk" in device_map_without_no_convert.values():
380
+ raise ValueError(
381
+ "Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the "
382
+ "quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules "
383
+ "in 32-bit, you need to set `load_in_8bit_fp32_cpu_offload=True` and pass a custom `device_map` to "
384
+ "`from_pretrained`. Check "
385
+ "https://huggingface.co/docs/transformers/main/en/main_classes/quantization#offload-between-cpu-and-gpu "
386
+ "for more details. "
387
+ )
388
+
389
+ # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer.adjust_max_memory
390
+ def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]:
391
+ # need more space for buffers that are created during quantization
392
+ max_memory = {key: val * 0.90 for key, val in max_memory.items()}
393
+ return max_memory
394
+
395
+ # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer.update_torch_dtype
396
+ def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
397
+ if torch_dtype is None:
398
+ # We force the `dtype` to be float16, this is a requirement from `bitsandbytes`
399
+ logger.info(
400
+ "Overriding torch_dtype=%s with `torch_dtype=torch.float16` due to "
401
+ "requirements of `bitsandbytes` to enable model loading in 8-bit or 4-bit. "
402
+ "Pass your own torch_dtype to specify the dtype of the remaining non-linear layers or pass"
403
+ " torch_dtype=torch.float16 to remove this warning.",
404
+ torch_dtype,
405
+ )
406
+ torch_dtype = torch.float16
407
+ return torch_dtype
408
+
409
+ # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer.update_device_map
410
+ def update_device_map(self, device_map):
411
+ if device_map is None:
412
+ if torch.xpu.is_available():
413
+ current_device = f"xpu:{torch.xpu.current_device()}"
414
+ else:
415
+ current_device = f"cuda:{torch.cuda.current_device()}"
416
+ device_map = {"": current_device}
417
+ logger.info(
418
+ "The device_map was not initialized. "
419
+ "Setting device_map to {"
420
+ ": {current_device}}. "
421
+ "If you want to use the model for inference, please set device_map ='auto' "
422
+ )
423
+ return device_map
424
+
425
+ def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype":
426
+ if target_dtype != torch.int8:
427
+ logger.info("target_dtype {target_dtype} is replaced by `torch.int8` for 8-bit BnB quantization")
428
+ return torch.int8
429
+
430
+ def check_if_quantized_param(
431
+ self,
432
+ model: "ModelMixin",
433
+ param_value: "torch.Tensor",
434
+ param_name: str,
435
+ state_dict: Dict[str, Any],
436
+ **kwargs,
437
+ ):
438
+ import bitsandbytes as bnb
439
+
440
+ module, tensor_name = get_module_from_name(model, param_name)
441
+ if isinstance(module._parameters.get(tensor_name, None), bnb.nn.Int8Params):
442
+ if self.pre_quantized:
443
+ if param_name.replace("weight", "SCB") not in state_dict.keys():
444
+ raise ValueError("Missing quantization component `SCB`")
445
+ if param_value.dtype != torch.int8:
446
+ raise ValueError(
447
+ f"Incompatible dtype `{param_value.dtype}` when loading 8-bit prequantized weight. Expected `torch.int8`."
448
+ )
449
+ return True
450
+ return False
451
+
452
+ def create_quantized_param(
453
+ self,
454
+ model: "ModelMixin",
455
+ param_value: "torch.Tensor",
456
+ param_name: str,
457
+ target_device: "torch.device",
458
+ state_dict: Dict[str, Any],
459
+ unexpected_keys: Optional[List[str]] = None,
460
+ **kwargs,
461
+ ):
462
+ import bitsandbytes as bnb
463
+
464
+ fp16_statistics_key = param_name.replace("weight", "SCB")
465
+ fp16_weights_format_key = param_name.replace("weight", "weight_format")
466
+
467
+ fp16_statistics = state_dict.get(fp16_statistics_key, None)
468
+ fp16_weights_format = state_dict.get(fp16_weights_format_key, None)
469
+
470
+ module, tensor_name = get_module_from_name(model, param_name)
471
+ if tensor_name not in module._parameters:
472
+ raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.")
473
+
474
+ old_value = getattr(module, tensor_name)
475
+
476
+ if not isinstance(module._parameters[tensor_name], bnb.nn.Int8Params):
477
+ raise ValueError(f"Parameter `{tensor_name}` should only be a `bnb.nn.Int8Params` instance.")
478
+ if (
479
+ old_value.device == torch.device("meta")
480
+ and target_device not in ["meta", torch.device("meta")]
481
+ and param_value is None
482
+ ):
483
+ raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {target_device}.")
484
+
485
+ new_value = param_value.to("cpu")
486
+ if self.pre_quantized and not self.is_serializable:
487
+ raise ValueError(
488
+ "Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. "
489
+ "Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."
490
+ )
491
+
492
+ kwargs = old_value.__dict__
493
+ new_value = bnb.nn.Int8Params(new_value, requires_grad=False, **kwargs).to(target_device)
494
+
495
+ module._parameters[tensor_name] = new_value
496
+ if fp16_statistics is not None:
497
+ setattr(module.weight, "SCB", fp16_statistics.to(target_device))
498
+ if unexpected_keys is not None:
499
+ unexpected_keys.remove(fp16_statistics_key)
500
+
501
+ # We just need to pop the `weight_format` keys from the state dict to remove unneeded
502
+ # messages. The correct format is correctly retrieved during the first forward pass.
503
+ if fp16_weights_format is not None and unexpected_keys is not None:
504
+ unexpected_keys.remove(fp16_weights_format_key)
505
+
506
+ # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer._process_model_after_weight_loading with 4bit->8bit
507
+ def _process_model_after_weight_loading(self, model: "ModelMixin", **kwargs):
508
+ model.is_8bit_serializable = self.is_serializable
509
+ return model
510
+
511
+ # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer._process_model_before_weight_loading with 4bit->8bit
512
+ def _process_model_before_weight_loading(
513
+ self,
514
+ model: "ModelMixin",
515
+ device_map,
516
+ keep_in_fp32_modules: List[str] = [],
517
+ **kwargs,
518
+ ):
519
+ from .utils import replace_with_bnb_linear
520
+
521
+ load_in_8bit_fp32_cpu_offload = self.quantization_config.llm_int8_enable_fp32_cpu_offload
522
+
523
+ # We may keep some modules such as the `proj_out` in their original dtype for numerical stability reasons
524
+ self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules
525
+
526
+ if not isinstance(self.modules_to_not_convert, list):
527
+ self.modules_to_not_convert = [self.modules_to_not_convert]
528
+
529
+ self.modules_to_not_convert.extend(keep_in_fp32_modules)
530
+
531
+ # Extend `self.modules_to_not_convert` to keys that are supposed to be offloaded to `cpu` or `disk`
532
+ if isinstance(device_map, dict) and len(device_map.keys()) > 1:
533
+ keys_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]]
534
+
535
+ if len(keys_on_cpu) > 0 and not load_in_8bit_fp32_cpu_offload:
536
+ raise ValueError(
537
+ "If you want to offload some keys to `cpu` or `disk`, you need to set "
538
+ "`llm_int8_enable_fp32_cpu_offload=True`. Note that these modules will not be "
539
+ " converted to 8-bit but kept in 32-bit."
540
+ )
541
+ self.modules_to_not_convert.extend(keys_on_cpu)
542
+
543
+ # Purge `None`.
544
+ # Unlike `transformers`, we don't know if we should always keep certain modules in FP32
545
+ # in case of diffusion transformer models. For language models and others alike, `lm_head`
546
+ # and tied modules are usually kept in FP32.
547
+ self.modules_to_not_convert = [module for module in self.modules_to_not_convert if module is not None]
548
+
549
+ model = replace_with_bnb_linear(
550
+ model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config
551
+ )
552
+ model.config.quantization_config = self.quantization_config
553
+ model.is_loaded_in_8bit = True
554
+
555
+ @property
556
+ # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer.is_serializable
557
+ def is_serializable(self):
558
+ # Because we're mandating `bitsandbytes` 0.43.3.
559
+ return True
560
+
561
+ @property
562
+ # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer.is_serializable
563
+ def is_trainable(self) -> bool:
564
+ # Because we're mandating `bitsandbytes` 0.43.3.
565
+ return True
566
+
567
+ @property
568
+ def is_compileable(self) -> bool:
569
+ return True
570
+
571
+ def _dequantize(self, model):
572
+ from .utils import dequantize_and_replace
573
+
574
+ model = dequantize_and_replace(
575
+ model, self.modules_to_not_convert, quantization_config=self.quantization_config
576
+ )
577
+ return model
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/bitsandbytes/utils.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. 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
+ Adapted from
16
+ https://github.com/huggingface/transformers/blob/c409cd81777fb27aadc043ed3d8339dbc020fb3b/src/transformers/integrations/bitsandbytes.py
17
+ """
18
+
19
+ import inspect
20
+ from inspect import signature
21
+ from typing import Union
22
+
23
+ from ...utils import is_accelerate_available, is_bitsandbytes_available, is_torch_available, logging
24
+ from ..quantization_config import QuantizationMethod
25
+
26
+
27
+ if is_torch_available():
28
+ import torch
29
+ import torch.nn as nn
30
+
31
+ if is_bitsandbytes_available():
32
+ import bitsandbytes as bnb
33
+
34
+ if is_accelerate_available():
35
+ import accelerate
36
+ from accelerate import init_empty_weights
37
+ from accelerate.hooks import add_hook_to_module, remove_hook_from_module
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+
42
+ def _replace_with_bnb_linear(
43
+ model,
44
+ modules_to_not_convert=None,
45
+ current_key_name=None,
46
+ quantization_config=None,
47
+ has_been_replaced=False,
48
+ ):
49
+ """
50
+ Private method that wraps the recursion for module replacement.
51
+
52
+ Returns the converted model and a boolean that indicates if the conversion has been successful or not.
53
+ """
54
+ for name, module in model.named_children():
55
+ if current_key_name is None:
56
+ current_key_name = []
57
+ current_key_name.append(name)
58
+
59
+ if isinstance(module, nn.Linear) and name not in modules_to_not_convert:
60
+ # Check if the current key is not in the `modules_to_not_convert`
61
+ current_key_name_str = ".".join(current_key_name)
62
+ if not any(
63
+ (key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
64
+ ):
65
+ with init_empty_weights():
66
+ in_features = module.in_features
67
+ out_features = module.out_features
68
+
69
+ if quantization_config.quantization_method() == "llm_int8":
70
+ model._modules[name] = bnb.nn.Linear8bitLt(
71
+ in_features,
72
+ out_features,
73
+ module.bias is not None,
74
+ has_fp16_weights=quantization_config.llm_int8_has_fp16_weight,
75
+ threshold=quantization_config.llm_int8_threshold,
76
+ )
77
+ has_been_replaced = True
78
+ else:
79
+ if (
80
+ quantization_config.llm_int8_skip_modules is not None
81
+ and name in quantization_config.llm_int8_skip_modules
82
+ ):
83
+ pass
84
+ else:
85
+ extra_kwargs = (
86
+ {"quant_storage": quantization_config.bnb_4bit_quant_storage}
87
+ if "quant_storage" in list(signature(bnb.nn.Linear4bit).parameters)
88
+ else {}
89
+ )
90
+ model._modules[name] = bnb.nn.Linear4bit(
91
+ in_features,
92
+ out_features,
93
+ module.bias is not None,
94
+ quantization_config.bnb_4bit_compute_dtype,
95
+ compress_statistics=quantization_config.bnb_4bit_use_double_quant,
96
+ quant_type=quantization_config.bnb_4bit_quant_type,
97
+ **extra_kwargs,
98
+ )
99
+ has_been_replaced = True
100
+ # Store the module class in case we need to transpose the weight later
101
+ model._modules[name].source_cls = type(module)
102
+ # Force requires grad to False to avoid unexpected errors
103
+ model._modules[name].requires_grad_(False)
104
+ if len(list(module.children())) > 0:
105
+ _, has_been_replaced = _replace_with_bnb_linear(
106
+ module,
107
+ modules_to_not_convert,
108
+ current_key_name,
109
+ quantization_config,
110
+ has_been_replaced=has_been_replaced,
111
+ )
112
+ # Remove the last key for recursion
113
+ current_key_name.pop(-1)
114
+ return model, has_been_replaced
115
+
116
+
117
+ def replace_with_bnb_linear(model, modules_to_not_convert=None, current_key_name=None, quantization_config=None):
118
+ """
119
+ Helper function to replace the `nn.Linear` layers within `model` with either `bnb.nn.Linear8bit` or
120
+ `bnb.nn.Linear4bit` using the `bitsandbytes` library.
121
+
122
+ References:
123
+ * `bnb.nn.Linear8bit`: [LLM.int8(): 8-bit Matrix Multiplication for Transformers at
124
+ Scale](https://huggingface.co/papers/2208.07339)
125
+ * `bnb.nn.Linear4bit`: [QLoRA: Efficient Finetuning of Quantized
126
+ LLMs](https://huggingface.co/papers/2305.14314)
127
+
128
+ Parameters:
129
+ model (`torch.nn.Module`):
130
+ Input model or `torch.nn.Module` as the function is run recursively.
131
+ modules_to_not_convert (`List[`str`]`, *optional*, defaults to `[]`):
132
+ Names of the modules to not convert in `Linear8bitLt`. In practice we keep the `modules_to_not_convert` in
133
+ full precision for numerical stability reasons.
134
+ current_key_name (`List[`str`]`, *optional*):
135
+ An array to track the current key of the recursion. This is used to check whether the current key (part of
136
+ it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
137
+ `disk`).
138
+ quantization_config ('transformers.utils.quantization_config.BitsAndBytesConfig'):
139
+ To configure and manage settings related to quantization, a technique used to compress neural network
140
+ models by reducing the precision of the weights and activations, thus making models more efficient in terms
141
+ of both storage and computation.
142
+ """
143
+ model, _ = _replace_with_bnb_linear(model, modules_to_not_convert, current_key_name, quantization_config)
144
+
145
+ has_been_replaced = any(
146
+ isinstance(replaced_module, (bnb.nn.Linear4bit, bnb.nn.Linear8bitLt))
147
+ for _, replaced_module in model.named_modules()
148
+ )
149
+ if not has_been_replaced:
150
+ logger.warning(
151
+ "You are loading your model in 8bit or 4bit but no linear modules were found in your model."
152
+ " Please double check your model architecture, or submit an issue on github if you think this is"
153
+ " a bug."
154
+ )
155
+
156
+ return model
157
+
158
+
159
+ # Adapted from PEFT: https://github.com/huggingface/peft/blob/6d458b300fc2ed82e19f796b53af4c97d03ea604/src/peft/utils/integrations.py#L81
160
+ def dequantize_bnb_weight(weight: "torch.nn.Parameter", state=None, dtype: "torch.dtype" = None):
161
+ """
162
+ Helper function to dequantize 4bit or 8bit bnb weights.
163
+
164
+ If the weight is not a bnb quantized weight, it will be returned as is.
165
+ """
166
+ if not isinstance(weight, torch.nn.Parameter):
167
+ raise TypeError(f"Input weight should be of type nn.Parameter, got {type(weight)} instead")
168
+
169
+ cls_name = weight.__class__.__name__
170
+ if cls_name not in ("Params4bit", "Int8Params"):
171
+ return weight
172
+
173
+ if cls_name == "Params4bit":
174
+ output_tensor = bnb.functional.dequantize_4bit(weight.data, weight.quant_state)
175
+ msg = f"The model is going to be dequantized in {output_tensor.dtype} - if you want to upcast it to another dtype, make sure to pass the desired dtype when quantizing the model through `bnb_4bit_quant_type` argument of `BitsAndBytesConfig`"
176
+ if dtype:
177
+ msg = f"The model is going to be first dequantized in {output_tensor.dtype} and type-casted to {dtype}"
178
+ output_tensor = output_tensor.to(dtype)
179
+ logger.warning_once(msg)
180
+ return output_tensor
181
+
182
+ if state.SCB is None:
183
+ state.SCB = weight.SCB
184
+
185
+ if hasattr(bnb.functional, "int8_vectorwise_dequant"):
186
+ # Use bitsandbytes API if available (requires v0.45.0+)
187
+ dequantized = bnb.functional.int8_vectorwise_dequant(weight.data, state.SCB)
188
+ else:
189
+ # Multiply by (scale/127) to dequantize.
190
+ dequantized = weight.data * state.SCB.view(-1, 1) * 7.874015718698502e-3
191
+
192
+ if dtype:
193
+ dequantized = dequantized.to(dtype)
194
+ return dequantized
195
+
196
+
197
+ def _create_accelerate_new_hook(old_hook):
198
+ r"""
199
+ Creates a new hook based on the old hook. Use it only if you know what you are doing ! This method is a copy of:
200
+ https://github.com/huggingface/peft/blob/748f7968f3a31ec06a1c2b0328993319ad9a150a/src/peft/utils/other.py#L245 with
201
+ some changes
202
+ """
203
+ old_hook_cls = getattr(accelerate.hooks, old_hook.__class__.__name__)
204
+ old_hook_attr = old_hook.__dict__
205
+ filtered_old_hook_attr = {}
206
+ old_hook_init_signature = inspect.signature(old_hook_cls.__init__)
207
+ for k in old_hook_attr.keys():
208
+ if k in old_hook_init_signature.parameters:
209
+ filtered_old_hook_attr[k] = old_hook_attr[k]
210
+ new_hook = old_hook_cls(**filtered_old_hook_attr)
211
+ return new_hook
212
+
213
+
214
+ def _dequantize_and_replace(
215
+ model,
216
+ dtype,
217
+ modules_to_not_convert=None,
218
+ current_key_name=None,
219
+ quantization_config=None,
220
+ has_been_replaced=False,
221
+ ):
222
+ """
223
+ Converts a quantized model into its dequantized original version. The newly converted model will have some
224
+ performance drop compared to the original model before quantization - use it only for specific usecases such as
225
+ QLoRA adapters merging.
226
+
227
+ Returns the converted model and a boolean that indicates if the conversion has been successful or not.
228
+ """
229
+ quant_method = quantization_config.quantization_method()
230
+
231
+ target_cls = bnb.nn.Linear8bitLt if quant_method == "llm_int8" else bnb.nn.Linear4bit
232
+
233
+ for name, module in model.named_children():
234
+ if current_key_name is None:
235
+ current_key_name = []
236
+ current_key_name.append(name)
237
+
238
+ if isinstance(module, target_cls) and name not in modules_to_not_convert:
239
+ # Check if the current key is not in the `modules_to_not_convert`
240
+ current_key_name_str = ".".join(current_key_name)
241
+
242
+ if not any(
243
+ (key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
244
+ ):
245
+ bias = getattr(module, "bias", None)
246
+
247
+ device = module.weight.device
248
+ with init_empty_weights():
249
+ new_module = torch.nn.Linear(module.in_features, module.out_features, bias=bias is not None)
250
+
251
+ if quant_method == "llm_int8":
252
+ state = module.state
253
+ else:
254
+ state = None
255
+
256
+ new_module.weight = torch.nn.Parameter(dequantize_bnb_weight(module.weight, state, dtype))
257
+
258
+ if bias is not None:
259
+ new_module.bias = bias
260
+
261
+ # Create a new hook and attach it in case we use accelerate
262
+ if hasattr(module, "_hf_hook"):
263
+ old_hook = module._hf_hook
264
+ new_hook = _create_accelerate_new_hook(old_hook)
265
+
266
+ remove_hook_from_module(module)
267
+ add_hook_to_module(new_module, new_hook)
268
+
269
+ new_module.to(device)
270
+ model._modules[name] = new_module
271
+ has_been_replaced = True
272
+ if len(list(module.children())) > 0:
273
+ _, has_been_replaced = _dequantize_and_replace(
274
+ module,
275
+ dtype=dtype,
276
+ modules_to_not_convert=modules_to_not_convert,
277
+ current_key_name=current_key_name,
278
+ quantization_config=quantization_config,
279
+ has_been_replaced=has_been_replaced,
280
+ )
281
+ # Remove the last key for recursion
282
+ current_key_name.pop(-1)
283
+ return model, has_been_replaced
284
+
285
+
286
+ def dequantize_and_replace(
287
+ model,
288
+ modules_to_not_convert=None,
289
+ quantization_config=None,
290
+ ):
291
+ model, _ = _dequantize_and_replace(
292
+ model,
293
+ dtype=model.dtype,
294
+ modules_to_not_convert=modules_to_not_convert,
295
+ quantization_config=quantization_config,
296
+ )
297
+ has_been_replaced = any(
298
+ isinstance(replaced_module, torch.nn.Linear) for _, replaced_module in model.named_modules()
299
+ )
300
+ if not has_been_replaced:
301
+ logger.warning(
302
+ "Some linear modules were not dequantized. This could lead to unexpected behaviour. Please check your model."
303
+ )
304
+
305
+ return model
306
+
307
+
308
+ def _check_bnb_status(module) -> Union[bool, bool]:
309
+ is_loaded_in_4bit_bnb = (
310
+ hasattr(module, "is_loaded_in_4bit")
311
+ and module.is_loaded_in_4bit
312
+ and getattr(module, "quantization_method", None) == QuantizationMethod.BITS_AND_BYTES
313
+ )
314
+ is_loaded_in_8bit_bnb = (
315
+ hasattr(module, "is_loaded_in_8bit")
316
+ and module.is_loaded_in_8bit
317
+ and getattr(module, "quantization_method", None) == QuantizationMethod.BITS_AND_BYTES
318
+ )
319
+ return is_loaded_in_4bit_bnb or is_loaded_in_8bit_bnb, is_loaded_in_4bit_bnb, is_loaded_in_8bit_bnb
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/gguf/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .gguf_quantizer import GGUFQuantizer
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/gguf/gguf_quantizer.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
2
+
3
+ from ..base import DiffusersQuantizer
4
+
5
+
6
+ if TYPE_CHECKING:
7
+ from ...models.modeling_utils import ModelMixin
8
+
9
+
10
+ from ...utils import (
11
+ get_module_from_name,
12
+ is_accelerate_available,
13
+ is_accelerate_version,
14
+ is_gguf_available,
15
+ is_gguf_version,
16
+ is_torch_available,
17
+ logging,
18
+ )
19
+
20
+
21
+ if is_torch_available() and is_gguf_available():
22
+ import torch
23
+
24
+ from .utils import (
25
+ GGML_QUANT_SIZES,
26
+ GGUFParameter,
27
+ _dequantize_gguf_and_restore_linear,
28
+ _quant_shape_from_byte_shape,
29
+ _replace_with_gguf_linear,
30
+ )
31
+
32
+
33
+ logger = logging.get_logger(__name__)
34
+
35
+
36
+ class GGUFQuantizer(DiffusersQuantizer):
37
+ use_keep_in_fp32_modules = True
38
+
39
+ def __init__(self, quantization_config, **kwargs):
40
+ super().__init__(quantization_config, **kwargs)
41
+
42
+ self.compute_dtype = quantization_config.compute_dtype
43
+ self.pre_quantized = quantization_config.pre_quantized
44
+ self.modules_to_not_convert = quantization_config.modules_to_not_convert
45
+
46
+ if not isinstance(self.modules_to_not_convert, list):
47
+ self.modules_to_not_convert = [self.modules_to_not_convert]
48
+
49
+ def validate_environment(self, *args, **kwargs):
50
+ if not is_accelerate_available() or is_accelerate_version("<", "0.26.0"):
51
+ raise ImportError(
52
+ "Loading GGUF Parameters requires `accelerate` installed in your environment: `pip install 'accelerate>=0.26.0'`"
53
+ )
54
+ if not is_gguf_available() or is_gguf_version("<", "0.10.0"):
55
+ raise ImportError(
56
+ "To load GGUF format files you must have `gguf` installed in your environment: `pip install gguf>=0.10.0`"
57
+ )
58
+
59
+ # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer.adjust_max_memory
60
+ def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]:
61
+ # need more space for buffers that are created during quantization
62
+ max_memory = {key: val * 0.90 for key, val in max_memory.items()}
63
+ return max_memory
64
+
65
+ def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype":
66
+ if target_dtype != torch.uint8:
67
+ logger.info(f"target_dtype {target_dtype} is replaced by `torch.uint8` for GGUF quantization")
68
+ return torch.uint8
69
+
70
+ def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
71
+ if torch_dtype is None:
72
+ torch_dtype = self.compute_dtype
73
+ return torch_dtype
74
+
75
+ def check_quantized_param_shape(self, param_name, current_param, loaded_param):
76
+ loaded_param_shape = loaded_param.shape
77
+ current_param_shape = current_param.shape
78
+ quant_type = loaded_param.quant_type
79
+
80
+ block_size, type_size = GGML_QUANT_SIZES[quant_type]
81
+
82
+ inferred_shape = _quant_shape_from_byte_shape(loaded_param_shape, type_size, block_size)
83
+ if inferred_shape != current_param_shape:
84
+ raise ValueError(
85
+ f"{param_name} has an expected quantized shape of: {inferred_shape}, but received shape: {loaded_param_shape}"
86
+ )
87
+
88
+ return True
89
+
90
+ def check_if_quantized_param(
91
+ self,
92
+ model: "ModelMixin",
93
+ param_value: Union["GGUFParameter", "torch.Tensor"],
94
+ param_name: str,
95
+ state_dict: Dict[str, Any],
96
+ **kwargs,
97
+ ) -> bool:
98
+ if isinstance(param_value, GGUFParameter):
99
+ return True
100
+
101
+ return False
102
+
103
+ def create_quantized_param(
104
+ self,
105
+ model: "ModelMixin",
106
+ param_value: Union["GGUFParameter", "torch.Tensor"],
107
+ param_name: str,
108
+ target_device: "torch.device",
109
+ state_dict: Optional[Dict[str, Any]] = None,
110
+ unexpected_keys: Optional[List[str]] = None,
111
+ **kwargs,
112
+ ):
113
+ module, tensor_name = get_module_from_name(model, param_name)
114
+ if tensor_name not in module._parameters and tensor_name not in module._buffers:
115
+ raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.")
116
+
117
+ if tensor_name in module._parameters:
118
+ module._parameters[tensor_name] = param_value.to(target_device)
119
+ if tensor_name in module._buffers:
120
+ module._buffers[tensor_name] = param_value.to(target_device)
121
+
122
+ def _process_model_before_weight_loading(
123
+ self,
124
+ model: "ModelMixin",
125
+ device_map,
126
+ keep_in_fp32_modules: List[str] = [],
127
+ **kwargs,
128
+ ):
129
+ state_dict = kwargs.get("state_dict", None)
130
+
131
+ self.modules_to_not_convert.extend(keep_in_fp32_modules)
132
+ self.modules_to_not_convert = [module for module in self.modules_to_not_convert if module is not None]
133
+
134
+ _replace_with_gguf_linear(
135
+ model, self.compute_dtype, state_dict, modules_to_not_convert=self.modules_to_not_convert
136
+ )
137
+
138
+ def _process_model_after_weight_loading(self, model: "ModelMixin", **kwargs):
139
+ return model
140
+
141
+ @property
142
+ def is_serializable(self):
143
+ return False
144
+
145
+ @property
146
+ def is_trainable(self) -> bool:
147
+ return False
148
+
149
+ @property
150
+ def is_compileable(self) -> bool:
151
+ return True
152
+
153
+ def _dequantize(self, model):
154
+ is_model_on_cpu = model.device.type == "cpu"
155
+ if is_model_on_cpu:
156
+ logger.info(
157
+ "Model was found to be on CPU (could happen as a result of `enable_model_cpu_offload()`). So, moving it to accelerator. After dequantization, will move the model back to CPU again to preserve the previous device."
158
+ )
159
+ device = (
160
+ torch.accelerator.current_accelerator()
161
+ if hasattr(torch, "accelerator")
162
+ else torch.cuda.current_device()
163
+ )
164
+ model.to(device)
165
+
166
+ model = _dequantize_gguf_and_restore_linear(model, self.modules_to_not_convert)
167
+ if is_model_on_cpu:
168
+ model.to("cpu")
169
+ return model
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/gguf/utils.py ADDED
@@ -0,0 +1,606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team and City96. 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
+ import os
17
+ from contextlib import nullcontext
18
+
19
+ import gguf
20
+ import torch
21
+ import torch.nn as nn
22
+
23
+ from ...utils import is_accelerate_available, is_kernels_available
24
+
25
+
26
+ if is_accelerate_available():
27
+ import accelerate
28
+ from accelerate import init_empty_weights
29
+ from accelerate.hooks import add_hook_to_module, remove_hook_from_module
30
+
31
+
32
+ can_use_cuda_kernels = (
33
+ os.getenv("DIFFUSERS_GGUF_CUDA_KERNELS", "false").lower() in ["1", "true", "yes"]
34
+ and torch.cuda.is_available()
35
+ and torch.cuda.get_device_capability()[0] >= 7
36
+ )
37
+ if can_use_cuda_kernels and is_kernels_available():
38
+ from kernels import get_kernel
39
+
40
+ ops = get_kernel("Isotr0py/ggml")
41
+ else:
42
+ ops = None
43
+
44
+ UNQUANTIZED_TYPES = {gguf.GGMLQuantizationType.F32, gguf.GGMLQuantizationType.F16, gguf.GGMLQuantizationType.BF16}
45
+ STANDARD_QUANT_TYPES = {
46
+ gguf.GGMLQuantizationType.Q4_0,
47
+ gguf.GGMLQuantizationType.Q4_1,
48
+ gguf.GGMLQuantizationType.Q5_0,
49
+ gguf.GGMLQuantizationType.Q5_1,
50
+ gguf.GGMLQuantizationType.Q8_0,
51
+ gguf.GGMLQuantizationType.Q8_1,
52
+ }
53
+ KQUANT_TYPES = {
54
+ gguf.GGMLQuantizationType.Q2_K,
55
+ gguf.GGMLQuantizationType.Q3_K,
56
+ gguf.GGMLQuantizationType.Q4_K,
57
+ gguf.GGMLQuantizationType.Q5_K,
58
+ gguf.GGMLQuantizationType.Q6_K,
59
+ }
60
+ IMATRIX_QUANT_TYPES = {
61
+ gguf.GGMLQuantizationType.IQ1_M,
62
+ gguf.GGMLQuantizationType.IQ1_S,
63
+ gguf.GGMLQuantizationType.IQ2_XXS,
64
+ gguf.GGMLQuantizationType.IQ2_XS,
65
+ gguf.GGMLQuantizationType.IQ2_S,
66
+ gguf.GGMLQuantizationType.IQ3_XXS,
67
+ gguf.GGMLQuantizationType.IQ3_S,
68
+ gguf.GGMLQuantizationType.IQ4_XS,
69
+ gguf.GGMLQuantizationType.IQ4_NL,
70
+ }
71
+ # TODO(Isotr0py): Currently, we don't have MMQ kernel for I-Matrix quantization.
72
+ # Consolidate DEQUANT_TYPES, MMVQ_QUANT_TYPES and MMQ_QUANT_TYPES after we add
73
+ # MMQ kernel for I-Matrix quantization.
74
+ DEQUANT_TYPES = STANDARD_QUANT_TYPES | KQUANT_TYPES | IMATRIX_QUANT_TYPES
75
+ MMVQ_QUANT_TYPES = STANDARD_QUANT_TYPES | KQUANT_TYPES | IMATRIX_QUANT_TYPES
76
+ MMQ_QUANT_TYPES = STANDARD_QUANT_TYPES | KQUANT_TYPES
77
+
78
+
79
+ def _fused_mul_mat_gguf(x: torch.Tensor, qweight: torch.Tensor, qweight_type: int) -> torch.Tensor:
80
+ # there is no need to call any kernel for fp16/bf16
81
+ if qweight_type in UNQUANTIZED_TYPES:
82
+ return x @ qweight.T
83
+
84
+ # TODO(Isotr0py): GGUF's MMQ and MMVQ implementation are designed for
85
+ # contiguous batching and inefficient with diffusers' batching,
86
+ # so we disabled it now.
87
+
88
+ # elif qweight_type in MMVQ_QUANT_TYPES:
89
+ # y = ops.ggml_mul_mat_vec_a8(qweight, x, qweight_type, qweight.shape[0])
90
+ # elif qweight_type in MMQ_QUANT_TYPES:
91
+ # y = ops.ggml_mul_mat_a8(qweight, x, qweight_type, qweight.shape[0])
92
+
93
+ # If there is no available MMQ kernel, fallback to dequantize
94
+ if qweight_type in DEQUANT_TYPES:
95
+ block_size, type_size = gguf.GGML_QUANT_SIZES[qweight_type]
96
+ shape = (qweight.shape[0], qweight.shape[1] // type_size * block_size)
97
+ weight = ops.ggml_dequantize(qweight, qweight_type, *shape)
98
+ y = x @ weight.to(x.dtype).T
99
+ else:
100
+ # Raise an error if the quantization type is not supported.
101
+ # Might be useful if llama.cpp adds a new quantization type.
102
+ # Wrap to GGMLQuantizationType IntEnum to make sure it's a valid type.
103
+ qweight_type = gguf.GGMLQuantizationType(qweight_type)
104
+ raise NotImplementedError(f"Unsupported GGUF quantization type: {qweight_type}")
105
+ return y.as_tensor()
106
+
107
+
108
+ # Copied from diffusers.quantizers.bitsandbytes.utils._create_accelerate_new_hook
109
+ def _create_accelerate_new_hook(old_hook):
110
+ r"""
111
+ Creates a new hook based on the old hook. Use it only if you know what you are doing ! This method is a copy of:
112
+ https://github.com/huggingface/peft/blob/748f7968f3a31ec06a1c2b0328993319ad9a150a/src/peft/utils/other.py#L245 with
113
+ some changes
114
+ """
115
+ old_hook_cls = getattr(accelerate.hooks, old_hook.__class__.__name__)
116
+ old_hook_attr = old_hook.__dict__
117
+ filtered_old_hook_attr = {}
118
+ old_hook_init_signature = inspect.signature(old_hook_cls.__init__)
119
+ for k in old_hook_attr.keys():
120
+ if k in old_hook_init_signature.parameters:
121
+ filtered_old_hook_attr[k] = old_hook_attr[k]
122
+ new_hook = old_hook_cls(**filtered_old_hook_attr)
123
+ return new_hook
124
+
125
+
126
+ def _replace_with_gguf_linear(model, compute_dtype, state_dict, prefix="", modules_to_not_convert=[]):
127
+ def _should_convert_to_gguf(state_dict, prefix):
128
+ weight_key = prefix + "weight"
129
+ return weight_key in state_dict and isinstance(state_dict[weight_key], GGUFParameter)
130
+
131
+ has_children = list(model.children())
132
+ if not has_children:
133
+ return
134
+
135
+ for name, module in model.named_children():
136
+ module_prefix = prefix + name + "."
137
+ _replace_with_gguf_linear(module, compute_dtype, state_dict, module_prefix, modules_to_not_convert)
138
+
139
+ if (
140
+ isinstance(module, nn.Linear)
141
+ and _should_convert_to_gguf(state_dict, module_prefix)
142
+ and name not in modules_to_not_convert
143
+ ):
144
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
145
+ with ctx():
146
+ model._modules[name] = GGUFLinear(
147
+ module.in_features,
148
+ module.out_features,
149
+ module.bias is not None,
150
+ compute_dtype=compute_dtype,
151
+ )
152
+ model._modules[name].source_cls = type(module)
153
+ # Force requires_grad to False to avoid unexpected errors
154
+ model._modules[name].requires_grad_(False)
155
+
156
+ return model
157
+
158
+
159
+ def _dequantize_gguf_and_restore_linear(model, modules_to_not_convert=[]):
160
+ for name, module in model.named_children():
161
+ if isinstance(module, GGUFLinear) and name not in modules_to_not_convert:
162
+ device = module.weight.device
163
+ bias = getattr(module, "bias", None)
164
+
165
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
166
+ with ctx():
167
+ new_module = nn.Linear(
168
+ module.in_features,
169
+ module.out_features,
170
+ module.bias is not None,
171
+ device=device,
172
+ )
173
+ new_module.weight = nn.Parameter(dequantize_gguf_tensor(module.weight))
174
+ if bias is not None:
175
+ new_module.bias = bias
176
+
177
+ # Create a new hook and attach it in case we use accelerate
178
+ if hasattr(module, "_hf_hook"):
179
+ old_hook = module._hf_hook
180
+ new_hook = _create_accelerate_new_hook(old_hook)
181
+
182
+ remove_hook_from_module(module)
183
+ add_hook_to_module(new_module, new_hook)
184
+
185
+ new_module.to(device)
186
+ model._modules[name] = new_module
187
+
188
+ has_children = list(module.children())
189
+ if has_children:
190
+ _dequantize_gguf_and_restore_linear(module, modules_to_not_convert)
191
+
192
+ return model
193
+
194
+
195
+ # dequantize operations based on torch ports of GGUF dequantize_functions
196
+ # from City96
197
+ # more info: https://github.com/city96/ComfyUI-GGUF/blob/main/dequant.py
198
+
199
+
200
+ QK_K = 256
201
+ K_SCALE_SIZE = 12
202
+
203
+
204
+ def to_uint32(x):
205
+ x = x.view(torch.uint8).to(torch.int32)
206
+ return (x[:, 0] | x[:, 1] << 8 | x[:, 2] << 16 | x[:, 3] << 24).unsqueeze(1)
207
+
208
+
209
+ def split_block_dims(blocks, *args):
210
+ n_max = blocks.shape[1]
211
+ dims = list(args) + [n_max - sum(args)]
212
+ return torch.split(blocks, dims, dim=1)
213
+
214
+
215
+ def get_scale_min(scales):
216
+ n_blocks = scales.shape[0]
217
+ scales = scales.view(torch.uint8)
218
+ scales = scales.reshape((n_blocks, 3, 4))
219
+
220
+ d, m, m_d = torch.split(scales, scales.shape[-2] // 3, dim=-2)
221
+
222
+ sc = torch.cat([d & 0x3F, (m_d & 0x0F) | ((d >> 2) & 0x30)], dim=-1)
223
+ min = torch.cat([m & 0x3F, (m_d >> 4) | ((m >> 2) & 0x30)], dim=-1)
224
+
225
+ return (sc.reshape((n_blocks, 8)), min.reshape((n_blocks, 8)))
226
+
227
+
228
+ def dequantize_blocks_Q8_0(blocks, block_size, type_size, dtype=None):
229
+ d, x = split_block_dims(blocks, 2)
230
+ d = d.view(torch.float16).to(dtype)
231
+ x = x.view(torch.int8)
232
+ return d * x
233
+
234
+
235
+ def dequantize_blocks_Q5_1(blocks, block_size, type_size, dtype=None):
236
+ n_blocks = blocks.shape[0]
237
+
238
+ d, m, qh, qs = split_block_dims(blocks, 2, 2, 4)
239
+ d = d.view(torch.float16).to(dtype)
240
+ m = m.view(torch.float16).to(dtype)
241
+ qh = to_uint32(qh)
242
+
243
+ qh = qh.reshape((n_blocks, 1)) >> torch.arange(32, device=d.device, dtype=torch.int32).reshape(1, 32)
244
+ ql = qs.reshape((n_blocks, -1, 1, block_size // 2)) >> torch.tensor(
245
+ [0, 4], device=d.device, dtype=torch.uint8
246
+ ).reshape(1, 1, 2, 1)
247
+ qh = (qh & 1).to(torch.uint8)
248
+ ql = (ql & 0x0F).reshape((n_blocks, -1))
249
+
250
+ qs = ql | (qh << 4)
251
+ return (d * qs) + m
252
+
253
+
254
+ def dequantize_blocks_Q5_0(blocks, block_size, type_size, dtype=None):
255
+ n_blocks = blocks.shape[0]
256
+
257
+ d, qh, qs = split_block_dims(blocks, 2, 4)
258
+ d = d.view(torch.float16).to(dtype)
259
+ qh = to_uint32(qh)
260
+
261
+ qh = qh.reshape(n_blocks, 1) >> torch.arange(32, device=d.device, dtype=torch.int32).reshape(1, 32)
262
+ ql = qs.reshape(n_blocks, -1, 1, block_size // 2) >> torch.tensor(
263
+ [0, 4], device=d.device, dtype=torch.uint8
264
+ ).reshape(1, 1, 2, 1)
265
+
266
+ qh = (qh & 1).to(torch.uint8)
267
+ ql = (ql & 0x0F).reshape(n_blocks, -1)
268
+
269
+ qs = (ql | (qh << 4)).to(torch.int8) - 16
270
+ return d * qs
271
+
272
+
273
+ def dequantize_blocks_Q4_1(blocks, block_size, type_size, dtype=None):
274
+ n_blocks = blocks.shape[0]
275
+
276
+ d, m, qs = split_block_dims(blocks, 2, 2)
277
+ d = d.view(torch.float16).to(dtype)
278
+ m = m.view(torch.float16).to(dtype)
279
+
280
+ qs = qs.reshape((n_blocks, -1, 1, block_size // 2)) >> torch.tensor(
281
+ [0, 4], device=d.device, dtype=torch.uint8
282
+ ).reshape(1, 1, 2, 1)
283
+ qs = (qs & 0x0F).reshape(n_blocks, -1)
284
+
285
+ return (d * qs) + m
286
+
287
+
288
+ def dequantize_blocks_Q4_0(blocks, block_size, type_size, dtype=None):
289
+ n_blocks = blocks.shape[0]
290
+
291
+ d, qs = split_block_dims(blocks, 2)
292
+ d = d.view(torch.float16).to(dtype)
293
+
294
+ qs = qs.reshape((n_blocks, -1, 1, block_size // 2)) >> torch.tensor(
295
+ [0, 4], device=d.device, dtype=torch.uint8
296
+ ).reshape((1, 1, 2, 1))
297
+ qs = (qs & 0x0F).reshape((n_blocks, -1)).to(torch.int8) - 8
298
+ return d * qs
299
+
300
+
301
+ def dequantize_blocks_Q6_K(blocks, block_size, type_size, dtype=None):
302
+ n_blocks = blocks.shape[0]
303
+
304
+ (
305
+ ql,
306
+ qh,
307
+ scales,
308
+ d,
309
+ ) = split_block_dims(blocks, QK_K // 2, QK_K // 4, QK_K // 16)
310
+
311
+ scales = scales.view(torch.int8).to(dtype)
312
+ d = d.view(torch.float16).to(dtype)
313
+ d = (d * scales).reshape((n_blocks, QK_K // 16, 1))
314
+
315
+ ql = ql.reshape((n_blocks, -1, 1, 64)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape(
316
+ (1, 1, 2, 1)
317
+ )
318
+ ql = (ql & 0x0F).reshape((n_blocks, -1, 32))
319
+ qh = qh.reshape((n_blocks, -1, 1, 32)) >> torch.tensor([0, 2, 4, 6], device=d.device, dtype=torch.uint8).reshape(
320
+ (1, 1, 4, 1)
321
+ )
322
+ qh = (qh & 0x03).reshape((n_blocks, -1, 32))
323
+ q = (ql | (qh << 4)).to(torch.int8) - 32
324
+ q = q.reshape((n_blocks, QK_K // 16, -1))
325
+
326
+ return (d * q).reshape((n_blocks, QK_K))
327
+
328
+
329
+ def dequantize_blocks_Q5_K(blocks, block_size, type_size, dtype=None):
330
+ n_blocks = blocks.shape[0]
331
+
332
+ d, dmin, scales, qh, qs = split_block_dims(blocks, 2, 2, K_SCALE_SIZE, QK_K // 8)
333
+
334
+ d = d.view(torch.float16).to(dtype)
335
+ dmin = dmin.view(torch.float16).to(dtype)
336
+
337
+ sc, m = get_scale_min(scales)
338
+
339
+ d = (d * sc).reshape((n_blocks, -1, 1))
340
+ dm = (dmin * m).reshape((n_blocks, -1, 1))
341
+
342
+ ql = qs.reshape((n_blocks, -1, 1, 32)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape(
343
+ (1, 1, 2, 1)
344
+ )
345
+ qh = qh.reshape((n_blocks, -1, 1, 32)) >> torch.arange(0, 8, device=d.device, dtype=torch.uint8).reshape(
346
+ (1, 1, 8, 1)
347
+ )
348
+ ql = (ql & 0x0F).reshape((n_blocks, -1, 32))
349
+ qh = (qh & 0x01).reshape((n_blocks, -1, 32))
350
+ q = ql | (qh << 4)
351
+
352
+ return (d * q - dm).reshape((n_blocks, QK_K))
353
+
354
+
355
+ def dequantize_blocks_Q4_K(blocks, block_size, type_size, dtype=None):
356
+ n_blocks = blocks.shape[0]
357
+
358
+ d, dmin, scales, qs = split_block_dims(blocks, 2, 2, K_SCALE_SIZE)
359
+ d = d.view(torch.float16).to(dtype)
360
+ dmin = dmin.view(torch.float16).to(dtype)
361
+
362
+ sc, m = get_scale_min(scales)
363
+
364
+ d = (d * sc).reshape((n_blocks, -1, 1))
365
+ dm = (dmin * m).reshape((n_blocks, -1, 1))
366
+
367
+ qs = qs.reshape((n_blocks, -1, 1, 32)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape(
368
+ (1, 1, 2, 1)
369
+ )
370
+ qs = (qs & 0x0F).reshape((n_blocks, -1, 32))
371
+
372
+ return (d * qs - dm).reshape((n_blocks, QK_K))
373
+
374
+
375
+ def dequantize_blocks_Q3_K(blocks, block_size, type_size, dtype=None):
376
+ n_blocks = blocks.shape[0]
377
+
378
+ hmask, qs, scales, d = split_block_dims(blocks, QK_K // 8, QK_K // 4, 12)
379
+ d = d.view(torch.float16).to(dtype)
380
+
381
+ lscales, hscales = scales[:, :8], scales[:, 8:]
382
+ lscales = lscales.reshape((n_blocks, 1, 8)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape(
383
+ (1, 2, 1)
384
+ )
385
+ lscales = lscales.reshape((n_blocks, 16))
386
+ hscales = hscales.reshape((n_blocks, 1, 4)) >> torch.tensor(
387
+ [0, 2, 4, 6], device=d.device, dtype=torch.uint8
388
+ ).reshape((1, 4, 1))
389
+ hscales = hscales.reshape((n_blocks, 16))
390
+ scales = (lscales & 0x0F) | ((hscales & 0x03) << 4)
391
+ scales = scales.to(torch.int8) - 32
392
+
393
+ dl = (d * scales).reshape((n_blocks, 16, 1))
394
+
395
+ ql = qs.reshape((n_blocks, -1, 1, 32)) >> torch.tensor([0, 2, 4, 6], device=d.device, dtype=torch.uint8).reshape(
396
+ (1, 1, 4, 1)
397
+ )
398
+ qh = hmask.reshape(n_blocks, -1, 1, 32) >> torch.arange(0, 8, device=d.device, dtype=torch.uint8).reshape(
399
+ (1, 1, 8, 1)
400
+ )
401
+ ql = ql.reshape((n_blocks, 16, QK_K // 16)) & 3
402
+ qh = (qh.reshape((n_blocks, 16, QK_K // 16)) & 1) ^ 1
403
+ q = ql.to(torch.int8) - (qh << 2).to(torch.int8)
404
+
405
+ return (dl * q).reshape((n_blocks, QK_K))
406
+
407
+
408
+ def dequantize_blocks_Q2_K(blocks, block_size, type_size, dtype=None):
409
+ n_blocks = blocks.shape[0]
410
+
411
+ scales, qs, d, dmin = split_block_dims(blocks, QK_K // 16, QK_K // 4, 2)
412
+ d = d.view(torch.float16).to(dtype)
413
+ dmin = dmin.view(torch.float16).to(dtype)
414
+
415
+ # (n_blocks, 16, 1)
416
+ dl = (d * (scales & 0xF)).reshape((n_blocks, QK_K // 16, 1))
417
+ ml = (dmin * (scales >> 4)).reshape((n_blocks, QK_K // 16, 1))
418
+
419
+ shift = torch.tensor([0, 2, 4, 6], device=d.device, dtype=torch.uint8).reshape((1, 1, 4, 1))
420
+
421
+ qs = (qs.reshape((n_blocks, -1, 1, 32)) >> shift) & 3
422
+ qs = qs.reshape((n_blocks, QK_K // 16, 16))
423
+ qs = dl * qs - ml
424
+
425
+ return qs.reshape((n_blocks, -1))
426
+
427
+
428
+ def dequantize_blocks_BF16(blocks, block_size, type_size, dtype=None):
429
+ return (blocks.view(torch.int16).to(torch.int32) << 16).view(torch.float32)
430
+
431
+
432
+ # this part from calcuis (gguf.org)
433
+ # more info: https://github.com/calcuis/gguf-connector/blob/main/src/gguf_connector/quant2c.py
434
+
435
+
436
+ def dequantize_blocks_IQ4_NL(blocks, block_size, type_size, dtype=None):
437
+ kvalues = torch.tensor(
438
+ [-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113],
439
+ dtype=torch.float32,
440
+ device=blocks.device,
441
+ )
442
+ n_blocks = blocks.shape[0]
443
+ d, qs = split_block_dims(blocks, 2)
444
+ d = d.view(torch.float16).to(dtype)
445
+ qs = qs.reshape((n_blocks, -1, 1, block_size // 2)) >> torch.tensor(
446
+ [0, 4], device=blocks.device, dtype=torch.uint8
447
+ ).reshape((1, 1, 2, 1))
448
+ qs = (qs & 15).reshape((n_blocks, -1)).to(torch.int64)
449
+ kvalues = kvalues.view(1, 1, 16)
450
+ qs = qs.unsqueeze(-1)
451
+ qs = torch.gather(kvalues.expand(qs.shape[0], qs.shape[1], 16), 2, qs)
452
+ qs = qs.squeeze(-1).to(dtype)
453
+ return d * qs
454
+
455
+
456
+ def dequantize_blocks_IQ4_XS(blocks, block_size, type_size, dtype=None):
457
+ kvalues = torch.tensor(
458
+ [-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113],
459
+ dtype=torch.float32,
460
+ device=blocks.device,
461
+ )
462
+ n_blocks = blocks.shape[0]
463
+ d, scales_h, scales_l, qs = split_block_dims(blocks, 2, 2, QK_K // 64)
464
+ d = d.view(torch.float16).to(dtype)
465
+ scales_h = scales_h.view(torch.int16)
466
+ scales_l = scales_l.reshape((n_blocks, -1, 1)) >> torch.tensor(
467
+ [0, 4], device=blocks.device, dtype=torch.uint8
468
+ ).reshape((1, 1, 2))
469
+ scales_h = scales_h.reshape((n_blocks, 1, -1)) >> torch.tensor(
470
+ [2 * i for i in range(QK_K // 32)], device=blocks.device, dtype=torch.uint8
471
+ ).reshape((1, -1, 1))
472
+ scales_l = scales_l.reshape((n_blocks, -1)) & 0x0F
473
+ scales_h = scales_h.reshape((n_blocks, -1)) & 0x03
474
+ scales = (scales_l | (scales_h << 4)) - 32
475
+ dl = (d * scales.to(dtype)).reshape((n_blocks, -1, 1))
476
+ shifts_q = torch.tensor([0, 4], device=blocks.device, dtype=torch.uint8).reshape(1, 1, 2, 1)
477
+ qs = qs.reshape((n_blocks, -1, 1, 16)) >> shifts_q
478
+ qs = (qs & 15).reshape((n_blocks, -1, 32)).to(torch.int64)
479
+ kvalues = kvalues.view(1, 1, 1, 16)
480
+ qs = qs.unsqueeze(-1)
481
+ qs = torch.gather(kvalues.expand(qs.shape[0], qs.shape[1], qs.shape[2], 16), 3, qs)
482
+ qs = qs.squeeze(-1).to(dtype)
483
+ return (dl * qs).reshape(n_blocks, -1)
484
+
485
+
486
+ GGML_QUANT_SIZES = gguf.GGML_QUANT_SIZES
487
+ dequantize_functions = {
488
+ gguf.GGMLQuantizationType.IQ4_NL: dequantize_blocks_IQ4_NL,
489
+ gguf.GGMLQuantizationType.IQ4_XS: dequantize_blocks_IQ4_XS,
490
+ gguf.GGMLQuantizationType.BF16: dequantize_blocks_BF16,
491
+ gguf.GGMLQuantizationType.Q8_0: dequantize_blocks_Q8_0,
492
+ gguf.GGMLQuantizationType.Q5_1: dequantize_blocks_Q5_1,
493
+ gguf.GGMLQuantizationType.Q5_0: dequantize_blocks_Q5_0,
494
+ gguf.GGMLQuantizationType.Q4_1: dequantize_blocks_Q4_1,
495
+ gguf.GGMLQuantizationType.Q4_0: dequantize_blocks_Q4_0,
496
+ gguf.GGMLQuantizationType.Q6_K: dequantize_blocks_Q6_K,
497
+ gguf.GGMLQuantizationType.Q5_K: dequantize_blocks_Q5_K,
498
+ gguf.GGMLQuantizationType.Q4_K: dequantize_blocks_Q4_K,
499
+ gguf.GGMLQuantizationType.Q3_K: dequantize_blocks_Q3_K,
500
+ gguf.GGMLQuantizationType.Q2_K: dequantize_blocks_Q2_K,
501
+ }
502
+ SUPPORTED_GGUF_QUANT_TYPES = list(dequantize_functions.keys())
503
+
504
+
505
+ def _quant_shape_from_byte_shape(shape, type_size, block_size):
506
+ return (*shape[:-1], shape[-1] // type_size * block_size)
507
+
508
+
509
+ def dequantize_gguf_tensor(tensor):
510
+ if not hasattr(tensor, "quant_type"):
511
+ return tensor
512
+
513
+ quant_type = tensor.quant_type
514
+ dequant_fn = dequantize_functions[quant_type]
515
+
516
+ block_size, type_size = GGML_QUANT_SIZES[quant_type]
517
+
518
+ tensor = tensor.view(torch.uint8)
519
+ shape = _quant_shape_from_byte_shape(tensor.shape, type_size, block_size)
520
+
521
+ n_blocks = tensor.numel() // type_size
522
+ blocks = tensor.reshape((n_blocks, type_size))
523
+
524
+ dequant = dequant_fn(blocks, block_size, type_size)
525
+ dequant = dequant.reshape(shape)
526
+
527
+ return dequant.as_tensor()
528
+
529
+
530
+ class GGUFParameter(torch.nn.Parameter):
531
+ def __new__(cls, data, requires_grad=False, quant_type=None):
532
+ data = data if data is not None else torch.empty(0)
533
+ self = torch.Tensor._make_subclass(cls, data, requires_grad)
534
+ self.quant_type = quant_type
535
+ block_size, type_size = GGML_QUANT_SIZES[quant_type]
536
+ self.quant_shape = _quant_shape_from_byte_shape(self.shape, type_size, block_size)
537
+
538
+ return self
539
+
540
+ def as_tensor(self):
541
+ return torch.Tensor._make_subclass(torch.Tensor, self, self.requires_grad)
542
+
543
+ @staticmethod
544
+ def _extract_quant_type(args):
545
+ # When converting from original format checkpoints we often use splits, cats etc on tensors
546
+ # this method ensures that the returned tensor type from those operations remains GGUFParameter
547
+ # so that we preserve quant_type information
548
+ for arg in args:
549
+ if isinstance(arg, list) and isinstance(arg[0], GGUFParameter):
550
+ return arg[0].quant_type
551
+ if isinstance(arg, GGUFParameter):
552
+ return arg.quant_type
553
+ return None
554
+
555
+ @classmethod
556
+ def __torch_function__(cls, func, types, args=(), kwargs=None):
557
+ if kwargs is None:
558
+ kwargs = {}
559
+
560
+ result = super().__torch_function__(func, types, args, kwargs)
561
+
562
+ if isinstance(result, torch.Tensor):
563
+ quant_type = cls._extract_quant_type(args)
564
+ return cls(result, quant_type=quant_type)
565
+ # Handle tuples and lists
566
+ elif type(result) in (list, tuple):
567
+ # Preserve the original type (tuple or list)
568
+ quant_type = cls._extract_quant_type(args)
569
+ wrapped = [cls(x, quant_type=quant_type) if isinstance(x, torch.Tensor) else x for x in result]
570
+ return type(result)(wrapped)
571
+ else:
572
+ return result
573
+
574
+
575
+ class GGUFLinear(nn.Linear):
576
+ def __init__(
577
+ self,
578
+ in_features,
579
+ out_features,
580
+ bias=False,
581
+ compute_dtype=None,
582
+ device=None,
583
+ ) -> None:
584
+ super().__init__(in_features, out_features, bias, device)
585
+ self.compute_dtype = compute_dtype
586
+ self.device = device
587
+
588
+ def forward(self, inputs: torch.Tensor):
589
+ if ops is not None and self.weight.is_cuda and inputs.is_cuda:
590
+ return self.forward_cuda(inputs)
591
+ return self.forward_native(inputs)
592
+
593
+ def forward_native(self, inputs: torch.Tensor):
594
+ weight = dequantize_gguf_tensor(self.weight)
595
+ weight = weight.to(self.compute_dtype)
596
+ bias = self.bias.to(self.compute_dtype) if self.bias is not None else None
597
+
598
+ output = torch.nn.functional.linear(inputs, weight, bias)
599
+ return output
600
+
601
+ def forward_cuda(self, inputs: torch.Tensor):
602
+ quant_type = self.weight.quant_type
603
+ output = _fused_mul_mat_gguf(inputs.to(self.compute_dtype), self.weight, quant_type)
604
+ if self.bias is not None:
605
+ output += self.bias.to(self.compute_dtype)
606
+ return output
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/modelopt/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .modelopt_quantizer import NVIDIAModelOptQuantizer
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/modelopt/modelopt_quantizer.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING, Any, Dict, List, Union
2
+
3
+ from ...utils import (
4
+ get_module_from_name,
5
+ is_accelerate_available,
6
+ is_nvidia_modelopt_available,
7
+ is_torch_available,
8
+ logging,
9
+ )
10
+ from ..base import DiffusersQuantizer
11
+
12
+
13
+ if TYPE_CHECKING:
14
+ from ...models.modeling_utils import ModelMixin
15
+
16
+
17
+ if is_torch_available():
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ if is_accelerate_available():
22
+ from accelerate.utils import set_module_tensor_to_device
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ class NVIDIAModelOptQuantizer(DiffusersQuantizer):
29
+ r"""
30
+ Diffusers Quantizer for TensorRT Model Optimizer
31
+ """
32
+
33
+ use_keep_in_fp32_modules = True
34
+ requires_calibration = False
35
+ required_packages = ["nvidia_modelopt"]
36
+
37
+ def __init__(self, quantization_config, **kwargs):
38
+ super().__init__(quantization_config, **kwargs)
39
+
40
+ def validate_environment(self, *args, **kwargs):
41
+ if not is_nvidia_modelopt_available():
42
+ raise ImportError(
43
+ "Loading an nvidia-modelopt quantized model requires nvidia-modelopt library (`pip install nvidia-modelopt`)"
44
+ )
45
+
46
+ self.offload = False
47
+
48
+ device_map = kwargs.get("device_map", None)
49
+ if isinstance(device_map, dict):
50
+ if "cpu" in device_map.values() or "disk" in device_map.values():
51
+ if self.pre_quantized:
52
+ raise ValueError(
53
+ "You are attempting to perform cpu/disk offload with a pre-quantized modelopt model "
54
+ "This is not supported yet. Please remove the CPU or disk device from the `device_map` argument."
55
+ )
56
+ else:
57
+ self.offload = True
58
+
59
+ def check_if_quantized_param(
60
+ self,
61
+ model: "ModelMixin",
62
+ param_value: "torch.Tensor",
63
+ param_name: str,
64
+ state_dict: Dict[str, Any],
65
+ **kwargs,
66
+ ):
67
+ # ModelOpt imports diffusers internally. This is here to prevent circular imports
68
+ from modelopt.torch.quantization.utils import is_quantized
69
+
70
+ module, tensor_name = get_module_from_name(model, param_name)
71
+ if self.pre_quantized:
72
+ return True
73
+ elif is_quantized(module) and "weight" in tensor_name:
74
+ return True
75
+ return False
76
+
77
+ def create_quantized_param(
78
+ self,
79
+ model: "ModelMixin",
80
+ param_value: "torch.Tensor",
81
+ param_name: str,
82
+ target_device: "torch.device",
83
+ *args,
84
+ **kwargs,
85
+ ):
86
+ """
87
+ Create the quantized parameter by calling .calibrate() after setting it to the module.
88
+ """
89
+ # ModelOpt imports diffusers internally. This is here to prevent circular imports
90
+ import modelopt.torch.quantization as mtq
91
+
92
+ dtype = kwargs.get("dtype", torch.float32)
93
+ module, tensor_name = get_module_from_name(model, param_name)
94
+ if self.pre_quantized:
95
+ module._parameters[tensor_name] = torch.nn.Parameter(param_value.to(device=target_device))
96
+ else:
97
+ set_module_tensor_to_device(model, param_name, target_device, param_value, dtype)
98
+ mtq.calibrate(
99
+ module, self.quantization_config.modelopt_config["algorithm"], self.quantization_config.forward_loop
100
+ )
101
+ mtq.compress(module)
102
+ module.weight.requires_grad = False
103
+
104
+ def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]:
105
+ max_memory = {key: val * 0.90 for key, val in max_memory.items()}
106
+ return max_memory
107
+
108
+ def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype":
109
+ if self.quantization_config.quant_type == "FP8":
110
+ target_dtype = torch.float8_e4m3fn
111
+ return target_dtype
112
+
113
+ def update_torch_dtype(self, torch_dtype: "torch.dtype" = None) -> "torch.dtype":
114
+ if torch_dtype is None:
115
+ logger.info("You did not specify `torch_dtype` in `from_pretrained`. Setting it to `torch.float32`.")
116
+ torch_dtype = torch.float32
117
+ return torch_dtype
118
+
119
+ def get_conv_param_names(self, model: "ModelMixin") -> List[str]:
120
+ """
121
+ Get parameter names for all convolutional layers in a HuggingFace ModelMixin. Includes Conv1d/2d/3d and
122
+ ConvTranspose1d/2d/3d.
123
+ """
124
+ conv_types = (
125
+ nn.Conv1d,
126
+ nn.Conv2d,
127
+ nn.Conv3d,
128
+ nn.ConvTranspose1d,
129
+ nn.ConvTranspose2d,
130
+ nn.ConvTranspose3d,
131
+ )
132
+
133
+ conv_param_names = []
134
+ for name, module in model.named_modules():
135
+ if isinstance(module, conv_types):
136
+ for param_name, _ in module.named_parameters(recurse=False):
137
+ conv_param_names.append(f"{name}.{param_name}")
138
+
139
+ return conv_param_names
140
+
141
+ def _process_model_before_weight_loading(
142
+ self,
143
+ model: "ModelMixin",
144
+ device_map,
145
+ keep_in_fp32_modules: List[str] = [],
146
+ **kwargs,
147
+ ):
148
+ # ModelOpt imports diffusers internally. This is here to prevent circular imports
149
+ import modelopt.torch.opt as mto
150
+
151
+ if self.pre_quantized:
152
+ return
153
+
154
+ modules_to_not_convert = self.quantization_config.modules_to_not_convert
155
+
156
+ if modules_to_not_convert is None:
157
+ modules_to_not_convert = []
158
+ if isinstance(modules_to_not_convert, str):
159
+ modules_to_not_convert = [modules_to_not_convert]
160
+ modules_to_not_convert.extend(keep_in_fp32_modules)
161
+ if self.quantization_config.disable_conv_quantization:
162
+ modules_to_not_convert.extend(self.get_conv_param_names(model))
163
+
164
+ for module in modules_to_not_convert:
165
+ self.quantization_config.modelopt_config["quant_cfg"]["*" + module + "*"] = {"enable": False}
166
+ self.quantization_config.modules_to_not_convert = modules_to_not_convert
167
+ mto.apply_mode(model, mode=[("quantize", self.quantization_config.modelopt_config)])
168
+ model.config.quantization_config = self.quantization_config
169
+
170
+ def _process_model_after_weight_loading(self, model, **kwargs):
171
+ # ModelOpt imports diffusers internally. This is here to prevent circular imports
172
+ from modelopt.torch.opt import ModeloptStateManager
173
+
174
+ if self.pre_quantized:
175
+ return model
176
+
177
+ for _, m in model.named_modules():
178
+ if hasattr(m, ModeloptStateManager._state_key) and m is not model:
179
+ ModeloptStateManager.remove_state(m)
180
+
181
+ return model
182
+
183
+ @property
184
+ def is_trainable(self):
185
+ return True
186
+
187
+ @property
188
+ def is_serializable(self):
189
+ self.quantization_config.check_model_patching(operation="saving")
190
+ return True
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/pipe_quant_config.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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 Dict, List, Optional, Union
17
+
18
+ from ..utils import is_transformers_available, logging
19
+ from .quantization_config import QuantizationConfigMixin as DiffQuantConfigMixin
20
+
21
+
22
+ try:
23
+ from transformers.utils.quantization_config import QuantizationConfigMixin as TransformersQuantConfigMixin
24
+ except ImportError:
25
+
26
+ class TransformersQuantConfigMixin:
27
+ pass
28
+
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+
33
+ class PipelineQuantizationConfig:
34
+ """
35
+ Configuration class to be used when applying quantization on-the-fly to [`~DiffusionPipeline.from_pretrained`].
36
+
37
+ Args:
38
+ quant_backend (`str`): Quantization backend to be used. When using this option, we assume that the backend
39
+ is available to both `diffusers` and `transformers`.
40
+ quant_kwargs (`dict`): Params to initialize the quantization backend class.
41
+ components_to_quantize (`list`): Components of a pipeline to be quantized.
42
+ quant_mapping (`dict`): Mapping defining the quantization specs to be used for the pipeline
43
+ components. When using this argument, users are not expected to provide `quant_backend`, `quant_kawargs`,
44
+ and `components_to_quantize`.
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ quant_backend: str = None,
50
+ quant_kwargs: Dict[str, Union[str, float, int, dict]] = None,
51
+ components_to_quantize: Optional[Union[List[str], str]] = None,
52
+ quant_mapping: Dict[str, Union[DiffQuantConfigMixin, "TransformersQuantConfigMixin"]] = None,
53
+ ):
54
+ self.quant_backend = quant_backend
55
+ # Initialize kwargs to be {} to set to the defaults.
56
+ self.quant_kwargs = quant_kwargs or {}
57
+ if components_to_quantize:
58
+ if isinstance(components_to_quantize, str):
59
+ components_to_quantize = [components_to_quantize]
60
+ self.components_to_quantize = components_to_quantize
61
+ self.quant_mapping = quant_mapping
62
+ self.config_mapping = {} # book-keeping Example: `{module_name: quant_config}`
63
+ self.post_init()
64
+
65
+ def post_init(self):
66
+ quant_mapping = self.quant_mapping
67
+ self.is_granular = True if quant_mapping is not None else False
68
+
69
+ self._validate_init_args()
70
+
71
+ def _validate_init_args(self):
72
+ if self.quant_backend and self.quant_mapping:
73
+ raise ValueError("Both `quant_backend` and `quant_mapping` cannot be specified at the same time.")
74
+
75
+ if not self.quant_mapping and not self.quant_backend:
76
+ raise ValueError("Must provide a `quant_backend` when not providing a `quant_mapping`.")
77
+
78
+ if not self.quant_kwargs and not self.quant_mapping:
79
+ raise ValueError("Both `quant_kwargs` and `quant_mapping` cannot be None.")
80
+
81
+ if self.quant_backend is not None:
82
+ self._validate_init_kwargs_in_backends()
83
+
84
+ if self.quant_mapping is not None:
85
+ self._validate_quant_mapping_args()
86
+
87
+ def _validate_init_kwargs_in_backends(self):
88
+ quant_backend = self.quant_backend
89
+
90
+ self._check_backend_availability(quant_backend)
91
+
92
+ quant_config_mapping_transformers, quant_config_mapping_diffusers = self._get_quant_config_list()
93
+
94
+ if quant_config_mapping_transformers is not None:
95
+ init_kwargs_transformers = inspect.signature(quant_config_mapping_transformers[quant_backend].__init__)
96
+ init_kwargs_transformers = {name for name in init_kwargs_transformers.parameters if name != "self"}
97
+ else:
98
+ init_kwargs_transformers = None
99
+
100
+ init_kwargs_diffusers = inspect.signature(quant_config_mapping_diffusers[quant_backend].__init__)
101
+ init_kwargs_diffusers = {name for name in init_kwargs_diffusers.parameters if name != "self"}
102
+
103
+ if init_kwargs_transformers != init_kwargs_diffusers:
104
+ raise ValueError(
105
+ "The signatures of the __init__ methods of the quantization config classes in `diffusers` and `transformers` don't match. "
106
+ f"Please provide a `quant_mapping` instead, in the {self.__class__.__name__} class. Refer to [the docs](https://huggingface.co/docs/diffusers/main/en/quantization/overview#pipeline-level-quantization) to learn more about how "
107
+ "this mapping would look like."
108
+ )
109
+
110
+ def _validate_quant_mapping_args(self):
111
+ quant_mapping = self.quant_mapping
112
+ transformers_map, diffusers_map = self._get_quant_config_list()
113
+
114
+ available_transformers = list(transformers_map.values()) if transformers_map else None
115
+ available_diffusers = list(diffusers_map.values())
116
+
117
+ for module_name, config in quant_mapping.items():
118
+ if any(isinstance(config, cfg) for cfg in available_diffusers):
119
+ continue
120
+
121
+ if available_transformers and any(isinstance(config, cfg) for cfg in available_transformers):
122
+ continue
123
+
124
+ if available_transformers:
125
+ raise ValueError(
126
+ f"Provided config for module_name={module_name} could not be found. "
127
+ f"Available diffusers configs: {available_diffusers}; "
128
+ f"Available transformers configs: {available_transformers}."
129
+ )
130
+ else:
131
+ raise ValueError(
132
+ f"Provided config for module_name={module_name} could not be found. "
133
+ f"Available diffusers configs: {available_diffusers}."
134
+ )
135
+
136
+ def _check_backend_availability(self, quant_backend: str):
137
+ quant_config_mapping_transformers, quant_config_mapping_diffusers = self._get_quant_config_list()
138
+
139
+ available_backends_transformers = (
140
+ list(quant_config_mapping_transformers.keys()) if quant_config_mapping_transformers else None
141
+ )
142
+ available_backends_diffusers = list(quant_config_mapping_diffusers.keys())
143
+
144
+ if (
145
+ available_backends_transformers and quant_backend not in available_backends_transformers
146
+ ) or quant_backend not in quant_config_mapping_diffusers:
147
+ error_message = f"Provided quant_backend={quant_backend} was not found."
148
+ if available_backends_transformers:
149
+ error_message += f"\nAvailable ones (transformers): {available_backends_transformers}."
150
+ error_message += f"\nAvailable ones (diffusers): {available_backends_diffusers}."
151
+ raise ValueError(error_message)
152
+
153
+ def _resolve_quant_config(self, is_diffusers: bool = True, module_name: str = None):
154
+ quant_config_mapping_transformers, quant_config_mapping_diffusers = self._get_quant_config_list()
155
+
156
+ quant_mapping = self.quant_mapping
157
+ components_to_quantize = self.components_to_quantize
158
+
159
+ # Granular case
160
+ if self.is_granular and module_name in quant_mapping:
161
+ logger.debug(f"Initializing quantization config class for {module_name}.")
162
+ config = quant_mapping[module_name]
163
+ self.config_mapping.update({module_name: config})
164
+ return config
165
+
166
+ # Global config case
167
+ else:
168
+ should_quantize = False
169
+ # Only quantize the modules requested for.
170
+ if components_to_quantize and module_name in components_to_quantize:
171
+ should_quantize = True
172
+ # No specification for `components_to_quantize` means all modules should be quantized.
173
+ elif not self.is_granular and not components_to_quantize:
174
+ should_quantize = True
175
+
176
+ if should_quantize:
177
+ logger.debug(f"Initializing quantization config class for {module_name}.")
178
+ mapping_to_use = quant_config_mapping_diffusers if is_diffusers else quant_config_mapping_transformers
179
+ quant_config_cls = mapping_to_use[self.quant_backend]
180
+ quant_kwargs = self.quant_kwargs
181
+ quant_obj = quant_config_cls(**quant_kwargs)
182
+ self.config_mapping.update({module_name: quant_obj})
183
+ return quant_obj
184
+
185
+ # Fallback: no applicable configuration found.
186
+ return None
187
+
188
+ def _get_quant_config_list(self):
189
+ if is_transformers_available():
190
+ from transformers.quantizers.auto import (
191
+ AUTO_QUANTIZATION_CONFIG_MAPPING as quant_config_mapping_transformers,
192
+ )
193
+ else:
194
+ quant_config_mapping_transformers = None
195
+
196
+ from ..quantizers.auto import AUTO_QUANTIZATION_CONFIG_MAPPING as quant_config_mapping_diffusers
197
+
198
+ return quant_config_mapping_transformers, quant_config_mapping_diffusers
199
+
200
+ def __repr__(self):
201
+ out = ""
202
+ config_mapping = dict(sorted(self.config_mapping.copy().items()))
203
+ for module_name, config in config_mapping.items():
204
+ out += f"{module_name} {config}"
205
+ return out
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/quantization_config.py ADDED
@@ -0,0 +1,1038 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+
4
+ # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """
19
+ Adapted from
20
+ https://github.com/huggingface/transformers/blob/52cb4034ada381fe1ffe8d428a1076e5411a8026/src/transformers/utils/quantization_config.py
21
+ """
22
+
23
+ import copy
24
+ import dataclasses
25
+ import importlib.metadata
26
+ import inspect
27
+ import json
28
+ import os
29
+ import warnings
30
+ from dataclasses import dataclass, is_dataclass
31
+ from enum import Enum
32
+ from functools import partial
33
+ from typing import Any, Callable, Dict, List, Optional, Union
34
+
35
+ from packaging import version
36
+
37
+ from ..utils import is_torch_available, is_torchao_available, is_torchao_version, logging
38
+
39
+
40
+ if is_torch_available():
41
+ import torch
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ class QuantizationMethod(str, Enum):
47
+ BITS_AND_BYTES = "bitsandbytes"
48
+ GGUF = "gguf"
49
+ TORCHAO = "torchao"
50
+ QUANTO = "quanto"
51
+ MODELOPT = "modelopt"
52
+
53
+
54
+ if is_torchao_available():
55
+ from torchao.quantization.quant_primitives import MappingType
56
+
57
+ class TorchAoJSONEncoder(json.JSONEncoder):
58
+ def default(self, obj):
59
+ if isinstance(obj, MappingType):
60
+ return obj.name
61
+ return super().default(obj)
62
+
63
+
64
+ @dataclass
65
+ class QuantizationConfigMixin:
66
+ """
67
+ Mixin class for quantization config
68
+ """
69
+
70
+ quant_method: QuantizationMethod
71
+ _exclude_attributes_at_init = []
72
+
73
+ @classmethod
74
+ def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs):
75
+ """
76
+ Instantiates a [`QuantizationConfigMixin`] from a Python dictionary of parameters.
77
+
78
+ Args:
79
+ config_dict (`Dict[str, Any]`):
80
+ Dictionary that will be used to instantiate the configuration object.
81
+ return_unused_kwargs (`bool`, *optional*, defaults to `False`):
82
+ Whether or not to return a list of unused keyword arguments. Used for `from_pretrained` method in
83
+ `PreTrainedModel`.
84
+ kwargs (`Dict[str, Any]`):
85
+ Additional parameters from which to initialize the configuration object.
86
+
87
+ Returns:
88
+ [`QuantizationConfigMixin`]: The configuration object instantiated from those parameters.
89
+ """
90
+
91
+ config = cls(**config_dict)
92
+
93
+ to_remove = []
94
+ for key, value in kwargs.items():
95
+ if hasattr(config, key):
96
+ setattr(config, key, value)
97
+ to_remove.append(key)
98
+ for key in to_remove:
99
+ kwargs.pop(key, None)
100
+
101
+ if return_unused_kwargs:
102
+ return config, kwargs
103
+ else:
104
+ return config
105
+
106
+ def to_json_file(self, json_file_path: Union[str, os.PathLike]):
107
+ """
108
+ Save this instance to a JSON file.
109
+
110
+ Args:
111
+ json_file_path (`str` or `os.PathLike`):
112
+ Path to the JSON file in which this configuration instance's parameters will be saved.
113
+ use_diff (`bool`, *optional*, defaults to `True`):
114
+ If set to `True`, only the difference between the config instance and the default
115
+ `QuantizationConfig()` is serialized to JSON file.
116
+ """
117
+ with open(json_file_path, "w", encoding="utf-8") as writer:
118
+ config_dict = self.to_dict()
119
+ json_string = json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
120
+
121
+ writer.write(json_string)
122
+
123
+ def to_dict(self) -> Dict[str, Any]:
124
+ """
125
+ Serializes this instance to a Python dictionary. Returns:
126
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
127
+ """
128
+ return copy.deepcopy(self.__dict__)
129
+
130
+ def __iter__(self):
131
+ """allows `dict(obj)` for situations where obj may be a dict or QuantizationConfigMixin"""
132
+ for attr, value in copy.deepcopy(self.__dict__).items():
133
+ yield attr, value
134
+
135
+ def __repr__(self):
136
+ return f"{self.__class__.__name__} {self.to_json_string()}"
137
+
138
+ def to_json_string(self, use_diff: bool = True) -> str:
139
+ """
140
+ Serializes this instance to a JSON string.
141
+
142
+ Args:
143
+ use_diff (`bool`, *optional*, defaults to `True`):
144
+ If set to `True`, only the difference between the config instance and the default `PretrainedConfig()`
145
+ is serialized to JSON string.
146
+
147
+ Returns:
148
+ `str`: String containing all the attributes that make up this configuration instance in JSON format.
149
+ """
150
+ if use_diff is True:
151
+ config_dict = self.to_diff_dict()
152
+ else:
153
+ config_dict = self.to_dict()
154
+ return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
155
+
156
+ def update(self, **kwargs):
157
+ """
158
+ Updates attributes of this class instance with attributes from `kwargs` if they match existing attributes,
159
+ returning all the unused kwargs.
160
+
161
+ Args:
162
+ kwargs (`Dict[str, Any]`):
163
+ Dictionary of attributes to tentatively update this class.
164
+
165
+ Returns:
166
+ `Dict[str, Any]`: Dictionary containing all the key-value pairs that were not used to update the instance.
167
+ """
168
+ to_remove = []
169
+ for key, value in kwargs.items():
170
+ if hasattr(self, key):
171
+ setattr(self, key, value)
172
+ to_remove.append(key)
173
+
174
+ # Remove all the attributes that were updated, without modifying the input dict
175
+ unused_kwargs = {key: value for key, value in kwargs.items() if key not in to_remove}
176
+ return unused_kwargs
177
+
178
+
179
+ @dataclass
180
+ class BitsAndBytesConfig(QuantizationConfigMixin):
181
+ """
182
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
183
+ loaded using `bitsandbytes`.
184
+
185
+ This replaces `load_in_8bit` or `load_in_4bit` therefore both options are mutually exclusive.
186
+
187
+ Currently only supports `LLM.int8()`, `FP4`, and `NF4` quantization. If more methods are added to `bitsandbytes`,
188
+ then more arguments will be added to this class.
189
+
190
+ Args:
191
+ load_in_8bit (`bool`, *optional*, defaults to `False`):
192
+ This flag is used to enable 8-bit quantization with LLM.int8().
193
+ load_in_4bit (`bool`, *optional*, defaults to `False`):
194
+ This flag is used to enable 4-bit quantization by replacing the Linear layers with FP4/NF4 layers from
195
+ `bitsandbytes`.
196
+ llm_int8_threshold (`float`, *optional*, defaults to 6.0):
197
+ This corresponds to the outlier threshold for outlier detection as described in `LLM.int8() : 8-bit Matrix
198
+ Multiplication for Transformers at Scale` paper: https://huggingface.co/papers/2208.07339 Any hidden states
199
+ value that is above this threshold will be considered an outlier and the operation on those values will be
200
+ done in fp16. Values are usually normally distributed, that is, most values are in the range [-3.5, 3.5],
201
+ but there are some exceptional systematic outliers that are very differently distributed for large models.
202
+ These outliers are often in the interval [-60, -6] or [6, 60]. Int8 quantization works well for values of
203
+ magnitude ~5, but beyond that, there is a significant performance penalty. A good default threshold is 6,
204
+ but a lower threshold might be needed for more unstable models (small models, fine-tuning).
205
+ llm_int8_skip_modules (`List[str]`, *optional*):
206
+ An explicit list of the modules that we do not want to convert in 8-bit. This is useful for models such as
207
+ Jukebox that has several heads in different places and not necessarily at the last position. For example
208
+ for `CausalLM` models, the last `lm_head` is typically kept in its original `dtype`.
209
+ llm_int8_enable_fp32_cpu_offload (`bool`, *optional*, defaults to `False`):
210
+ This flag is used for advanced use cases and users that are aware of this feature. If you want to split
211
+ your model in different parts and run some parts in int8 on GPU and some parts in fp32 on CPU, you can use
212
+ this flag. This is useful for offloading large models such as `google/flan-t5-xxl`. Note that the int8
213
+ operations will not be run on CPU.
214
+ llm_int8_has_fp16_weight (`bool`, *optional*, defaults to `False`):
215
+ This flag runs LLM.int8() with 16-bit main weights. This is useful for fine-tuning as the weights do not
216
+ have to be converted back and forth for the backward pass.
217
+ bnb_4bit_compute_dtype (`torch.dtype` or str, *optional*, defaults to `torch.float32`):
218
+ This sets the computational type which might be different than the input type. For example, inputs might be
219
+ fp32, but computation can be set to bf16 for speedups.
220
+ bnb_4bit_quant_type (`str`, *optional*, defaults to `"fp4"`):
221
+ This sets the quantization data type in the bnb.nn.Linear4Bit layers. Options are FP4 and NF4 data types
222
+ which are specified by `fp4` or `nf4`.
223
+ bnb_4bit_use_double_quant (`bool`, *optional*, defaults to `False`):
224
+ This flag is used for nested quantization where the quantization constants from the first quantization are
225
+ quantized again.
226
+ bnb_4bit_quant_storage (`torch.dtype` or str, *optional*, defaults to `torch.uint8`):
227
+ This sets the storage type to pack the quanitzed 4-bit prarams.
228
+ kwargs (`Dict[str, Any]`, *optional*):
229
+ Additional parameters from which to initialize the configuration object.
230
+ """
231
+
232
+ _exclude_attributes_at_init = ["_load_in_4bit", "_load_in_8bit", "quant_method"]
233
+
234
+ def __init__(
235
+ self,
236
+ load_in_8bit=False,
237
+ load_in_4bit=False,
238
+ llm_int8_threshold=6.0,
239
+ llm_int8_skip_modules=None,
240
+ llm_int8_enable_fp32_cpu_offload=False,
241
+ llm_int8_has_fp16_weight=False,
242
+ bnb_4bit_compute_dtype=None,
243
+ bnb_4bit_quant_type="fp4",
244
+ bnb_4bit_use_double_quant=False,
245
+ bnb_4bit_quant_storage=None,
246
+ **kwargs,
247
+ ):
248
+ self.quant_method = QuantizationMethod.BITS_AND_BYTES
249
+
250
+ if load_in_4bit and load_in_8bit:
251
+ raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
252
+
253
+ self._load_in_8bit = load_in_8bit
254
+ self._load_in_4bit = load_in_4bit
255
+ self.llm_int8_threshold = llm_int8_threshold
256
+ self.llm_int8_skip_modules = llm_int8_skip_modules
257
+ self.llm_int8_enable_fp32_cpu_offload = llm_int8_enable_fp32_cpu_offload
258
+ self.llm_int8_has_fp16_weight = llm_int8_has_fp16_weight
259
+ self.bnb_4bit_quant_type = bnb_4bit_quant_type
260
+ self.bnb_4bit_use_double_quant = bnb_4bit_use_double_quant
261
+
262
+ if bnb_4bit_compute_dtype is None:
263
+ self.bnb_4bit_compute_dtype = torch.float32
264
+ elif isinstance(bnb_4bit_compute_dtype, str):
265
+ self.bnb_4bit_compute_dtype = getattr(torch, bnb_4bit_compute_dtype)
266
+ elif isinstance(bnb_4bit_compute_dtype, torch.dtype):
267
+ self.bnb_4bit_compute_dtype = bnb_4bit_compute_dtype
268
+ else:
269
+ raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype")
270
+
271
+ if bnb_4bit_quant_storage is None:
272
+ self.bnb_4bit_quant_storage = torch.uint8
273
+ elif isinstance(bnb_4bit_quant_storage, str):
274
+ if bnb_4bit_quant_storage not in [
275
+ "float16",
276
+ "float32",
277
+ "int8",
278
+ "uint8",
279
+ "float64",
280
+ "bfloat16",
281
+ ]:
282
+ raise ValueError(
283
+ "`bnb_4bit_quant_storage` must be a valid string (one of 'float16', 'float32', 'int8', 'uint8', 'float64', 'bfloat16') "
284
+ )
285
+ self.bnb_4bit_quant_storage = getattr(torch, bnb_4bit_quant_storage)
286
+ elif isinstance(bnb_4bit_quant_storage, torch.dtype):
287
+ self.bnb_4bit_quant_storage = bnb_4bit_quant_storage
288
+ else:
289
+ raise ValueError("bnb_4bit_quant_storage must be a string or a torch.dtype")
290
+
291
+ if kwargs and not all(k in self._exclude_attributes_at_init for k in kwargs):
292
+ logger.warning(f"Unused kwargs: {list(kwargs.keys())}. These kwargs are not used in {self.__class__}.")
293
+
294
+ self.post_init()
295
+
296
+ @property
297
+ def load_in_4bit(self):
298
+ return self._load_in_4bit
299
+
300
+ @load_in_4bit.setter
301
+ def load_in_4bit(self, value: bool):
302
+ if not isinstance(value, bool):
303
+ raise TypeError("load_in_4bit must be a boolean")
304
+
305
+ if self.load_in_8bit and value:
306
+ raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
307
+ self._load_in_4bit = value
308
+
309
+ @property
310
+ def load_in_8bit(self):
311
+ return self._load_in_8bit
312
+
313
+ @load_in_8bit.setter
314
+ def load_in_8bit(self, value: bool):
315
+ if not isinstance(value, bool):
316
+ raise TypeError("load_in_8bit must be a boolean")
317
+
318
+ if self.load_in_4bit and value:
319
+ raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
320
+ self._load_in_8bit = value
321
+
322
+ def post_init(self):
323
+ r"""
324
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
325
+ """
326
+ if not isinstance(self.load_in_4bit, bool):
327
+ raise TypeError("load_in_4bit must be a boolean")
328
+
329
+ if not isinstance(self.load_in_8bit, bool):
330
+ raise TypeError("load_in_8bit must be a boolean")
331
+
332
+ if not isinstance(self.llm_int8_threshold, float):
333
+ raise TypeError("llm_int8_threshold must be a float")
334
+
335
+ if self.llm_int8_skip_modules is not None and not isinstance(self.llm_int8_skip_modules, list):
336
+ raise TypeError("llm_int8_skip_modules must be a list of strings")
337
+ if not isinstance(self.llm_int8_enable_fp32_cpu_offload, bool):
338
+ raise TypeError("llm_int8_enable_fp32_cpu_offload must be a boolean")
339
+
340
+ if not isinstance(self.llm_int8_has_fp16_weight, bool):
341
+ raise TypeError("llm_int8_has_fp16_weight must be a boolean")
342
+
343
+ if self.bnb_4bit_compute_dtype is not None and not isinstance(self.bnb_4bit_compute_dtype, torch.dtype):
344
+ raise TypeError("bnb_4bit_compute_dtype must be torch.dtype")
345
+
346
+ if not isinstance(self.bnb_4bit_quant_type, str):
347
+ raise TypeError("bnb_4bit_quant_type must be a string")
348
+
349
+ if not isinstance(self.bnb_4bit_use_double_quant, bool):
350
+ raise TypeError("bnb_4bit_use_double_quant must be a boolean")
351
+
352
+ if self.load_in_4bit and not version.parse(importlib.metadata.version("bitsandbytes")) >= version.parse(
353
+ "0.39.0"
354
+ ):
355
+ raise ValueError(
356
+ "4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version"
357
+ )
358
+
359
+ def is_quantizable(self):
360
+ r"""
361
+ Returns `True` if the model is quantizable, `False` otherwise.
362
+ """
363
+ return self.load_in_8bit or self.load_in_4bit
364
+
365
+ def quantization_method(self):
366
+ r"""
367
+ This method returns the quantization method used for the model. If the model is not quantizable, it returns
368
+ `None`.
369
+ """
370
+ if self.load_in_8bit:
371
+ return "llm_int8"
372
+ elif self.load_in_4bit and self.bnb_4bit_quant_type == "fp4":
373
+ return "fp4"
374
+ elif self.load_in_4bit and self.bnb_4bit_quant_type == "nf4":
375
+ return "nf4"
376
+ else:
377
+ return None
378
+
379
+ def to_dict(self) -> Dict[str, Any]:
380
+ """
381
+ Serializes this instance to a Python dictionary. Returns:
382
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
383
+ """
384
+ output = copy.deepcopy(self.__dict__)
385
+ output["bnb_4bit_compute_dtype"] = str(output["bnb_4bit_compute_dtype"]).split(".")[1]
386
+ output["bnb_4bit_quant_storage"] = str(output["bnb_4bit_quant_storage"]).split(".")[1]
387
+ output["load_in_4bit"] = self.load_in_4bit
388
+ output["load_in_8bit"] = self.load_in_8bit
389
+
390
+ return output
391
+
392
+ def __repr__(self):
393
+ config_dict = self.to_dict()
394
+ return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n"
395
+
396
+ def to_diff_dict(self) -> Dict[str, Any]:
397
+ """
398
+ Removes all attributes from config which correspond to the default config attributes for better readability and
399
+ serializes to a Python dictionary.
400
+
401
+ Returns:
402
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
403
+ """
404
+ config_dict = self.to_dict()
405
+
406
+ # get the default config dict
407
+ default_config_dict = BitsAndBytesConfig().to_dict()
408
+
409
+ serializable_config_dict = {}
410
+
411
+ # only serialize values that differ from the default config
412
+ for key, value in config_dict.items():
413
+ if value != default_config_dict[key]:
414
+ serializable_config_dict[key] = value
415
+
416
+ return serializable_config_dict
417
+
418
+
419
+ @dataclass
420
+ class GGUFQuantizationConfig(QuantizationConfigMixin):
421
+ """This is a config class for GGUF Quantization techniques.
422
+
423
+ Args:
424
+ compute_dtype: (`torch.dtype`, defaults to `torch.float32`):
425
+ This sets the computational type which might be different than the input type. For example, inputs might be
426
+ fp32, but computation can be set to bf16 for speedups.
427
+
428
+ """
429
+
430
+ def __init__(self, compute_dtype: Optional["torch.dtype"] = None):
431
+ self.quant_method = QuantizationMethod.GGUF
432
+ self.compute_dtype = compute_dtype
433
+ self.pre_quantized = True
434
+
435
+ # TODO: (Dhruv) Add this as an init argument when we can support loading unquantized checkpoints.
436
+ self.modules_to_not_convert = None
437
+
438
+ if self.compute_dtype is None:
439
+ self.compute_dtype = torch.float32
440
+
441
+
442
+ @dataclass
443
+ class TorchAoConfig(QuantizationConfigMixin):
444
+ """This is a config class for torchao quantization/sparsity techniques.
445
+
446
+ Args:
447
+ quant_type (Union[`str`, AOBaseConfig]):
448
+ The type of quantization we want to use, currently supporting:
449
+ - **Integer quantization:**
450
+ - Full function names: `int4_weight_only`, `int8_dynamic_activation_int4_weight`,
451
+ `int8_weight_only`, `int8_dynamic_activation_int8_weight`
452
+ - Shorthands: `int4wo`, `int4dq`, `int8wo`, `int8dq`
453
+
454
+ - **Floating point 8-bit quantization:**
455
+ - Full function names: `float8_weight_only`, `float8_dynamic_activation_float8_weight`,
456
+ `float8_static_activation_float8_weight`
457
+ - Shorthands: `float8wo`, `float8wo_e5m2`, `float8wo_e4m3`, `float8dq`, `float8dq_e4m3`,
458
+ `float8_e4m3_tensor`, `float8_e4m3_row`,
459
+
460
+ - **Floating point X-bit quantization:**
461
+ - Full function names: `fpx_weight_only`
462
+ - Shorthands: `fpX_eAwB`, where `X` is the number of bits (between `1` to `7`), `A` is the number
463
+ of exponent bits and `B` is the number of mantissa bits. The constraint of `X == A + B + 1` must
464
+ be satisfied for a given shorthand notation.
465
+
466
+ - **Unsigned Integer quantization:**
467
+ - Full function names: `uintx_weight_only`
468
+ - Shorthands: `uint1wo`, `uint2wo`, `uint3wo`, `uint4wo`, `uint5wo`, `uint6wo`, `uint7wo`
469
+ - An AOBaseConfig instance: for more advanced configuration options.
470
+ modules_to_not_convert (`List[str]`, *optional*, default to `None`):
471
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have some
472
+ modules left in their original precision.
473
+ kwargs (`Dict[str, Any]`, *optional*):
474
+ The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization
475
+ supports two keyword arguments `group_size` and `inner_k_tiles` currently. More API examples and
476
+ documentation of arguments can be found in
477
+ https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques
478
+
479
+ Example:
480
+ ```python
481
+ from diffusers import FluxTransformer2DModel, TorchAoConfig
482
+
483
+ # AOBaseConfig-based configuration
484
+ from torchao.quantization import Int8WeightOnlyConfig
485
+
486
+ quantization_config = TorchAoConfig(Int8WeightOnlyConfig())
487
+
488
+ # String-based config
489
+ quantization_config = TorchAoConfig("int8wo")
490
+ transformer = FluxTransformer2DModel.from_pretrained(
491
+ "black-forest-labs/Flux.1-Dev",
492
+ subfolder="transformer",
493
+ quantization_config=quantization_config,
494
+ torch_dtype=torch.bfloat16,
495
+ )
496
+ ```
497
+ """
498
+
499
+ def __init__(
500
+ self,
501
+ quant_type: Union[str, "AOBaseConfig"], # noqa: F821
502
+ modules_to_not_convert: Optional[List[str]] = None,
503
+ **kwargs,
504
+ ) -> None:
505
+ self.quant_method = QuantizationMethod.TORCHAO
506
+ self.quant_type = quant_type
507
+ self.modules_to_not_convert = modules_to_not_convert
508
+
509
+ # When we load from serialized config, "quant_type_kwargs" will be the key
510
+ if "quant_type_kwargs" in kwargs:
511
+ self.quant_type_kwargs = kwargs["quant_type_kwargs"]
512
+ else:
513
+ self.quant_type_kwargs = kwargs
514
+
515
+ self.post_init()
516
+
517
+ def post_init(self):
518
+ if not isinstance(self.quant_type, str):
519
+ if is_torchao_version("<=", "0.9.0"):
520
+ raise ValueError(
521
+ f"torchao <= 0.9.0 only supports string quant_type, got {type(self.quant_type).__name__}. "
522
+ f"Upgrade to torchao > 0.9.0 to use AOBaseConfig."
523
+ )
524
+
525
+ from torchao.quantization.quant_api import AOBaseConfig
526
+
527
+ if not isinstance(self.quant_type, AOBaseConfig):
528
+ raise TypeError(f"quant_type must be a AOBaseConfig instance, got {type(self.quant_type).__name__}")
529
+
530
+ elif isinstance(self.quant_type, str):
531
+ TORCHAO_QUANT_TYPE_METHODS = self._get_torchao_quant_type_to_method()
532
+
533
+ if self.quant_type not in TORCHAO_QUANT_TYPE_METHODS.keys():
534
+ is_floating_quant_type = self.quant_type.startswith("float") or self.quant_type.startswith("fp")
535
+ if is_floating_quant_type and not self._is_xpu_or_cuda_capability_atleast_8_9():
536
+ raise ValueError(
537
+ f"Requested quantization type: {self.quant_type} is not supported on GPUs with CUDA capability <= 8.9. You "
538
+ f"can check the CUDA capability of your GPU using `torch.cuda.get_device_capability()`."
539
+ )
540
+
541
+ raise ValueError(
542
+ f"Requested quantization type: {self.quant_type} is not supported or is an incorrect `quant_type` name. If you think the "
543
+ f"provided quantization type should be supported, please open an issue at https://github.com/huggingface/diffusers/issues."
544
+ )
545
+
546
+ method = TORCHAO_QUANT_TYPE_METHODS[self.quant_type]
547
+ signature = inspect.signature(method)
548
+ all_kwargs = {
549
+ param.name
550
+ for param in signature.parameters.values()
551
+ if param.kind in [inspect.Parameter.KEYWORD_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD]
552
+ }
553
+ unsupported_kwargs = list(self.quant_type_kwargs.keys() - all_kwargs)
554
+
555
+ if len(unsupported_kwargs) > 0:
556
+ raise ValueError(
557
+ f'The quantization method "{self.quant_type}" does not support the following keyword arguments: '
558
+ f"{unsupported_kwargs}. The following keywords arguments are supported: {all_kwargs}."
559
+ )
560
+
561
+ def to_dict(self):
562
+ """Convert configuration to a dictionary."""
563
+ d = super().to_dict()
564
+
565
+ if isinstance(self.quant_type, str):
566
+ # Handle layout serialization if present
567
+ if "quant_type_kwargs" in d and "layout" in d["quant_type_kwargs"]:
568
+ if is_dataclass(d["quant_type_kwargs"]["layout"]):
569
+ d["quant_type_kwargs"]["layout"] = [
570
+ d["quant_type_kwargs"]["layout"].__class__.__name__,
571
+ dataclasses.asdict(d["quant_type_kwargs"]["layout"]),
572
+ ]
573
+ if isinstance(d["quant_type_kwargs"]["layout"], list):
574
+ assert len(d["quant_type_kwargs"]["layout"]) == 2, "layout saves layout name and layout kwargs"
575
+ assert isinstance(d["quant_type_kwargs"]["layout"][0], str), "layout name must be a string"
576
+ assert isinstance(d["quant_type_kwargs"]["layout"][1], dict), "layout kwargs must be a dict"
577
+ else:
578
+ raise ValueError("layout must be a list")
579
+ else:
580
+ # Handle AOBaseConfig serialization
581
+ from torchao.core.config import config_to_dict
582
+
583
+ # For now we assume there is 1 config per Transformer, however in the future
584
+ # We may want to support a config per fqn.
585
+ d["quant_type"] = {"default": config_to_dict(self.quant_type)}
586
+
587
+ return d
588
+
589
+ @classmethod
590
+ def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs):
591
+ """Create configuration from a dictionary."""
592
+ if not is_torchao_version(">", "0.9.0"):
593
+ raise NotImplementedError("TorchAoConfig requires torchao > 0.9.0 for construction from dict")
594
+ config_dict = config_dict.copy()
595
+ quant_type = config_dict.pop("quant_type")
596
+
597
+ if isinstance(quant_type, str):
598
+ return cls(quant_type=quant_type, **config_dict)
599
+ # Check if we only have one key which is "default"
600
+ # In the future we may update this
601
+ assert len(quant_type) == 1 and "default" in quant_type, (
602
+ "Expected only one key 'default' in quant_type dictionary"
603
+ )
604
+ quant_type = quant_type["default"]
605
+
606
+ # Deserialize quant_type if needed
607
+ from torchao.core.config import config_from_dict
608
+
609
+ quant_type = config_from_dict(quant_type)
610
+
611
+ return cls(quant_type=quant_type, **config_dict)
612
+
613
+ @classmethod
614
+ def _get_torchao_quant_type_to_method(cls):
615
+ r"""
616
+ Returns supported torchao quantization types with all commonly used notations.
617
+ """
618
+
619
+ if is_torchao_available():
620
+ # TODO(aryan): Support autoquant and sparsify
621
+ from torchao.quantization import (
622
+ float8_dynamic_activation_float8_weight,
623
+ float8_static_activation_float8_weight,
624
+ float8_weight_only,
625
+ fpx_weight_only,
626
+ int4_weight_only,
627
+ int8_dynamic_activation_int4_weight,
628
+ int8_dynamic_activation_int8_weight,
629
+ int8_weight_only,
630
+ uintx_weight_only,
631
+ )
632
+
633
+ # TODO(aryan): Add a note on how to use PerAxis and PerGroup observers
634
+ from torchao.quantization.observer import PerRow, PerTensor
635
+
636
+ def generate_float8dq_types(dtype: torch.dtype):
637
+ name = "e5m2" if dtype == torch.float8_e5m2 else "e4m3"
638
+ types = {}
639
+
640
+ for granularity_cls in [PerTensor, PerRow]:
641
+ # Note: Activation and Weights cannot have different granularities
642
+ granularity_name = "tensor" if granularity_cls is PerTensor else "row"
643
+ types[f"float8dq_{name}_{granularity_name}"] = partial(
644
+ float8_dynamic_activation_float8_weight,
645
+ activation_dtype=dtype,
646
+ weight_dtype=dtype,
647
+ granularity=(granularity_cls(), granularity_cls()),
648
+ )
649
+
650
+ return types
651
+
652
+ def generate_fpx_quantization_types(bits: int):
653
+ types = {}
654
+
655
+ for ebits in range(1, bits):
656
+ mbits = bits - ebits - 1
657
+ types[f"fp{bits}_e{ebits}m{mbits}"] = partial(fpx_weight_only, ebits=ebits, mbits=mbits)
658
+
659
+ non_sign_bits = bits - 1
660
+ default_ebits = (non_sign_bits + 1) // 2
661
+ default_mbits = non_sign_bits - default_ebits
662
+ types[f"fp{bits}"] = partial(fpx_weight_only, ebits=default_ebits, mbits=default_mbits)
663
+
664
+ return types
665
+
666
+ INT4_QUANTIZATION_TYPES = {
667
+ # int4 weight + bfloat16/float16 activation
668
+ "int4wo": int4_weight_only,
669
+ "int4_weight_only": int4_weight_only,
670
+ # int4 weight + int8 activation
671
+ "int4dq": int8_dynamic_activation_int4_weight,
672
+ "int8_dynamic_activation_int4_weight": int8_dynamic_activation_int4_weight,
673
+ }
674
+
675
+ INT8_QUANTIZATION_TYPES = {
676
+ # int8 weight + bfloat16/float16 activation
677
+ "int8wo": int8_weight_only,
678
+ "int8_weight_only": int8_weight_only,
679
+ # int8 weight + int8 activation
680
+ "int8dq": int8_dynamic_activation_int8_weight,
681
+ "int8_dynamic_activation_int8_weight": int8_dynamic_activation_int8_weight,
682
+ }
683
+
684
+ # TODO(aryan): handle torch 2.2/2.3
685
+ FLOATX_QUANTIZATION_TYPES = {
686
+ # float8_e5m2 weight + bfloat16/float16 activation
687
+ "float8wo": partial(float8_weight_only, weight_dtype=torch.float8_e5m2),
688
+ "float8_weight_only": float8_weight_only,
689
+ "float8wo_e5m2": partial(float8_weight_only, weight_dtype=torch.float8_e5m2),
690
+ # float8_e4m3 weight + bfloat16/float16 activation
691
+ "float8wo_e4m3": partial(float8_weight_only, weight_dtype=torch.float8_e4m3fn),
692
+ # float8_e5m2 weight + float8 activation (dynamic)
693
+ "float8dq": float8_dynamic_activation_float8_weight,
694
+ "float8_dynamic_activation_float8_weight": float8_dynamic_activation_float8_weight,
695
+ # ===== Matrix multiplication is not supported in float8_e5m2 so the following errors out.
696
+ # However, changing activation_dtype=torch.float8_e4m3 might work here =====
697
+ # "float8dq_e5m2": partial(
698
+ # float8_dynamic_activation_float8_weight,
699
+ # activation_dtype=torch.float8_e5m2,
700
+ # weight_dtype=torch.float8_e5m2,
701
+ # ),
702
+ # **generate_float8dq_types(torch.float8_e5m2),
703
+ # ===== =====
704
+ # float8_e4m3 weight + float8 activation (dynamic)
705
+ "float8dq_e4m3": partial(
706
+ float8_dynamic_activation_float8_weight,
707
+ activation_dtype=torch.float8_e4m3fn,
708
+ weight_dtype=torch.float8_e4m3fn,
709
+ ),
710
+ **generate_float8dq_types(torch.float8_e4m3fn),
711
+ # float8 weight + float8 activation (static)
712
+ "float8_static_activation_float8_weight": float8_static_activation_float8_weight,
713
+ # For fpx, only x <= 8 is supported by default. Other dtypes can be explored by users directly
714
+ # fpx weight + bfloat16/float16 activation
715
+ **generate_fpx_quantization_types(3),
716
+ **generate_fpx_quantization_types(4),
717
+ **generate_fpx_quantization_types(5),
718
+ **generate_fpx_quantization_types(6),
719
+ **generate_fpx_quantization_types(7),
720
+ }
721
+
722
+ UINTX_QUANTIZATION_DTYPES = {
723
+ "uintx_weight_only": uintx_weight_only,
724
+ "uint1wo": partial(uintx_weight_only, dtype=torch.uint1),
725
+ "uint2wo": partial(uintx_weight_only, dtype=torch.uint2),
726
+ "uint3wo": partial(uintx_weight_only, dtype=torch.uint3),
727
+ "uint4wo": partial(uintx_weight_only, dtype=torch.uint4),
728
+ "uint5wo": partial(uintx_weight_only, dtype=torch.uint5),
729
+ "uint6wo": partial(uintx_weight_only, dtype=torch.uint6),
730
+ "uint7wo": partial(uintx_weight_only, dtype=torch.uint7),
731
+ # "uint8wo": partial(uintx_weight_only, dtype=torch.uint8), # uint8 quantization is not supported
732
+ }
733
+
734
+ QUANTIZATION_TYPES = {}
735
+ QUANTIZATION_TYPES.update(INT4_QUANTIZATION_TYPES)
736
+ QUANTIZATION_TYPES.update(INT8_QUANTIZATION_TYPES)
737
+ QUANTIZATION_TYPES.update(UINTX_QUANTIZATION_DTYPES)
738
+
739
+ if cls._is_xpu_or_cuda_capability_atleast_8_9():
740
+ QUANTIZATION_TYPES.update(FLOATX_QUANTIZATION_TYPES)
741
+
742
+ return QUANTIZATION_TYPES
743
+ else:
744
+ raise ValueError(
745
+ "TorchAoConfig requires torchao to be installed, please install with `pip install torchao`"
746
+ )
747
+
748
+ @staticmethod
749
+ def _is_xpu_or_cuda_capability_atleast_8_9() -> bool:
750
+ if torch.cuda.is_available():
751
+ major, minor = torch.cuda.get_device_capability()
752
+ if major == 8:
753
+ return minor >= 9
754
+ return major >= 9
755
+ elif torch.xpu.is_available():
756
+ return True
757
+ else:
758
+ raise RuntimeError("TorchAO requires a CUDA compatible GPU or Intel XPU and installation of PyTorch.")
759
+
760
+ def get_apply_tensor_subclass(self):
761
+ """Create the appropriate quantization method based on configuration."""
762
+ if not isinstance(self.quant_type, str):
763
+ return self.quant_type
764
+ else:
765
+ methods = self._get_torchao_quant_type_to_method()
766
+ quant_type_kwargs = self.quant_type_kwargs.copy()
767
+ if (
768
+ not torch.cuda.is_available()
769
+ and is_torchao_available()
770
+ and self.quant_type == "int4_weight_only"
771
+ and version.parse(importlib.metadata.version("torchao")) >= version.parse("0.8.0")
772
+ and quant_type_kwargs.get("layout", None) is None
773
+ ):
774
+ if torch.xpu.is_available():
775
+ if version.parse(importlib.metadata.version("torchao")) >= version.parse(
776
+ "0.11.0"
777
+ ) and version.parse(importlib.metadata.version("torch")) > version.parse("2.7.9"):
778
+ from torchao.dtypes import Int4XPULayout
779
+ from torchao.quantization.quant_primitives import ZeroPointDomain
780
+
781
+ quant_type_kwargs["layout"] = Int4XPULayout()
782
+ quant_type_kwargs["zero_point_domain"] = ZeroPointDomain.INT
783
+ else:
784
+ raise ValueError(
785
+ "TorchAoConfig requires torchao >= 0.11.0 and torch >= 2.8.0 for XPU support. Please upgrade the version or use run on CPU with the cpu version pytorch."
786
+ )
787
+ else:
788
+ from torchao.dtypes import Int4CPULayout
789
+
790
+ quant_type_kwargs["layout"] = Int4CPULayout()
791
+
792
+ return methods[self.quant_type](**quant_type_kwargs)
793
+
794
+ def __repr__(self):
795
+ r"""
796
+ Example of how this looks for `TorchAoConfig("uint4wo", group_size=32)`:
797
+
798
+ ```
799
+ TorchAoConfig {
800
+ "modules_to_not_convert": null,
801
+ "quant_method": "torchao",
802
+ "quant_type": "uint4wo",
803
+ "quant_type_kwargs": {
804
+ "group_size": 32
805
+ }
806
+ }
807
+ ```
808
+ """
809
+ config_dict = self.to_dict()
810
+ return (
811
+ f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True, cls=TorchAoJSONEncoder)}\n"
812
+ )
813
+
814
+
815
+ @dataclass
816
+ class QuantoConfig(QuantizationConfigMixin):
817
+ """
818
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
819
+ loaded using `quanto`.
820
+
821
+ Args:
822
+ weights_dtype (`str`, *optional*, defaults to `"int8"`):
823
+ The target dtype for the weights after quantization. Supported values are ("float8","int8","int4","int2")
824
+ modules_to_not_convert (`list`, *optional*, default to `None`):
825
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have some
826
+ modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers).
827
+ """
828
+
829
+ def __init__(
830
+ self,
831
+ weights_dtype: str = "int8",
832
+ modules_to_not_convert: Optional[List[str]] = None,
833
+ **kwargs,
834
+ ):
835
+ self.quant_method = QuantizationMethod.QUANTO
836
+ self.weights_dtype = weights_dtype
837
+ self.modules_to_not_convert = modules_to_not_convert
838
+
839
+ self.post_init()
840
+
841
+ def post_init(self):
842
+ r"""
843
+ Safety checker that arguments are correct
844
+ """
845
+ accepted_weights = ["float8", "int8", "int4", "int2"]
846
+ if self.weights_dtype not in accepted_weights:
847
+ raise ValueError(f"Only support weights in {accepted_weights} but found {self.weights_dtype}")
848
+
849
+
850
+ @dataclass
851
+ class NVIDIAModelOptConfig(QuantizationConfigMixin):
852
+ """This is a config class to use nvidia modelopt for quantization.
853
+
854
+ Args:
855
+ quant_type (`str`):
856
+ The type of quantization we want to use, following is how to use:
857
+ **weightquant_activationquant ==> FP8_FP8** In the above example we have use FP8 for both weight and
858
+ activation quantization. Following are the all the options:
859
+ - FP8
860
+ - INT8
861
+ - INT4
862
+ - NF4
863
+ - NVFP4
864
+ modules_to_not_convert (`List[str]`, *optional*, default to `None`):
865
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have some
866
+ weight_only (`bool`, *optional*, default to `False`):
867
+ If set to `True`, the quantization will be applied only to the weights of the model.
868
+ channel_quantize (`int`, *optional*, default to `None`):
869
+ The channel quantization axis, useful for quantizing models across different axes.
870
+ block_quantize (`int`, *optional*, default to `None`):
871
+ The block size, useful to further quantize each channel/axes into blocks.
872
+ scale_channel_quantize (`int`, *optional*, default to `None`):
873
+ The scale channel quantization axis, useful for quantizing calculated scale across different axes.
874
+ scale_block_quantize (`int`, *optional*, default to `None`):
875
+ The scale block size, useful for quantizing each scale channel/axes into blocks.
876
+ algorithm (`str`, *optional*, default to `"max"`):
877
+ The algorithm to use for quantization, currently only supports `"max"`.
878
+ forward_loop (`Callable`, *optional*, default to `None`):
879
+ The forward loop function to use for calibration during quantization.
880
+ modelopt_config (`dict`, *optional*, default to `None`):
881
+ The modelopt config, useful for passing custom configs to modelopt.
882
+ disable_conv_quantization (`bool`, *optional*, default to `False`):
883
+ If set to `True`, the quantization will be disabled for convolutional layers.
884
+ kwargs (`Dict[str, Any]`, *optional*):
885
+ Additional parameters which are to be used for calibration.
886
+ """
887
+
888
+ quanttype_to_numbits = {
889
+ "FP8": (4, 3),
890
+ "INT8": 8,
891
+ "INT4": 4,
892
+ "NF4": 4,
893
+ "NVFP4": (2, 1),
894
+ }
895
+ quanttype_to_scalingbits = {
896
+ "NF4": 8,
897
+ "NVFP4": (4, 3),
898
+ }
899
+
900
+ def __init__(
901
+ self,
902
+ quant_type: str,
903
+ modules_to_not_convert: Optional[List[str]] = None,
904
+ weight_only: bool = True,
905
+ channel_quantize: Optional[int] = None,
906
+ block_quantize: Optional[int] = None,
907
+ scale_channel_quantize: Optional[int] = None,
908
+ scale_block_quantize: Optional[int] = None,
909
+ algorithm: str = "max",
910
+ forward_loop: Optional[Callable] = None,
911
+ modelopt_config: Optional[dict] = None,
912
+ disable_conv_quantization: bool = False,
913
+ **kwargs,
914
+ ) -> None:
915
+ self.quant_method = QuantizationMethod.MODELOPT
916
+ self._normalize_quant_type(quant_type)
917
+ self.modules_to_not_convert = modules_to_not_convert
918
+ self.weight_only = weight_only
919
+ self.channel_quantize = channel_quantize
920
+ self.block_quantize = block_quantize
921
+ self.calib_cfg = {
922
+ "method": algorithm,
923
+ # add more options here if needed
924
+ }
925
+ self.forward_loop = forward_loop
926
+ self.scale_channel_quantize = scale_channel_quantize
927
+ self.scale_block_quantize = scale_block_quantize
928
+ self.modelopt_config = self.get_config_from_quant_type() if not modelopt_config else modelopt_config
929
+ self.disable_conv_quantization = disable_conv_quantization
930
+
931
+ def check_model_patching(self, operation: str = "loading"):
932
+ # ModelOpt imports diffusers internally. This is here to prevent circular imports
933
+ from modelopt.torch.opt.plugins.huggingface import _PATCHED_CLASSES
934
+
935
+ if len(_PATCHED_CLASSES) == 0:
936
+ warning_msg = (
937
+ f"Not {operation} weights in modelopt format. This might cause unreliable behavior."
938
+ "Please make sure to run the following code before loading/saving model weights:\n\n"
939
+ " from modelopt.torch.opt import enable_huggingface_checkpointing\n"
940
+ " enable_huggingface_checkpointing()\n"
941
+ )
942
+ warnings.warn(warning_msg)
943
+
944
+ def _normalize_quant_type(self, quant_type: str) -> str:
945
+ """
946
+ Validates and normalizes the quantization type string.
947
+
948
+ Splits the quant_type into weight and activation components, verifies them against supported types, and
949
+ replaces unsupported values with safe defaults.
950
+
951
+ Args:
952
+ quant_type (str): The input quantization type string (e.g., 'FP8_INT8').
953
+
954
+ Returns:
955
+ str: A valid quantization type string (e.g., 'FP8_INT8' or 'FP8').
956
+ """
957
+ parts = quant_type.split("_")
958
+ w_type = parts[0]
959
+ act_type = parts[1] if len(parts) > 1 else None
960
+ if len(parts) > 2:
961
+ logger.warning(f"Quantization type {quant_type} is not supported. Picking FP8_INT8 as default")
962
+ w_type = "FP8"
963
+ act_type = None
964
+ else:
965
+ if w_type not in NVIDIAModelOptConfig.quanttype_to_numbits:
966
+ logger.warning(f"Weight Quantization type {w_type} is not supported. Picking FP8 as default")
967
+ w_type = "FP8"
968
+ if act_type is not None and act_type not in NVIDIAModelOptConfig.quanttype_to_numbits:
969
+ logger.warning(f"Activation Quantization type {act_type} is not supported. Picking INT8 as default")
970
+ act_type = None
971
+ self.quant_type = w_type + ("_" + act_type if act_type is not None else "")
972
+
973
+ def get_config_from_quant_type(self) -> Dict[str, Any]:
974
+ """
975
+ Get the config from the quantization type.
976
+ """
977
+ import modelopt.torch.quantization as mtq
978
+
979
+ BASE_CONFIG = {
980
+ "quant_cfg": {
981
+ "*weight_quantizer": {"fake_quant": False},
982
+ "*input_quantizer": {},
983
+ "*output_quantizer": {"enable": False},
984
+ "*q_bmm_quantizer": {},
985
+ "*k_bmm_quantizer": {},
986
+ "*v_bmm_quantizer": {},
987
+ "*softmax_quantizer": {},
988
+ **mtq.config._default_disabled_quantizer_cfg,
989
+ },
990
+ "algorithm": self.calib_cfg,
991
+ }
992
+
993
+ quant_cfg = BASE_CONFIG["quant_cfg"]
994
+ if self.weight_only:
995
+ for k in quant_cfg:
996
+ if "*weight_quantizer" not in k and not quant_cfg[k]:
997
+ quant_cfg[k]["enable"] = False
998
+
999
+ parts = self.quant_type.split("_")
1000
+ w_type = parts[0]
1001
+ act_type = parts[1].replace("A", "") if len(parts) > 1 else None
1002
+ for k in quant_cfg:
1003
+ if k not in mtq.config._default_disabled_quantizer_cfg and "enable" not in quant_cfg[k]:
1004
+ if k == "*input_quantizer":
1005
+ if act_type is not None:
1006
+ quant_cfg[k]["num_bits"] = NVIDIAModelOptConfig.quanttype_to_numbits[act_type]
1007
+ continue
1008
+ quant_cfg[k]["num_bits"] = NVIDIAModelOptConfig.quanttype_to_numbits[w_type]
1009
+
1010
+ if self.block_quantize is not None and self.channel_quantize is not None:
1011
+ quant_cfg["*weight_quantizer"]["block_sizes"] = {self.channel_quantize: self.block_quantize}
1012
+ quant_cfg["*input_quantizer"]["block_sizes"] = {
1013
+ self.channel_quantize: self.block_quantize,
1014
+ "type": "dynamic",
1015
+ }
1016
+ elif self.channel_quantize is not None:
1017
+ quant_cfg["*weight_quantizer"]["axis"] = self.channel_quantize
1018
+ quant_cfg["*input_quantizer"]["axis"] = self.channel_quantize
1019
+ quant_cfg["*input_quantizer"]["type"] = "dynamic"
1020
+
1021
+ # Only fixed scaling sizes are supported for now in modelopt
1022
+ if self.scale_channel_quantize is not None and self.scale_block_quantize is not None:
1023
+ if w_type in NVIDIAModelOptConfig.quanttype_to_scalingbits:
1024
+ quant_cfg["*weight_quantizer"]["block_sizes"].update(
1025
+ {
1026
+ "scale_bits": NVIDIAModelOptConfig.quanttype_to_scalingbits[w_type],
1027
+ "scale_block_sizes": {self.scale_channel_quantize: self.scale_block_quantize},
1028
+ }
1029
+ )
1030
+ if act_type and act_type in NVIDIAModelOptConfig.quanttype_to_scalingbits:
1031
+ quant_cfg["*input_quantizer"]["block_sizes"].update(
1032
+ {
1033
+ "scale_bits": NVIDIAModelOptConfig.quanttype_to_scalingbits[act_type],
1034
+ "scale_block_sizes": {self.scale_channel_quantize: self.scale_block_quantize},
1035
+ }
1036
+ )
1037
+
1038
+ return BASE_CONFIG
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/quanto/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .quanto_quantizer import QuantoQuantizer
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/quanto/quanto_quantizer.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING, Any, Dict, List, Union
2
+
3
+ from diffusers.utils.import_utils import is_optimum_quanto_version
4
+
5
+ from ...utils import (
6
+ get_module_from_name,
7
+ is_accelerate_available,
8
+ is_accelerate_version,
9
+ is_optimum_quanto_available,
10
+ is_torch_available,
11
+ logging,
12
+ )
13
+ from ..base import DiffusersQuantizer
14
+
15
+
16
+ if TYPE_CHECKING:
17
+ from ...models.modeling_utils import ModelMixin
18
+
19
+
20
+ if is_torch_available():
21
+ import torch
22
+
23
+ if is_accelerate_available():
24
+ from accelerate.utils import CustomDtype, set_module_tensor_to_device
25
+
26
+ if is_optimum_quanto_available():
27
+ from .utils import _replace_with_quanto_layers
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+
32
+ class QuantoQuantizer(DiffusersQuantizer):
33
+ r"""
34
+ Diffusers Quantizer for Optimum Quanto
35
+ """
36
+
37
+ use_keep_in_fp32_modules = True
38
+ requires_calibration = False
39
+ required_packages = ["quanto", "accelerate"]
40
+
41
+ def __init__(self, quantization_config, **kwargs):
42
+ super().__init__(quantization_config, **kwargs)
43
+
44
+ def validate_environment(self, *args, **kwargs):
45
+ if not is_optimum_quanto_available():
46
+ raise ImportError(
47
+ "Loading an optimum-quanto quantized model requires optimum-quanto library (`pip install optimum-quanto`)"
48
+ )
49
+ if not is_optimum_quanto_version(">=", "0.2.6"):
50
+ raise ImportError(
51
+ "Loading an optimum-quanto quantized model requires `optimum-quanto>=0.2.6`. "
52
+ "Please upgrade your installation with `pip install --upgrade optimum-quanto"
53
+ )
54
+
55
+ if not is_accelerate_available():
56
+ raise ImportError(
57
+ "Loading an optimum-quanto quantized model requires accelerate library (`pip install accelerate`)"
58
+ )
59
+
60
+ device_map = kwargs.get("device_map", None)
61
+ if isinstance(device_map, dict) and len(device_map.keys()) > 1:
62
+ raise ValueError(
63
+ "`device_map` for multi-GPU inference or CPU/disk offload is currently not supported with Diffusers and the Quanto backend"
64
+ )
65
+
66
+ def check_if_quantized_param(
67
+ self,
68
+ model: "ModelMixin",
69
+ param_value: "torch.Tensor",
70
+ param_name: str,
71
+ state_dict: Dict[str, Any],
72
+ **kwargs,
73
+ ):
74
+ # Quanto imports diffusers internally. This is here to prevent circular imports
75
+ from optimum.quanto import QModuleMixin, QTensor
76
+ from optimum.quanto.tensor.packed import PackedTensor
77
+
78
+ module, tensor_name = get_module_from_name(model, param_name)
79
+ if self.pre_quantized and any(isinstance(module, t) for t in [QTensor, PackedTensor]):
80
+ return True
81
+ elif isinstance(module, QModuleMixin) and "weight" in tensor_name:
82
+ return not module.frozen
83
+
84
+ return False
85
+
86
+ def create_quantized_param(
87
+ self,
88
+ model: "ModelMixin",
89
+ param_value: "torch.Tensor",
90
+ param_name: str,
91
+ target_device: "torch.device",
92
+ *args,
93
+ **kwargs,
94
+ ):
95
+ """
96
+ Create the quantized parameter by calling .freeze() after setting it to the module.
97
+ """
98
+
99
+ dtype = kwargs.get("dtype", torch.float32)
100
+ module, tensor_name = get_module_from_name(model, param_name)
101
+ if self.pre_quantized:
102
+ setattr(module, tensor_name, param_value)
103
+ else:
104
+ set_module_tensor_to_device(model, param_name, target_device, param_value, dtype)
105
+ module.freeze()
106
+ module.weight.requires_grad = False
107
+
108
+ def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]:
109
+ max_memory = {key: val * 0.90 for key, val in max_memory.items()}
110
+ return max_memory
111
+
112
+ def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype":
113
+ if is_accelerate_version(">=", "0.27.0"):
114
+ mapping = {
115
+ "int8": torch.int8,
116
+ "float8": CustomDtype.FP8,
117
+ "int4": CustomDtype.INT4,
118
+ "int2": CustomDtype.INT2,
119
+ }
120
+ target_dtype = mapping[self.quantization_config.weights_dtype]
121
+
122
+ return target_dtype
123
+
124
+ def update_torch_dtype(self, torch_dtype: "torch.dtype" = None) -> "torch.dtype":
125
+ if torch_dtype is None:
126
+ logger.info("You did not specify `torch_dtype` in `from_pretrained`. Setting it to `torch.float32`.")
127
+ torch_dtype = torch.float32
128
+ return torch_dtype
129
+
130
+ def update_missing_keys(self, model, missing_keys: List[str], prefix: str) -> List[str]:
131
+ # Quanto imports diffusers internally. This is here to prevent circular imports
132
+ from optimum.quanto import QModuleMixin
133
+
134
+ not_missing_keys = []
135
+ for name, module in model.named_modules():
136
+ if isinstance(module, QModuleMixin):
137
+ for missing in missing_keys:
138
+ if (
139
+ (name in missing or name in f"{prefix}.{missing}")
140
+ and not missing.endswith(".weight")
141
+ and not missing.endswith(".bias")
142
+ ):
143
+ not_missing_keys.append(missing)
144
+ return [k for k in missing_keys if k not in not_missing_keys]
145
+
146
+ def _process_model_before_weight_loading(
147
+ self,
148
+ model: "ModelMixin",
149
+ device_map,
150
+ keep_in_fp32_modules: List[str] = [],
151
+ **kwargs,
152
+ ):
153
+ self.modules_to_not_convert = self.quantization_config.modules_to_not_convert
154
+
155
+ if not isinstance(self.modules_to_not_convert, list):
156
+ self.modules_to_not_convert = [self.modules_to_not_convert]
157
+
158
+ self.modules_to_not_convert.extend(keep_in_fp32_modules)
159
+
160
+ model = _replace_with_quanto_layers(
161
+ model,
162
+ modules_to_not_convert=self.modules_to_not_convert,
163
+ quantization_config=self.quantization_config,
164
+ pre_quantized=self.pre_quantized,
165
+ )
166
+ model.config.quantization_config = self.quantization_config
167
+
168
+ def _process_model_after_weight_loading(self, model, **kwargs):
169
+ return model
170
+
171
+ @property
172
+ def is_trainable(self):
173
+ return True
174
+
175
+ @property
176
+ def is_serializable(self):
177
+ return True
178
+
179
+ @property
180
+ def is_compileable(self) -> bool:
181
+ return True
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/quanto/utils.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+
3
+ from ...utils import is_accelerate_available, logging
4
+
5
+
6
+ logger = logging.get_logger(__name__)
7
+
8
+ if is_accelerate_available():
9
+ from accelerate import init_empty_weights
10
+
11
+
12
+ def _replace_with_quanto_layers(model, quantization_config, modules_to_not_convert: list, pre_quantized=False):
13
+ # Quanto imports diffusers internally. These are placed here to avoid circular imports
14
+ from optimum.quanto import QLinear, freeze, qfloat8, qint2, qint4, qint8
15
+
16
+ def _get_weight_type(dtype: str):
17
+ return {"float8": qfloat8, "int8": qint8, "int4": qint4, "int2": qint2}[dtype]
18
+
19
+ def _replace_layers(model, quantization_config, modules_to_not_convert):
20
+ has_children = list(model.children())
21
+ if not has_children:
22
+ return model
23
+
24
+ for name, module in model.named_children():
25
+ _replace_layers(module, quantization_config, modules_to_not_convert)
26
+
27
+ if name in modules_to_not_convert:
28
+ continue
29
+
30
+ if isinstance(module, nn.Linear):
31
+ with init_empty_weights():
32
+ qlinear = QLinear(
33
+ in_features=module.in_features,
34
+ out_features=module.out_features,
35
+ bias=module.bias is not None,
36
+ dtype=module.weight.dtype,
37
+ weights=_get_weight_type(quantization_config.weights_dtype),
38
+ )
39
+ model._modules[name] = qlinear
40
+ model._modules[name].source_cls = type(module)
41
+ model._modules[name].requires_grad_(False)
42
+
43
+ return model
44
+
45
+ model = _replace_layers(model, quantization_config, modules_to_not_convert)
46
+ has_been_replaced = any(isinstance(replaced_module, QLinear) for _, replaced_module in model.named_modules())
47
+
48
+ if not has_been_replaced:
49
+ logger.warning(
50
+ f"{model.__class__.__name__} does not appear to have any `nn.Linear` modules. Quantization will not be applied."
51
+ " Please check your model architecture, or submit an issue on Github if you think this is a bug."
52
+ " https://github.com/huggingface/diffusers/issues/new"
53
+ )
54
+
55
+ # We need to freeze the pre_quantized model in order for the loaded state_dict and model state dict
56
+ # to match when trying to load weights with load_model_dict_into_meta
57
+ if pre_quantized:
58
+ freeze(model)
59
+
60
+ return model
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/torchao/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. 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
+ from .torchao_quantizer import TorchAoHfQuantizer
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/quantizers/torchao/torchao_quantizer.py ADDED
@@ -0,0 +1,417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Adapted from
17
+ https://github.com/huggingface/transformers/blob/3a8eb74668e9c2cc563b2f5c62fac174797063e0/src/transformers/quantizers/quantizer_torchao.py
18
+ """
19
+
20
+ import importlib
21
+ import re
22
+ import types
23
+ from fnmatch import fnmatch
24
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
25
+
26
+ from packaging import version
27
+
28
+ from ...utils import (
29
+ get_module_from_name,
30
+ is_torch_available,
31
+ is_torch_version,
32
+ is_torchao_available,
33
+ is_torchao_version,
34
+ logging,
35
+ )
36
+ from ..base import DiffusersQuantizer
37
+
38
+
39
+ if TYPE_CHECKING:
40
+ from ...models.modeling_utils import ModelMixin
41
+
42
+
43
+ if is_torch_available():
44
+ import torch
45
+ import torch.nn as nn
46
+
47
+ if is_torch_version(">=", "2.5"):
48
+ SUPPORTED_TORCH_DTYPES_FOR_QUANTIZATION = (
49
+ # At the moment, only int8 is supported for integer quantization dtypes.
50
+ # In Torch 2.6, int1-int7 will be introduced, so this can be visited in the future
51
+ # to support more quantization methods, such as intx_weight_only.
52
+ torch.int8,
53
+ torch.float8_e4m3fn,
54
+ torch.float8_e5m2,
55
+ torch.uint1,
56
+ torch.uint2,
57
+ torch.uint3,
58
+ torch.uint4,
59
+ torch.uint5,
60
+ torch.uint6,
61
+ torch.uint7,
62
+ )
63
+ else:
64
+ SUPPORTED_TORCH_DTYPES_FOR_QUANTIZATION = (
65
+ torch.int8,
66
+ torch.float8_e4m3fn,
67
+ torch.float8_e5m2,
68
+ )
69
+
70
+ if is_torchao_available():
71
+ from torchao.quantization import quantize_
72
+
73
+
74
+ def _update_torch_safe_globals():
75
+ safe_globals = [
76
+ (torch.uint1, "torch.uint1"),
77
+ (torch.uint2, "torch.uint2"),
78
+ (torch.uint3, "torch.uint3"),
79
+ (torch.uint4, "torch.uint4"),
80
+ (torch.uint5, "torch.uint5"),
81
+ (torch.uint6, "torch.uint6"),
82
+ (torch.uint7, "torch.uint7"),
83
+ ]
84
+ try:
85
+ from torchao.dtypes import NF4Tensor
86
+ from torchao.dtypes.floatx.float8_layout import Float8AQTTensorImpl
87
+ from torchao.dtypes.uintx.uint4_layout import UInt4Tensor
88
+ from torchao.dtypes.uintx.uintx_layout import UintxAQTTensorImpl, UintxTensor
89
+
90
+ safe_globals.extend([UintxTensor, UInt4Tensor, UintxAQTTensorImpl, Float8AQTTensorImpl, NF4Tensor])
91
+
92
+ except (ImportError, ModuleNotFoundError) as e:
93
+ logger.warning(
94
+ "Unable to import `torchao` Tensor objects. This may affect loading checkpoints serialized with `torchao`"
95
+ )
96
+ logger.debug(e)
97
+
98
+ finally:
99
+ torch.serialization.add_safe_globals(safe_globals=safe_globals)
100
+
101
+
102
+ if (
103
+ is_torch_available()
104
+ and is_torch_version(">=", "2.6.0")
105
+ and is_torchao_available()
106
+ and is_torchao_version(">=", "0.7.0")
107
+ ):
108
+ _update_torch_safe_globals()
109
+
110
+
111
+ def fuzzy_match_size(config_name: str) -> Optional[str]:
112
+ """
113
+ Extract the size digit from strings like "4weight", "8weight". Returns the digit as an integer if found, otherwise
114
+ None.
115
+ """
116
+ config_name = config_name.lower()
117
+
118
+ str_match = re.search(r"(\d)weight", config_name)
119
+
120
+ if str_match:
121
+ return str_match.group(1)
122
+
123
+ return None
124
+
125
+
126
+ logger = logging.get_logger(__name__)
127
+
128
+
129
+ def _quantization_type(weight):
130
+ from torchao.dtypes import AffineQuantizedTensor
131
+ from torchao.quantization.linear_activation_quantized_tensor import LinearActivationQuantizedTensor
132
+
133
+ if isinstance(weight, AffineQuantizedTensor):
134
+ return f"{weight.__class__.__name__}({weight._quantization_type()})"
135
+
136
+ if isinstance(weight, LinearActivationQuantizedTensor):
137
+ return f"{weight.__class__.__name__}(activation={weight.input_quant_func}, weight={_quantization_type(weight.original_weight_tensor)})"
138
+
139
+
140
+ def _linear_extra_repr(self):
141
+ weight = _quantization_type(self.weight)
142
+ if weight is None:
143
+ return f"in_features={self.weight.shape[1]}, out_features={self.weight.shape[0]}, weight=None"
144
+ else:
145
+ return f"in_features={self.weight.shape[1]}, out_features={self.weight.shape[0]}, weight={weight}"
146
+
147
+
148
+ class TorchAoHfQuantizer(DiffusersQuantizer):
149
+ r"""
150
+ Diffusers Quantizer for TorchAO: https://github.com/pytorch/ao/.
151
+ """
152
+
153
+ requires_calibration = False
154
+ required_packages = ["torchao"]
155
+
156
+ def __init__(self, quantization_config, **kwargs):
157
+ super().__init__(quantization_config, **kwargs)
158
+
159
+ def validate_environment(self, *args, **kwargs):
160
+ if not is_torchao_available():
161
+ raise ImportError(
162
+ "Loading a TorchAO quantized model requires the torchao library. Please install with `pip install torchao`"
163
+ )
164
+ torchao_version = version.parse(importlib.metadata.version("torch"))
165
+ if torchao_version < version.parse("0.7.0"):
166
+ raise RuntimeError(
167
+ f"The minimum required version of `torchao` is 0.7.0, but the current version is {torchao_version}. Please upgrade with `pip install -U torchao`."
168
+ )
169
+
170
+ self.offload = False
171
+
172
+ device_map = kwargs.get("device_map", None)
173
+ if isinstance(device_map, dict):
174
+ if "cpu" in device_map.values() or "disk" in device_map.values():
175
+ if self.pre_quantized:
176
+ raise ValueError(
177
+ "You are attempting to perform cpu/disk offload with a pre-quantized torchao model "
178
+ "This is not supported yet. Please remove the CPU or disk device from the `device_map` argument."
179
+ )
180
+ else:
181
+ self.offload = True
182
+
183
+ if self.pre_quantized:
184
+ weights_only = kwargs.get("weights_only", None)
185
+ if weights_only:
186
+ torch_version = version.parse(importlib.metadata.version("torch"))
187
+ if torch_version < version.parse("2.5.0"):
188
+ # TODO(aryan): TorchAO is compatible with Pytorch >= 2.2 for certain quantization types. Try to see if we can support it in future
189
+ raise RuntimeError(
190
+ f"In order to use TorchAO pre-quantized model, you need to have torch>=2.5.0. However, the current version is {torch_version}."
191
+ )
192
+
193
+ def update_torch_dtype(self, torch_dtype):
194
+ quant_type = self.quantization_config.quant_type
195
+ if isinstance(quant_type, str) and (quant_type.startswith("int") or quant_type.startswith("uint")):
196
+ if torch_dtype is not None and torch_dtype != torch.bfloat16:
197
+ logger.warning(
198
+ f"You are trying to set torch_dtype to {torch_dtype} for int4/int8/uintx quantization, but "
199
+ f"only bfloat16 is supported right now. Please set `torch_dtype=torch.bfloat16`."
200
+ )
201
+
202
+ if torch_dtype is None:
203
+ # We need to set the torch_dtype, otherwise we have dtype mismatch when performing the quantized linear op
204
+ logger.warning(
205
+ "Overriding `torch_dtype` with `torch_dtype=torch.bfloat16` due to requirements of `torchao` "
206
+ "to enable model loading in different precisions. Pass your own `torch_dtype` to specify the "
207
+ "dtype of the remaining non-linear layers, or pass torch_dtype=torch.bfloat16, to remove this warning."
208
+ )
209
+ torch_dtype = torch.bfloat16
210
+
211
+ return torch_dtype
212
+
213
+ def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype":
214
+ quant_type = self.quantization_config.quant_type
215
+ from accelerate.utils import CustomDtype
216
+
217
+ if isinstance(quant_type, str):
218
+ if quant_type.startswith("int8"):
219
+ # Note that int4 weights are created by packing into torch.int8, but since there is no torch.int4, we use torch.int8
220
+ return torch.int8
221
+ elif quant_type.startswith("int4"):
222
+ return CustomDtype.INT4
223
+ elif quant_type == "uintx_weight_only":
224
+ return self.quantization_config.quant_type_kwargs.get("dtype", torch.uint8)
225
+ elif quant_type.startswith("uint"):
226
+ return {
227
+ 1: torch.uint1,
228
+ 2: torch.uint2,
229
+ 3: torch.uint3,
230
+ 4: torch.uint4,
231
+ 5: torch.uint5,
232
+ 6: torch.uint6,
233
+ 7: torch.uint7,
234
+ }[int(quant_type[4])]
235
+ elif quant_type.startswith("float") or quant_type.startswith("fp"):
236
+ return torch.bfloat16
237
+
238
+ elif is_torchao_version(">", "0.9.0"):
239
+ from torchao.core.config import AOBaseConfig
240
+
241
+ quant_type = self.quantization_config.quant_type
242
+ if isinstance(quant_type, AOBaseConfig):
243
+ # Extract size digit using fuzzy match on the class name
244
+ config_name = quant_type.__class__.__name__
245
+ size_digit = fuzzy_match_size(config_name)
246
+
247
+ # Map the extracted digit to appropriate dtype
248
+ if size_digit == "4":
249
+ return CustomDtype.INT4
250
+ else:
251
+ # Default to int8
252
+ return torch.int8
253
+
254
+ if isinstance(target_dtype, SUPPORTED_TORCH_DTYPES_FOR_QUANTIZATION):
255
+ return target_dtype
256
+
257
+ # We need one of the supported dtypes to be selected in order for accelerate to determine
258
+ # the total size of modules/parameters for auto device placement.
259
+ possible_device_maps = ["auto", "balanced", "balanced_low_0", "sequential"]
260
+ raise ValueError(
261
+ f"You have set `device_map` as one of {possible_device_maps} on a TorchAO quantized model but a suitable target dtype "
262
+ f"could not be inferred. The supported target_dtypes are: {SUPPORTED_TORCH_DTYPES_FOR_QUANTIZATION}. If you think the "
263
+ f"dtype you are using should be supported, please open an issue at https://github.com/huggingface/diffusers/issues."
264
+ )
265
+
266
+ def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]:
267
+ max_memory = {key: val * 0.9 for key, val in max_memory.items()}
268
+ return max_memory
269
+
270
+ def check_if_quantized_param(
271
+ self,
272
+ model: "ModelMixin",
273
+ param_value: "torch.Tensor",
274
+ param_name: str,
275
+ state_dict: Dict[str, Any],
276
+ **kwargs,
277
+ ) -> bool:
278
+ param_device = kwargs.pop("param_device", None)
279
+ # Check if the param_name is not in self.modules_to_not_convert
280
+ if any((key + "." in param_name) or (key == param_name) for key in self.modules_to_not_convert):
281
+ return False
282
+ elif param_device == "cpu" and self.offload:
283
+ # We don't quantize weights that we offload
284
+ return False
285
+ else:
286
+ # We only quantize the weight of nn.Linear
287
+ module, tensor_name = get_module_from_name(model, param_name)
288
+ return isinstance(module, torch.nn.Linear) and (tensor_name == "weight")
289
+
290
+ def create_quantized_param(
291
+ self,
292
+ model: "ModelMixin",
293
+ param_value: "torch.Tensor",
294
+ param_name: str,
295
+ target_device: "torch.device",
296
+ state_dict: Dict[str, Any],
297
+ unexpected_keys: List[str],
298
+ **kwargs,
299
+ ):
300
+ r"""
301
+ Each nn.Linear layer that needs to be quantized is processed here. First, we set the value the weight tensor,
302
+ then we move it to the target device. Finally, we quantize the module.
303
+ """
304
+ module, tensor_name = get_module_from_name(model, param_name)
305
+
306
+ if self.pre_quantized:
307
+ # If we're loading pre-quantized weights, replace the repr of linear layers for pretty printing info
308
+ # about AffineQuantizedTensor
309
+ module._parameters[tensor_name] = torch.nn.Parameter(param_value.to(device=target_device))
310
+ if isinstance(module, nn.Linear):
311
+ module.extra_repr = types.MethodType(_linear_extra_repr, module)
312
+ else:
313
+ # As we perform quantization here, the repr of linear layers is that of AQT, so we don't have to do it ourselves
314
+ module._parameters[tensor_name] = torch.nn.Parameter(param_value).to(device=target_device)
315
+ quantize_(module, self.quantization_config.get_apply_tensor_subclass())
316
+
317
+ def get_cuda_warm_up_factor(self):
318
+ """
319
+ This factor is used in caching_allocator_warmup to determine how many bytes to pre-allocate for CUDA warmup.
320
+ - A factor of 2 means we pre-allocate the full memory footprint of the model.
321
+ - A factor of 4 means we pre-allocate half of that, and so on
322
+
323
+ However, when using TorchAO, calculating memory usage with param.numel() * param.element_size() doesn't give
324
+ the correct size for quantized weights (like int4 or int8) That's because TorchAO internally represents
325
+ quantized tensors using subtensors and metadata, and the reported element_size() still corresponds to the
326
+ torch_dtype not the actual bit-width of the quantized data.
327
+
328
+ To correct for this:
329
+ - Use a division factor of 8 for int4 weights
330
+ - Use a division factor of 4 for int8 weights
331
+ """
332
+ # Original mapping for non-AOBaseConfig types
333
+ # For the uint types, this is a best guess. Once these types become more used
334
+ # we can look into their nuances.
335
+ if is_torchao_version(">", "0.9.0"):
336
+ from torchao.core.config import AOBaseConfig
337
+
338
+ quant_type = self.quantization_config.quant_type
339
+ # For autoquant case, it will be treated in the string implementation below in map_to_target_dtype
340
+ if isinstance(quant_type, AOBaseConfig):
341
+ # Extract size digit using fuzzy match on the class name
342
+ config_name = quant_type.__class__.__name__
343
+ size_digit = fuzzy_match_size(config_name)
344
+
345
+ if size_digit == "4":
346
+ return 8
347
+ else:
348
+ return 4
349
+
350
+ map_to_target_dtype = {"int4_*": 8, "int8_*": 4, "uint*": 8, "float8*": 4}
351
+ quant_type = self.quantization_config.quant_type
352
+ for pattern, target_dtype in map_to_target_dtype.items():
353
+ if fnmatch(quant_type, pattern):
354
+ return target_dtype
355
+ raise ValueError(f"Unsupported quant_type: {quant_type!r}")
356
+
357
+ def _process_model_before_weight_loading(
358
+ self,
359
+ model: "ModelMixin",
360
+ device_map,
361
+ keep_in_fp32_modules: List[str] = [],
362
+ **kwargs,
363
+ ):
364
+ self.modules_to_not_convert = self.quantization_config.modules_to_not_convert
365
+
366
+ if not isinstance(self.modules_to_not_convert, list):
367
+ self.modules_to_not_convert = [self.modules_to_not_convert]
368
+
369
+ self.modules_to_not_convert.extend(keep_in_fp32_modules)
370
+
371
+ # Extend `self.modules_to_not_convert` to keys that are supposed to be offloaded to `cpu` or `disk`
372
+ if isinstance(device_map, dict) and len(device_map.keys()) > 1:
373
+ keys_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]]
374
+ self.modules_to_not_convert.extend(keys_on_cpu)
375
+
376
+ # Purge `None`.
377
+ # Unlike `transformers`, we don't know if we should always keep certain modules in FP32
378
+ # in case of diffusion transformer models. For language models and others alike, `lm_head`
379
+ # and tied modules are usually kept in FP32.
380
+ self.modules_to_not_convert = [module for module in self.modules_to_not_convert if module is not None]
381
+
382
+ model.config.quantization_config = self.quantization_config
383
+
384
+ def _process_model_after_weight_loading(self, model: "ModelMixin"):
385
+ return model
386
+
387
+ def is_serializable(self, safe_serialization=None):
388
+ # TODO(aryan): needs to be tested
389
+ if safe_serialization:
390
+ logger.warning(
391
+ "torchao quantized model does not support safe serialization, please set `safe_serialization` to False."
392
+ )
393
+ return False
394
+
395
+ _is_torchao_serializable = version.parse(importlib.metadata.version("huggingface_hub")) >= version.parse(
396
+ "0.25.0"
397
+ )
398
+
399
+ if not _is_torchao_serializable:
400
+ logger.warning("torchao quantized model is only serializable after huggingface_hub >= 0.25.0 ")
401
+
402
+ if self.offload and self.quantization_config.modules_to_not_convert is None:
403
+ logger.warning(
404
+ "The model contains offloaded modules and these modules are not quantized. We don't recommend saving the model as we won't be able to reload them."
405
+ "If you want to specify modules to not quantize, please specify modules_to_not_convert in the quantization_config."
406
+ )
407
+ return False
408
+
409
+ return _is_torchao_serializable
410
+
411
+ @property
412
+ def is_trainable(self):
413
+ return self.quantization_config.quant_type.startswith("int8")
414
+
415
+ @property
416
+ def is_compileable(self) -> bool:
417
+ return True
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/README.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Schedulers
2
+
3
+ For more information on the schedulers, please refer to the [docs](https://huggingface.co/docs/diffusers/api/schedulers/overview).
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/__init__.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+ from typing import TYPE_CHECKING
16
+
17
+ from ..utils import (
18
+ DIFFUSERS_SLOW_IMPORT,
19
+ OptionalDependencyNotAvailable,
20
+ _LazyModule,
21
+ get_objects_from_module,
22
+ is_flax_available,
23
+ is_scipy_available,
24
+ is_torch_available,
25
+ is_torchsde_available,
26
+ )
27
+
28
+
29
+ _dummy_modules = {}
30
+ _import_structure = {}
31
+
32
+ try:
33
+ if not is_torch_available():
34
+ raise OptionalDependencyNotAvailable()
35
+ except OptionalDependencyNotAvailable:
36
+ from ..utils import dummy_pt_objects # noqa F403
37
+
38
+ _dummy_modules.update(get_objects_from_module(dummy_pt_objects))
39
+
40
+ else:
41
+ _import_structure["deprecated"] = ["KarrasVeScheduler", "ScoreSdeVpScheduler"]
42
+ _import_structure["scheduling_amused"] = ["AmusedScheduler"]
43
+ _import_structure["scheduling_consistency_decoder"] = ["ConsistencyDecoderScheduler"]
44
+ _import_structure["scheduling_consistency_models"] = ["CMStochasticIterativeScheduler"]
45
+ _import_structure["scheduling_ddim"] = ["DDIMScheduler"]
46
+ _import_structure["scheduling_ddim_cogvideox"] = ["CogVideoXDDIMScheduler"]
47
+ _import_structure["scheduling_ddim_inverse"] = ["DDIMInverseScheduler"]
48
+ _import_structure["scheduling_ddim_parallel"] = ["DDIMParallelScheduler"]
49
+ _import_structure["scheduling_ddpm"] = ["DDPMScheduler"]
50
+ _import_structure["scheduling_ddpm_parallel"] = ["DDPMParallelScheduler"]
51
+ _import_structure["scheduling_ddpm_wuerstchen"] = ["DDPMWuerstchenScheduler"]
52
+ _import_structure["scheduling_deis_multistep"] = ["DEISMultistepScheduler"]
53
+ _import_structure["scheduling_dpm_cogvideox"] = ["CogVideoXDPMScheduler"]
54
+ _import_structure["scheduling_dpmsolver_multistep"] = ["DPMSolverMultistepScheduler"]
55
+ _import_structure["scheduling_dpmsolver_multistep_inverse"] = ["DPMSolverMultistepInverseScheduler"]
56
+ _import_structure["scheduling_dpmsolver_singlestep"] = ["DPMSolverSinglestepScheduler"]
57
+ _import_structure["scheduling_edm_dpmsolver_multistep"] = ["EDMDPMSolverMultistepScheduler"]
58
+ _import_structure["scheduling_edm_euler"] = ["EDMEulerScheduler"]
59
+ _import_structure["scheduling_euler_ancestral_discrete"] = ["EulerAncestralDiscreteScheduler"]
60
+ _import_structure["scheduling_euler_discrete"] = ["EulerDiscreteScheduler"]
61
+ _import_structure["scheduling_flow_match_euler_discrete"] = ["FlowMatchEulerDiscreteScheduler"]
62
+ _import_structure["scheduling_flow_match_heun_discrete"] = ["FlowMatchHeunDiscreteScheduler"]
63
+ _import_structure["scheduling_flow_match_lcm"] = ["FlowMatchLCMScheduler"]
64
+ _import_structure["scheduling_heun_discrete"] = ["HeunDiscreteScheduler"]
65
+ _import_structure["scheduling_ipndm"] = ["IPNDMScheduler"]
66
+ _import_structure["scheduling_k_dpm_2_ancestral_discrete"] = ["KDPM2AncestralDiscreteScheduler"]
67
+ _import_structure["scheduling_k_dpm_2_discrete"] = ["KDPM2DiscreteScheduler"]
68
+ _import_structure["scheduling_lcm"] = ["LCMScheduler"]
69
+ _import_structure["scheduling_pndm"] = ["PNDMScheduler"]
70
+ _import_structure["scheduling_repaint"] = ["RePaintScheduler"]
71
+ _import_structure["scheduling_sasolver"] = ["SASolverScheduler"]
72
+ _import_structure["scheduling_scm"] = ["SCMScheduler"]
73
+ _import_structure["scheduling_sde_ve"] = ["ScoreSdeVeScheduler"]
74
+ _import_structure["scheduling_tcd"] = ["TCDScheduler"]
75
+ _import_structure["scheduling_unclip"] = ["UnCLIPScheduler"]
76
+ _import_structure["scheduling_unipc_multistep"] = ["UniPCMultistepScheduler"]
77
+ _import_structure["scheduling_utils"] = ["AysSchedules", "KarrasDiffusionSchedulers", "SchedulerMixin"]
78
+ _import_structure["scheduling_vq_diffusion"] = ["VQDiffusionScheduler"]
79
+
80
+ try:
81
+ if not is_flax_available():
82
+ raise OptionalDependencyNotAvailable()
83
+ except OptionalDependencyNotAvailable:
84
+ from ..utils import dummy_flax_objects # noqa F403
85
+
86
+ _dummy_modules.update(get_objects_from_module(dummy_flax_objects))
87
+
88
+ else:
89
+ _import_structure["scheduling_ddim_flax"] = ["FlaxDDIMScheduler"]
90
+ _import_structure["scheduling_ddpm_flax"] = ["FlaxDDPMScheduler"]
91
+ _import_structure["scheduling_dpmsolver_multistep_flax"] = ["FlaxDPMSolverMultistepScheduler"]
92
+ _import_structure["scheduling_euler_discrete_flax"] = ["FlaxEulerDiscreteScheduler"]
93
+ _import_structure["scheduling_karras_ve_flax"] = ["FlaxKarrasVeScheduler"]
94
+ _import_structure["scheduling_lms_discrete_flax"] = ["FlaxLMSDiscreteScheduler"]
95
+ _import_structure["scheduling_pndm_flax"] = ["FlaxPNDMScheduler"]
96
+ _import_structure["scheduling_sde_ve_flax"] = ["FlaxScoreSdeVeScheduler"]
97
+ _import_structure["scheduling_utils_flax"] = [
98
+ "FlaxKarrasDiffusionSchedulers",
99
+ "FlaxSchedulerMixin",
100
+ "FlaxSchedulerOutput",
101
+ "broadcast_to_shape_from_left",
102
+ ]
103
+
104
+
105
+ try:
106
+ if not (is_torch_available() and is_scipy_available()):
107
+ raise OptionalDependencyNotAvailable()
108
+ except OptionalDependencyNotAvailable:
109
+ from ..utils import dummy_torch_and_scipy_objects # noqa F403
110
+
111
+ _dummy_modules.update(get_objects_from_module(dummy_torch_and_scipy_objects))
112
+
113
+ else:
114
+ _import_structure["scheduling_lms_discrete"] = ["LMSDiscreteScheduler"]
115
+
116
+ try:
117
+ if not (is_torch_available() and is_torchsde_available()):
118
+ raise OptionalDependencyNotAvailable()
119
+ except OptionalDependencyNotAvailable:
120
+ from ..utils import dummy_torch_and_torchsde_objects # noqa F403
121
+
122
+ _dummy_modules.update(get_objects_from_module(dummy_torch_and_torchsde_objects))
123
+
124
+ else:
125
+ _import_structure["scheduling_cosine_dpmsolver_multistep"] = ["CosineDPMSolverMultistepScheduler"]
126
+ _import_structure["scheduling_dpmsolver_sde"] = ["DPMSolverSDEScheduler"]
127
+
128
+ if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
129
+ from ..utils import (
130
+ OptionalDependencyNotAvailable,
131
+ is_flax_available,
132
+ is_scipy_available,
133
+ is_torch_available,
134
+ is_torchsde_available,
135
+ )
136
+
137
+ try:
138
+ if not is_torch_available():
139
+ raise OptionalDependencyNotAvailable()
140
+ except OptionalDependencyNotAvailable:
141
+ from ..utils.dummy_pt_objects import * # noqa F403
142
+ else:
143
+ from .deprecated import KarrasVeScheduler, ScoreSdeVpScheduler
144
+ from .scheduling_amused import AmusedScheduler
145
+ from .scheduling_consistency_decoder import ConsistencyDecoderScheduler
146
+ from .scheduling_consistency_models import CMStochasticIterativeScheduler
147
+ from .scheduling_ddim import DDIMScheduler
148
+ from .scheduling_ddim_cogvideox import CogVideoXDDIMScheduler
149
+ from .scheduling_ddim_inverse import DDIMInverseScheduler
150
+ from .scheduling_ddim_parallel import DDIMParallelScheduler
151
+ from .scheduling_ddpm import DDPMScheduler
152
+ from .scheduling_ddpm_parallel import DDPMParallelScheduler
153
+ from .scheduling_ddpm_wuerstchen import DDPMWuerstchenScheduler
154
+ from .scheduling_deis_multistep import DEISMultistepScheduler
155
+ from .scheduling_dpm_cogvideox import CogVideoXDPMScheduler
156
+ from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler
157
+ from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler
158
+ from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler
159
+ from .scheduling_edm_dpmsolver_multistep import EDMDPMSolverMultistepScheduler
160
+ from .scheduling_edm_euler import EDMEulerScheduler
161
+ from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler
162
+ from .scheduling_euler_discrete import EulerDiscreteScheduler
163
+ from .scheduling_flow_match_euler_discrete import FlowMatchEulerDiscreteScheduler
164
+ from .scheduling_flow_match_heun_discrete import FlowMatchHeunDiscreteScheduler
165
+ from .scheduling_flow_match_lcm import FlowMatchLCMScheduler
166
+ from .scheduling_heun_discrete import HeunDiscreteScheduler
167
+ from .scheduling_ipndm import IPNDMScheduler
168
+ from .scheduling_k_dpm_2_ancestral_discrete import KDPM2AncestralDiscreteScheduler
169
+ from .scheduling_k_dpm_2_discrete import KDPM2DiscreteScheduler
170
+ from .scheduling_lcm import LCMScheduler
171
+ from .scheduling_pndm import PNDMScheduler
172
+ from .scheduling_repaint import RePaintScheduler
173
+ from .scheduling_sasolver import SASolverScheduler
174
+ from .scheduling_scm import SCMScheduler
175
+ from .scheduling_sde_ve import ScoreSdeVeScheduler
176
+ from .scheduling_tcd import TCDScheduler
177
+ from .scheduling_unclip import UnCLIPScheduler
178
+ from .scheduling_unipc_multistep import UniPCMultistepScheduler
179
+ from .scheduling_utils import AysSchedules, KarrasDiffusionSchedulers, SchedulerMixin
180
+ from .scheduling_vq_diffusion import VQDiffusionScheduler
181
+ try:
182
+ if not is_flax_available():
183
+ raise OptionalDependencyNotAvailable()
184
+ except OptionalDependencyNotAvailable:
185
+ from ..utils.dummy_flax_objects import * # noqa F403
186
+ else:
187
+ from .scheduling_ddim_flax import FlaxDDIMScheduler
188
+ from .scheduling_ddpm_flax import FlaxDDPMScheduler
189
+ from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler
190
+ from .scheduling_euler_discrete_flax import FlaxEulerDiscreteScheduler
191
+ from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler
192
+ from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler
193
+ from .scheduling_pndm_flax import FlaxPNDMScheduler
194
+ from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler
195
+ from .scheduling_utils_flax import (
196
+ FlaxKarrasDiffusionSchedulers,
197
+ FlaxSchedulerMixin,
198
+ FlaxSchedulerOutput,
199
+ broadcast_to_shape_from_left,
200
+ )
201
+
202
+ try:
203
+ if not (is_torch_available() and is_scipy_available()):
204
+ raise OptionalDependencyNotAvailable()
205
+ except OptionalDependencyNotAvailable:
206
+ from ..utils.dummy_torch_and_scipy_objects import * # noqa F403
207
+ else:
208
+ from .scheduling_lms_discrete import LMSDiscreteScheduler
209
+
210
+ try:
211
+ if not (is_torch_available() and is_torchsde_available()):
212
+ raise OptionalDependencyNotAvailable()
213
+ except OptionalDependencyNotAvailable:
214
+ from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403
215
+ else:
216
+ from .scheduling_cosine_dpmsolver_multistep import CosineDPMSolverMultistepScheduler
217
+ from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
218
+
219
+ else:
220
+ import sys
221
+
222
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
223
+ for name, value in _dummy_modules.items():
224
+ setattr(sys.modules[__name__], name, value)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/deprecated/__init__.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING
2
+
3
+ from ...utils import (
4
+ DIFFUSERS_SLOW_IMPORT,
5
+ OptionalDependencyNotAvailable,
6
+ _LazyModule,
7
+ get_objects_from_module,
8
+ is_torch_available,
9
+ is_transformers_available,
10
+ )
11
+
12
+
13
+ _dummy_objects = {}
14
+ _import_structure = {}
15
+
16
+ try:
17
+ if not (is_transformers_available() and is_torch_available()):
18
+ raise OptionalDependencyNotAvailable()
19
+ except OptionalDependencyNotAvailable:
20
+ from ...utils import dummy_pt_objects # noqa F403
21
+
22
+ _dummy_objects.update(get_objects_from_module(dummy_pt_objects))
23
+ else:
24
+ _import_structure["scheduling_karras_ve"] = ["KarrasVeScheduler"]
25
+ _import_structure["scheduling_sde_vp"] = ["ScoreSdeVpScheduler"]
26
+
27
+ if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
28
+ try:
29
+ if not is_torch_available():
30
+ raise OptionalDependencyNotAvailable()
31
+
32
+ except OptionalDependencyNotAvailable:
33
+ from ...utils.dummy_pt_objects import * # noqa F403
34
+ else:
35
+ from .scheduling_karras_ve import KarrasVeScheduler
36
+ from .scheduling_sde_vp import ScoreSdeVpScheduler
37
+
38
+
39
+ else:
40
+ import sys
41
+
42
+ sys.modules[__name__] = _LazyModule(
43
+ __name__,
44
+ globals()["__file__"],
45
+ _import_structure,
46
+ module_spec=__spec__,
47
+ )
48
+
49
+ for name, value in _dummy_objects.items():
50
+ setattr(sys.modules[__name__], name, value)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/deprecated/scheduling_karras_ve.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 NVIDIA and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from dataclasses import dataclass
17
+ from typing import Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+
22
+ from ...configuration_utils import ConfigMixin, register_to_config
23
+ from ...utils import BaseOutput
24
+ from ...utils.torch_utils import randn_tensor
25
+ from ..scheduling_utils import SchedulerMixin
26
+
27
+
28
+ @dataclass
29
+ class KarrasVeOutput(BaseOutput):
30
+ """
31
+ Output class for the scheduler's step function output.
32
+
33
+ Args:
34
+ prev_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
35
+ Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the
36
+ denoising loop.
37
+ derivative (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
38
+ Derivative of predicted original image sample (x_0).
39
+ pred_original_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
40
+ The predicted denoised sample (x_{0}) based on the model output from the current timestep.
41
+ `pred_original_sample` can be used to preview progress or for guidance.
42
+ """
43
+
44
+ prev_sample: torch.Tensor
45
+ derivative: torch.Tensor
46
+ pred_original_sample: Optional[torch.Tensor] = None
47
+
48
+
49
+ class KarrasVeScheduler(SchedulerMixin, ConfigMixin):
50
+ """
51
+ A stochastic scheduler tailored to variance-expanding models.
52
+
53
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
54
+ methods the library implements for all schedulers such as loading and saving.
55
+
56
+ > [!TIP] > For more details on the parameters, see [Appendix E](https://huggingface.co/papers/2206.00364). The grid
57
+ search > values used to find the optimal `{s_noise, s_churn, s_min, s_max}` for a specific model are described in
58
+ Table 5 of > the paper.
59
+
60
+ Args:
61
+ sigma_min (`float`, defaults to 0.02):
62
+ The minimum noise magnitude.
63
+ sigma_max (`float`, defaults to 100):
64
+ The maximum noise magnitude.
65
+ s_noise (`float`, defaults to 1.007):
66
+ The amount of additional noise to counteract loss of detail during sampling. A reasonable range is [1.000,
67
+ 1.011].
68
+ s_churn (`float`, defaults to 80):
69
+ The parameter controlling the overall amount of stochasticity. A reasonable range is [0, 100].
70
+ s_min (`float`, defaults to 0.05):
71
+ The start value of the sigma range to add noise (enable stochasticity). A reasonable range is [0, 10].
72
+ s_max (`float`, defaults to 50):
73
+ The end value of the sigma range to add noise. A reasonable range is [0.2, 80].
74
+ """
75
+
76
+ order = 2
77
+
78
+ @register_to_config
79
+ def __init__(
80
+ self,
81
+ sigma_min: float = 0.02,
82
+ sigma_max: float = 100,
83
+ s_noise: float = 1.007,
84
+ s_churn: float = 80,
85
+ s_min: float = 0.05,
86
+ s_max: float = 50,
87
+ ):
88
+ # standard deviation of the initial noise distribution
89
+ self.init_noise_sigma = sigma_max
90
+
91
+ # setable values
92
+ self.num_inference_steps: int = None
93
+ self.timesteps: np.IntTensor = None
94
+ self.schedule: torch.Tensor = None # sigma(t_i)
95
+
96
+ def scale_model_input(self, sample: torch.Tensor, timestep: Optional[int] = None) -> torch.Tensor:
97
+ """
98
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
99
+ current timestep.
100
+
101
+ Args:
102
+ sample (`torch.Tensor`):
103
+ The input sample.
104
+ timestep (`int`, *optional*):
105
+ The current timestep in the diffusion chain.
106
+
107
+ Returns:
108
+ `torch.Tensor`:
109
+ A scaled input sample.
110
+ """
111
+ return sample
112
+
113
+ def set_timesteps(self, num_inference_steps: int, device: Union[str, torch.device] = None):
114
+ """
115
+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
116
+
117
+ Args:
118
+ num_inference_steps (`int`):
119
+ The number of diffusion steps used when generating samples with a pre-trained model.
120
+ device (`str` or `torch.device`, *optional*):
121
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
122
+ """
123
+ self.num_inference_steps = num_inference_steps
124
+ timesteps = np.arange(0, self.num_inference_steps)[::-1].copy()
125
+ self.timesteps = torch.from_numpy(timesteps).to(device)
126
+ schedule = [
127
+ (
128
+ self.config.sigma_max**2
129
+ * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1))
130
+ )
131
+ for i in self.timesteps
132
+ ]
133
+ self.schedule = torch.tensor(schedule, dtype=torch.float32, device=device)
134
+
135
+ def add_noise_to_input(
136
+ self, sample: torch.Tensor, sigma: float, generator: Optional[torch.Generator] = None
137
+ ) -> Tuple[torch.Tensor, float]:
138
+ """
139
+ Explicit Langevin-like "churn" step of adding noise to the sample according to a `gamma_i ≥ 0` to reach a
140
+ higher noise level `sigma_hat = sigma_i + gamma_i*sigma_i`.
141
+
142
+ Args:
143
+ sample (`torch.Tensor`):
144
+ The input sample.
145
+ sigma (`float`):
146
+ generator (`torch.Generator`, *optional*):
147
+ A random number generator.
148
+ """
149
+ if self.config.s_min <= sigma <= self.config.s_max:
150
+ gamma = min(self.config.s_churn / self.num_inference_steps, 2**0.5 - 1)
151
+ else:
152
+ gamma = 0
153
+
154
+ # sample eps ~ N(0, S_noise^2 * I)
155
+ eps = self.config.s_noise * randn_tensor(sample.shape, generator=generator).to(sample.device)
156
+ sigma_hat = sigma + gamma * sigma
157
+ sample_hat = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps)
158
+
159
+ return sample_hat, sigma_hat
160
+
161
+ def step(
162
+ self,
163
+ model_output: torch.Tensor,
164
+ sigma_hat: float,
165
+ sigma_prev: float,
166
+ sample_hat: torch.Tensor,
167
+ return_dict: bool = True,
168
+ ) -> Union[KarrasVeOutput, Tuple]:
169
+ """
170
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
171
+ process from the learned model outputs (most often the predicted noise).
172
+
173
+ Args:
174
+ model_output (`torch.Tensor`):
175
+ The direct output from learned diffusion model.
176
+ sigma_hat (`float`):
177
+ sigma_prev (`float`):
178
+ sample_hat (`torch.Tensor`):
179
+ return_dict (`bool`, *optional*, defaults to `True`):
180
+ Whether or not to return a [`~schedulers.scheduling_karras_ve.KarrasVESchedulerOutput`] or `tuple`.
181
+
182
+ Returns:
183
+ [`~schedulers.scheduling_karras_ve.KarrasVESchedulerOutput`] or `tuple`:
184
+ If return_dict is `True`, [`~schedulers.scheduling_karras_ve.KarrasVESchedulerOutput`] is returned,
185
+ otherwise a tuple is returned where the first element is the sample tensor.
186
+
187
+ """
188
+
189
+ pred_original_sample = sample_hat + sigma_hat * model_output
190
+ derivative = (sample_hat - pred_original_sample) / sigma_hat
191
+ sample_prev = sample_hat + (sigma_prev - sigma_hat) * derivative
192
+
193
+ if not return_dict:
194
+ return (sample_prev, derivative)
195
+
196
+ return KarrasVeOutput(
197
+ prev_sample=sample_prev, derivative=derivative, pred_original_sample=pred_original_sample
198
+ )
199
+
200
+ def step_correct(
201
+ self,
202
+ model_output: torch.Tensor,
203
+ sigma_hat: float,
204
+ sigma_prev: float,
205
+ sample_hat: torch.Tensor,
206
+ sample_prev: torch.Tensor,
207
+ derivative: torch.Tensor,
208
+ return_dict: bool = True,
209
+ ) -> Union[KarrasVeOutput, Tuple]:
210
+ """
211
+ Corrects the predicted sample based on the `model_output` of the network.
212
+
213
+ Args:
214
+ model_output (`torch.Tensor`):
215
+ The direct output from learned diffusion model.
216
+ sigma_hat (`float`): TODO
217
+ sigma_prev (`float`): TODO
218
+ sample_hat (`torch.Tensor`): TODO
219
+ sample_prev (`torch.Tensor`): TODO
220
+ derivative (`torch.Tensor`): TODO
221
+ return_dict (`bool`, *optional*, defaults to `True`):
222
+ Whether or not to return a [`~schedulers.scheduling_ddpm.DDPMSchedulerOutput`] or `tuple`.
223
+
224
+ Returns:
225
+ prev_sample (TODO): updated sample in the diffusion chain. derivative (TODO): TODO
226
+
227
+ """
228
+ pred_original_sample = sample_prev + sigma_prev * model_output
229
+ derivative_corr = (sample_prev - pred_original_sample) / sigma_prev
230
+ sample_prev = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr)
231
+
232
+ if not return_dict:
233
+ return (sample_prev, derivative)
234
+
235
+ return KarrasVeOutput(
236
+ prev_sample=sample_prev, derivative=derivative, pred_original_sample=pred_original_sample
237
+ )
238
+
239
+ def add_noise(self, original_samples, noise, timesteps):
240
+ raise NotImplementedError()
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/deprecated/scheduling_sde_vp.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Google Brain and 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
+ # DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch
16
+
17
+ import math
18
+ from typing import Union
19
+
20
+ import torch
21
+
22
+ from ...configuration_utils import ConfigMixin, register_to_config
23
+ from ...utils.torch_utils import randn_tensor
24
+ from ..scheduling_utils import SchedulerMixin
25
+
26
+
27
+ class ScoreSdeVpScheduler(SchedulerMixin, ConfigMixin):
28
+ """
29
+ `ScoreSdeVpScheduler` is a variance preserving stochastic differential equation (SDE) scheduler.
30
+
31
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
32
+ methods the library implements for all schedulers such as loading and saving.
33
+
34
+ Args:
35
+ num_train_timesteps (`int`, defaults to 2000):
36
+ The number of diffusion steps to train the model.
37
+ beta_min (`int`, defaults to 0.1):
38
+ beta_max (`int`, defaults to 20):
39
+ sampling_eps (`int`, defaults to 1e-3):
40
+ The end value of sampling where timesteps decrease progressively from 1 to epsilon.
41
+ """
42
+
43
+ order = 1
44
+
45
+ @register_to_config
46
+ def __init__(self, num_train_timesteps=2000, beta_min=0.1, beta_max=20, sampling_eps=1e-3):
47
+ self.sigmas = None
48
+ self.discrete_sigmas = None
49
+ self.timesteps = None
50
+
51
+ def set_timesteps(self, num_inference_steps, device: Union[str, torch.device] = None):
52
+ """
53
+ Sets the continuous timesteps used for the diffusion chain (to be run before inference).
54
+
55
+ Args:
56
+ num_inference_steps (`int`):
57
+ The number of diffusion steps used when generating samples with a pre-trained model.
58
+ device (`str` or `torch.device`, *optional*):
59
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
60
+ """
61
+ self.timesteps = torch.linspace(1, self.config.sampling_eps, num_inference_steps, device=device)
62
+
63
+ def step_pred(self, score, x, t, generator=None):
64
+ """
65
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
66
+ process from the learned model outputs (most often the predicted noise).
67
+
68
+ Args:
69
+ score ():
70
+ x ():
71
+ t ():
72
+ generator (`torch.Generator`, *optional*):
73
+ A random number generator.
74
+ """
75
+ if self.timesteps is None:
76
+ raise ValueError(
77
+ "`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler"
78
+ )
79
+
80
+ # TODO(Patrick) better comments + non-PyTorch
81
+ # postprocess model score
82
+ log_mean_coeff = -0.25 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min
83
+ std = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff))
84
+ std = std.flatten()
85
+ while len(std.shape) < len(score.shape):
86
+ std = std.unsqueeze(-1)
87
+ score = -score / std
88
+
89
+ # compute
90
+ dt = -1.0 / len(self.timesteps)
91
+
92
+ beta_t = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min)
93
+ beta_t = beta_t.flatten()
94
+ while len(beta_t.shape) < len(x.shape):
95
+ beta_t = beta_t.unsqueeze(-1)
96
+ drift = -0.5 * beta_t * x
97
+
98
+ diffusion = torch.sqrt(beta_t)
99
+ drift = drift - diffusion**2 * score
100
+ x_mean = x + drift * dt
101
+
102
+ # add noise
103
+ noise = randn_tensor(x.shape, layout=x.layout, generator=generator, device=x.device, dtype=x.dtype)
104
+ x = x_mean + diffusion * math.sqrt(-dt) * noise
105
+
106
+ return x, x_mean
107
+
108
+ def __len__(self):
109
+ return self.config.num_train_timesteps
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/scheduling_amused.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from dataclasses import dataclass
3
+ from typing import List, Literal, Optional, Tuple, Union
4
+
5
+ import torch
6
+
7
+ from ..configuration_utils import ConfigMixin, register_to_config
8
+ from ..utils import BaseOutput
9
+ from .scheduling_utils import SchedulerMixin
10
+
11
+
12
+ def gumbel_noise(t: torch.Tensor, generator: Optional[torch.Generator] = None) -> torch.Tensor:
13
+ """
14
+ Generate Gumbel noise for sampling.
15
+
16
+ Args:
17
+ t (`torch.Tensor`):
18
+ Input tensor to match the shape and dtype of the output noise.
19
+ generator (`torch.Generator`, *optional*):
20
+ A random number generator for reproducible sampling.
21
+
22
+ Returns:
23
+ `torch.Tensor`:
24
+ Gumbel-distributed noise with the same shape, dtype, and device as the input tensor.
25
+ """
26
+ device = generator.device if generator is not None else t.device
27
+ noise = torch.zeros_like(t, device=device).uniform_(0, 1, generator=generator).to(t.device)
28
+ return -torch.log((-torch.log(noise.clamp(1e-20))).clamp(1e-20))
29
+
30
+
31
+ def mask_by_random_topk(
32
+ mask_len: torch.Tensor,
33
+ probs: torch.Tensor,
34
+ temperature: float = 1.0,
35
+ generator: Optional[torch.Generator] = None,
36
+ ) -> torch.Tensor:
37
+ """
38
+ Mask tokens by selecting the top-k lowest confidence scores with temperature-based randomness.
39
+
40
+ Args:
41
+ mask_len (`torch.Tensor`):
42
+ Number of tokens to mask per sample in the batch.
43
+ probs (`torch.Tensor`):
44
+ Probability scores for each token.
45
+ temperature (`float`, *optional*, defaults to 1.0):
46
+ Temperature parameter for controlling randomness in the masking process.
47
+ generator (`torch.Generator`, *optional*):
48
+ A random number generator for reproducible sampling.
49
+
50
+ Returns:
51
+ `torch.Tensor`:
52
+ Boolean mask indicating which tokens should be masked.
53
+ """
54
+ confidence = torch.log(probs.clamp(1e-20)) + temperature * gumbel_noise(probs, generator=generator)
55
+ sorted_confidence = torch.sort(confidence, dim=-1).values
56
+ cut_off = torch.gather(sorted_confidence, 1, mask_len.long())
57
+ masking = confidence < cut_off
58
+ return masking
59
+
60
+
61
+ @dataclass
62
+ class AmusedSchedulerOutput(BaseOutput):
63
+ """
64
+ Output class for the scheduler's `step` function output.
65
+
66
+ Args:
67
+ prev_sample (`torch.LongTensor` of shape `(batch_size, height, width)` or `(batch_size, sequence_length)`):
68
+ Computed sample `(x_{t-1})` of previous timestep with token IDs. `prev_sample` should be used as next model
69
+ input in the denoising loop.
70
+ pred_original_sample (`torch.LongTensor` of shape `(batch_size, height, width)` or `(batch_size, sequence_length)`, *optional*):
71
+ The predicted fully denoised sample `(x_{0})` with token IDs based on the model output from the current
72
+ timestep. `pred_original_sample` can be used to preview progress or for guidance.
73
+ """
74
+
75
+ prev_sample: torch.Tensor
76
+ pred_original_sample: Optional[torch.Tensor] = None
77
+
78
+
79
+ class AmusedScheduler(SchedulerMixin, ConfigMixin):
80
+ """
81
+ A scheduler for masked token generation as used in [`AmusedPipeline`].
82
+
83
+ This scheduler iteratively unmasks tokens based on their confidence scores, following either a cosine or linear
84
+ schedule. Unlike traditional diffusion schedulers that work with continuous pixel values, this scheduler operates
85
+ on discrete token IDs, making it suitable for autoregressive and non-autoregressive masked token generation models.
86
+
87
+ This scheduler inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the
88
+ generic methods the library implements for all schedulers such as loading and saving.
89
+
90
+ Args:
91
+ mask_token_id (`int`):
92
+ The token ID used to represent masked tokens in the sequence.
93
+ masking_schedule (`Literal["cosine", "linear"]`, *optional*, defaults to `"cosine"`):
94
+ The schedule type for determining the mask ratio at each timestep. Can be either `"cosine"` or `"linear"`.
95
+ """
96
+
97
+ order = 1
98
+
99
+ temperatures: Optional[torch.Tensor]
100
+ timesteps: Optional[torch.Tensor]
101
+
102
+ @register_to_config
103
+ def __init__(
104
+ self,
105
+ mask_token_id: int,
106
+ masking_schedule: Literal["cosine", "linear"] = "cosine",
107
+ ):
108
+ self.temperatures = None
109
+ self.timesteps = None
110
+
111
+ def set_timesteps(
112
+ self,
113
+ num_inference_steps: int,
114
+ temperature: Union[float, Tuple[float, float], List[float]] = (2, 0),
115
+ device: Optional[Union[str, torch.device]] = None,
116
+ ) -> None:
117
+ """
118
+ Set the discrete timesteps used for the diffusion chain (to be run before inference).
119
+
120
+ Args:
121
+ num_inference_steps (`int`):
122
+ The number of diffusion steps used when generating samples with a pre-trained model.
123
+ temperature (`Union[float, Tuple[float, float], List[float]]`, *optional*, defaults to `(2, 0)`):
124
+ Temperature parameter(s) for controlling the randomness of sampling. If a tuple or list is provided,
125
+ temperatures will be linearly interpolated between the first and second values across all timesteps. If
126
+ a single value is provided, temperatures will be linearly interpolated from that value to 0.01.
127
+ device (`str` or `torch.device`, *optional*):
128
+ The device to which the timesteps and temperatures should be moved to. If `None`, the timesteps are not
129
+ moved.
130
+ """
131
+ self.timesteps = torch.arange(num_inference_steps, device=device).flip(0)
132
+
133
+ if isinstance(temperature, (tuple, list)):
134
+ self.temperatures = torch.linspace(temperature[0], temperature[1], num_inference_steps, device=device)
135
+ else:
136
+ self.temperatures = torch.linspace(temperature, 0.01, num_inference_steps, device=device)
137
+
138
+ def step(
139
+ self,
140
+ model_output: torch.Tensor,
141
+ timestep: int,
142
+ sample: torch.LongTensor,
143
+ starting_mask_ratio: float = 1.0,
144
+ generator: Optional[torch.Generator] = None,
145
+ return_dict: bool = True,
146
+ ) -> Union[AmusedSchedulerOutput, Tuple[torch.Tensor, torch.Tensor]]:
147
+ """
148
+ Predict the sample at the previous timestep by masking tokens based on confidence scores.
149
+
150
+ Args:
151
+ model_output (`torch.Tensor`):
152
+ The direct output from the learned diffusion model. Typically of shape `(batch_size, num_tokens,
153
+ codebook_size)` or `(batch_size, codebook_size, height, width)` for 2D inputs.
154
+ timestep (`int`):
155
+ The current discrete timestep in the diffusion chain.
156
+ sample (`torch.LongTensor`):
157
+ A current instance of a sample created by the diffusion process. Contains token IDs, with masked
158
+ positions indicated by `mask_token_id`.
159
+ starting_mask_ratio (`float`, *optional*, defaults to 1.0):
160
+ A multiplier applied to the mask ratio schedule. Values less than 1.0 will result in fewer tokens being
161
+ masked at each step.
162
+ generator (`torch.Generator`, *optional*):
163
+ A random number generator for reproducible sampling.
164
+ return_dict (`bool`, *optional*, defaults to `True`):
165
+ Whether to return an [`~schedulers.scheduling_amused.AmusedSchedulerOutput`] or a plain tuple.
166
+
167
+ Returns:
168
+ [`~schedulers.scheduling_amused.AmusedSchedulerOutput`] or `tuple`:
169
+ If `return_dict` is `True`, [`~schedulers.scheduling_amused.AmusedSchedulerOutput`] is returned,
170
+ otherwise a tuple is returned where the first element is the sample tensor (`prev_sample`) and the
171
+ second element is the predicted original sample tensor (`pred_original_sample`).
172
+ """
173
+ two_dim_input = sample.ndim == 3 and model_output.ndim == 4
174
+
175
+ if two_dim_input:
176
+ batch_size, codebook_size, height, width = model_output.shape
177
+ sample = sample.reshape(batch_size, height * width)
178
+ model_output = model_output.reshape(batch_size, codebook_size, height * width).permute(0, 2, 1)
179
+
180
+ unknown_map = sample == self.config.mask_token_id
181
+
182
+ probs = model_output.softmax(dim=-1)
183
+
184
+ device = probs.device
185
+ probs_ = probs.to(generator.device) if generator is not None else probs # handles when generator is on CPU
186
+ if probs_.device.type == "cpu" and probs_.dtype != torch.float32:
187
+ probs_ = probs_.float() # multinomial is not implemented for cpu half precision
188
+ probs_ = probs_.reshape(-1, probs.size(-1))
189
+ pred_original_sample = torch.multinomial(probs_, 1, generator=generator).to(device=device)
190
+ pred_original_sample = pred_original_sample[:, 0].view(*probs.shape[:-1])
191
+ pred_original_sample = torch.where(unknown_map, pred_original_sample, sample)
192
+
193
+ if timestep == 0:
194
+ prev_sample = pred_original_sample
195
+ else:
196
+ seq_len = sample.shape[1]
197
+ step_idx = (self.timesteps == timestep).nonzero()
198
+ ratio = (step_idx + 1) / len(self.timesteps)
199
+
200
+ if self.config.masking_schedule == "cosine":
201
+ mask_ratio = torch.cos(ratio * math.pi / 2)
202
+ elif self.config.masking_schedule == "linear":
203
+ mask_ratio = 1 - ratio
204
+ else:
205
+ raise ValueError(f"unknown masking schedule {self.config.masking_schedule}")
206
+
207
+ mask_ratio = starting_mask_ratio * mask_ratio
208
+
209
+ mask_len = (seq_len * mask_ratio).floor()
210
+ # do not mask more than amount previously masked
211
+ mask_len = torch.min(unknown_map.sum(dim=-1, keepdim=True) - 1, mask_len)
212
+ # mask at least one
213
+ mask_len = torch.max(torch.tensor([1], device=model_output.device), mask_len)
214
+
215
+ selected_probs = torch.gather(probs, -1, pred_original_sample[:, :, None])[:, :, 0]
216
+ # Ignores the tokens given in the input by overwriting their confidence.
217
+ selected_probs = torch.where(unknown_map, selected_probs, torch.finfo(selected_probs.dtype).max)
218
+
219
+ masking = mask_by_random_topk(mask_len, selected_probs, self.temperatures[step_idx], generator)
220
+
221
+ # Masks tokens with lower confidence.
222
+ prev_sample = torch.where(masking, self.config.mask_token_id, pred_original_sample)
223
+
224
+ if two_dim_input:
225
+ prev_sample = prev_sample.reshape(batch_size, height, width)
226
+ pred_original_sample = pred_original_sample.reshape(batch_size, height, width)
227
+
228
+ if not return_dict:
229
+ return (prev_sample, pred_original_sample)
230
+
231
+ return AmusedSchedulerOutput(prev_sample, pred_original_sample)
232
+
233
+ def add_noise(
234
+ self,
235
+ sample: torch.LongTensor,
236
+ timesteps: int,
237
+ generator: Optional[torch.Generator] = None,
238
+ ) -> torch.LongTensor:
239
+ """
240
+ Add noise to a sample by randomly masking tokens according to the masking schedule.
241
+
242
+ Args:
243
+ sample (`torch.LongTensor`):
244
+ The input sample containing token IDs to be partially masked.
245
+ timesteps (`int`):
246
+ The timestep that determines how much masking to apply. Higher timesteps result in more masking.
247
+ generator (`torch.Generator`, *optional*):
248
+ A random number generator for reproducible masking.
249
+
250
+ Returns:
251
+ `torch.LongTensor`:
252
+ The sample with some tokens replaced by `mask_token_id` according to the masking schedule.
253
+ """
254
+ step_idx = (self.timesteps == timesteps).nonzero()
255
+ ratio = (step_idx + 1) / len(self.timesteps)
256
+
257
+ if self.config.masking_schedule == "cosine":
258
+ mask_ratio = torch.cos(ratio * math.pi / 2)
259
+ elif self.config.masking_schedule == "linear":
260
+ mask_ratio = 1 - ratio
261
+ else:
262
+ raise ValueError(f"unknown masking schedule {self.config.masking_schedule}")
263
+
264
+ mask_indices = (
265
+ torch.rand(
266
+ sample.shape, device=generator.device if generator is not None else sample.device, generator=generator
267
+ ).to(sample.device)
268
+ < mask_ratio
269
+ )
270
+
271
+ masked_sample = sample.clone()
272
+
273
+ masked_sample[mask_indices] = self.config.mask_token_id
274
+
275
+ return masked_sample
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/scheduling_consistency_decoder.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from dataclasses import dataclass
3
+ from typing import Literal, Optional, Tuple, Union
4
+
5
+ import torch
6
+
7
+ from ..configuration_utils import ConfigMixin, register_to_config
8
+ from ..utils import BaseOutput
9
+ from ..utils.torch_utils import randn_tensor
10
+ from .scheduling_utils import SchedulerMixin
11
+
12
+
13
+ # Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar
14
+ def betas_for_alpha_bar(
15
+ num_diffusion_timesteps: int,
16
+ max_beta: float = 0.999,
17
+ alpha_transform_type: Literal["cosine", "exp"] = "cosine",
18
+ ) -> torch.Tensor:
19
+ """
20
+ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
21
+ (1-beta) over time from t = [0,1].
22
+
23
+ Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
24
+ to that part of the diffusion process.
25
+
26
+ Args:
27
+ num_diffusion_timesteps (`int`):
28
+ The number of betas to produce.
29
+ max_beta (`float`, defaults to `0.999`):
30
+ The maximum beta to use; use values lower than 1 to avoid numerical instability.
31
+ alpha_transform_type (`"cosine"` or `"exp"`, defaults to `"cosine"`):
32
+ The type of noise schedule for `alpha_bar`. Choose from `cosine` or `exp`.
33
+
34
+ Returns:
35
+ `torch.Tensor`:
36
+ The betas used by the scheduler to step the model outputs.
37
+ """
38
+ if alpha_transform_type == "cosine":
39
+
40
+ def alpha_bar_fn(t):
41
+ return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
42
+
43
+ elif alpha_transform_type == "exp":
44
+
45
+ def alpha_bar_fn(t):
46
+ return math.exp(t * -12.0)
47
+
48
+ else:
49
+ raise ValueError(f"Unsupported alpha_transform_type: {alpha_transform_type}")
50
+
51
+ betas = []
52
+ for i in range(num_diffusion_timesteps):
53
+ t1 = i / num_diffusion_timesteps
54
+ t2 = (i + 1) / num_diffusion_timesteps
55
+ betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
56
+ return torch.tensor(betas, dtype=torch.float32)
57
+
58
+
59
+ @dataclass
60
+ class ConsistencyDecoderSchedulerOutput(BaseOutput):
61
+ """
62
+ Output class for the scheduler's `step` function.
63
+
64
+ Args:
65
+ prev_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
66
+ Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
67
+ denoising loop.
68
+ """
69
+
70
+ prev_sample: torch.Tensor
71
+
72
+
73
+ class ConsistencyDecoderScheduler(SchedulerMixin, ConfigMixin):
74
+ order = 1
75
+
76
+ @register_to_config
77
+ def __init__(
78
+ self,
79
+ num_train_timesteps: int = 1024,
80
+ sigma_data: float = 0.5,
81
+ ):
82
+ betas = betas_for_alpha_bar(num_train_timesteps)
83
+
84
+ alphas = 1.0 - betas
85
+ alphas_cumprod = torch.cumprod(alphas, dim=0)
86
+
87
+ self.sqrt_alphas_cumprod = torch.sqrt(alphas_cumprod)
88
+ self.sqrt_one_minus_alphas_cumprod = torch.sqrt(1.0 - alphas_cumprod)
89
+
90
+ sigmas = torch.sqrt(1.0 / alphas_cumprod - 1)
91
+
92
+ sqrt_recip_alphas_cumprod = torch.sqrt(1.0 / alphas_cumprod)
93
+
94
+ self.c_skip = sqrt_recip_alphas_cumprod * sigma_data**2 / (sigmas**2 + sigma_data**2)
95
+ self.c_out = sigmas * sigma_data / (sigmas**2 + sigma_data**2) ** 0.5
96
+ self.c_in = sqrt_recip_alphas_cumprod / (sigmas**2 + sigma_data**2) ** 0.5
97
+
98
+ def set_timesteps(
99
+ self,
100
+ num_inference_steps: Optional[int] = None,
101
+ device: Union[str, torch.device] = None,
102
+ ):
103
+ if num_inference_steps != 2:
104
+ raise ValueError("Currently more than 2 inference steps are not supported.")
105
+
106
+ self.timesteps = torch.tensor([1008, 512], dtype=torch.long, device=device)
107
+ self.sqrt_alphas_cumprod = self.sqrt_alphas_cumprod.to(device)
108
+ self.sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod.to(device)
109
+ self.c_skip = self.c_skip.to(device)
110
+ self.c_out = self.c_out.to(device)
111
+ self.c_in = self.c_in.to(device)
112
+
113
+ @property
114
+ def init_noise_sigma(self):
115
+ return self.sqrt_one_minus_alphas_cumprod[self.timesteps[0]]
116
+
117
+ def scale_model_input(self, sample: torch.Tensor, timestep: Optional[int] = None) -> torch.Tensor:
118
+ """
119
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
120
+ current timestep.
121
+
122
+ Args:
123
+ sample (`torch.Tensor`):
124
+ The input sample.
125
+ timestep (`int`, *optional*):
126
+ The current timestep in the diffusion chain.
127
+
128
+ Returns:
129
+ `torch.Tensor`:
130
+ A scaled input sample.
131
+ """
132
+ return sample * self.c_in[timestep]
133
+
134
+ def step(
135
+ self,
136
+ model_output: torch.Tensor,
137
+ timestep: Union[float, torch.Tensor],
138
+ sample: torch.Tensor,
139
+ generator: Optional[torch.Generator] = None,
140
+ return_dict: bool = True,
141
+ ) -> Union[ConsistencyDecoderSchedulerOutput, Tuple]:
142
+ """
143
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
144
+ process from the learned model outputs (most often the predicted noise).
145
+
146
+ Args:
147
+ model_output (`torch.Tensor`):
148
+ The direct output from the learned diffusion model.
149
+ timestep (`float`):
150
+ The current timestep in the diffusion chain.
151
+ sample (`torch.Tensor`):
152
+ A current instance of a sample created by the diffusion process.
153
+ generator (`torch.Generator`, *optional*):
154
+ A random number generator.
155
+ return_dict (`bool`, *optional*, defaults to `True`):
156
+ Whether or not to return a
157
+ [`~schedulers.scheduling_consistency_models.ConsistencyDecoderSchedulerOutput`] or `tuple`.
158
+
159
+ Returns:
160
+ [`~schedulers.scheduling_consistency_models.ConsistencyDecoderSchedulerOutput`] or `tuple`:
161
+ If return_dict is `True`,
162
+ [`~schedulers.scheduling_consistency_models.ConsistencyDecoderSchedulerOutput`] is returned, otherwise
163
+ a tuple is returned where the first element is the sample tensor.
164
+ """
165
+ x_0 = self.c_out[timestep] * model_output + self.c_skip[timestep] * sample
166
+
167
+ timestep_idx = torch.where(self.timesteps == timestep)[0]
168
+
169
+ if timestep_idx == len(self.timesteps) - 1:
170
+ prev_sample = x_0
171
+ else:
172
+ noise = randn_tensor(x_0.shape, generator=generator, dtype=x_0.dtype, device=x_0.device)
173
+ prev_sample = (
174
+ self.sqrt_alphas_cumprod[self.timesteps[timestep_idx + 1]].to(x_0.dtype) * x_0
175
+ + self.sqrt_one_minus_alphas_cumprod[self.timesteps[timestep_idx + 1]].to(x_0.dtype) * noise
176
+ )
177
+
178
+ if not return_dict:
179
+ return (prev_sample,)
180
+
181
+ return ConsistencyDecoderSchedulerOutput(prev_sample=prev_sample)
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/scheduling_consistency_models.py ADDED
@@ -0,0 +1,479 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+ from dataclasses import dataclass
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+
21
+ from ..configuration_utils import ConfigMixin, register_to_config
22
+ from ..utils import BaseOutput, logging
23
+ from ..utils.torch_utils import randn_tensor
24
+ from .scheduling_utils import SchedulerMixin
25
+
26
+
27
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
28
+
29
+
30
+ @dataclass
31
+ class CMStochasticIterativeSchedulerOutput(BaseOutput):
32
+ """
33
+ Output class for the scheduler's `step` function.
34
+
35
+ Args:
36
+ prev_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
37
+ Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
38
+ denoising loop.
39
+ """
40
+
41
+ prev_sample: torch.Tensor
42
+
43
+
44
+ class CMStochasticIterativeScheduler(SchedulerMixin, ConfigMixin):
45
+ """
46
+ Multistep and onestep sampling for consistency models.
47
+
48
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
49
+ methods the library implements for all schedulers such as loading and saving.
50
+
51
+ Args:
52
+ num_train_timesteps (`int`, defaults to 40):
53
+ The number of diffusion steps to train the model.
54
+ sigma_min (`float`, defaults to 0.002):
55
+ Minimum noise magnitude in the sigma schedule. Defaults to 0.002 from the original implementation.
56
+ sigma_max (`float`, defaults to 80.0):
57
+ Maximum noise magnitude in the sigma schedule. Defaults to 80.0 from the original implementation.
58
+ sigma_data (`float`, defaults to 0.5):
59
+ The standard deviation of the data distribution from the EDM
60
+ [paper](https://huggingface.co/papers/2206.00364). Defaults to 0.5 from the original implementation.
61
+ s_noise (`float`, defaults to 1.0):
62
+ The amount of additional noise to counteract loss of detail during sampling. A reasonable range is [1.000,
63
+ 1.011]. Defaults to 1.0 from the original implementation.
64
+ rho (`float`, defaults to 7.0):
65
+ The parameter for calculating the Karras sigma schedule from the EDM
66
+ [paper](https://huggingface.co/papers/2206.00364). Defaults to 7.0 from the original implementation.
67
+ clip_denoised (`bool`, defaults to `True`):
68
+ Whether to clip the denoised outputs to `(-1, 1)`.
69
+ timesteps (`List` or `np.ndarray` or `torch.Tensor`, *optional*):
70
+ An explicit timestep schedule that can be optionally specified. The timesteps are expected to be in
71
+ increasing order.
72
+ """
73
+
74
+ order = 1
75
+
76
+ @register_to_config
77
+ def __init__(
78
+ self,
79
+ num_train_timesteps: int = 40,
80
+ sigma_min: float = 0.002,
81
+ sigma_max: float = 80.0,
82
+ sigma_data: float = 0.5,
83
+ s_noise: float = 1.0,
84
+ rho: float = 7.0,
85
+ clip_denoised: bool = True,
86
+ ):
87
+ # standard deviation of the initial noise distribution
88
+ self.init_noise_sigma = sigma_max
89
+
90
+ ramp = np.linspace(0, 1, num_train_timesteps)
91
+ sigmas = self._convert_to_karras(ramp)
92
+ timesteps = self.sigma_to_t(sigmas)
93
+
94
+ # setable values
95
+ self.num_inference_steps = None
96
+ self.sigmas = torch.from_numpy(sigmas)
97
+ self.timesteps = torch.from_numpy(timesteps)
98
+ self.custom_timesteps = False
99
+ self.is_scale_input_called = False
100
+ self._step_index = None
101
+ self._begin_index = None
102
+ self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
103
+
104
+ @property
105
+ def step_index(self):
106
+ """
107
+ The index counter for current timestep. It will increase 1 after each scheduler step.
108
+ """
109
+ return self._step_index
110
+
111
+ @property
112
+ def begin_index(self):
113
+ """
114
+ The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
115
+ """
116
+ return self._begin_index
117
+
118
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
119
+ def set_begin_index(self, begin_index: int = 0):
120
+ """
121
+ Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
122
+
123
+ Args:
124
+ begin_index (`int`, defaults to `0`):
125
+ The begin index for the scheduler.
126
+ """
127
+ self._begin_index = begin_index
128
+
129
+ def scale_model_input(self, sample: torch.Tensor, timestep: Union[float, torch.Tensor]) -> torch.Tensor:
130
+ """
131
+ Scales the consistency model input by `(sigma**2 + sigma_data**2) ** 0.5`.
132
+
133
+ Args:
134
+ sample (`torch.Tensor`):
135
+ The input sample.
136
+ timestep (`float` or `torch.Tensor`):
137
+ The current timestep in the diffusion chain.
138
+
139
+ Returns:
140
+ `torch.Tensor`:
141
+ A scaled input sample.
142
+ """
143
+ # Get sigma corresponding to timestep
144
+ if self.step_index is None:
145
+ self._init_step_index(timestep)
146
+
147
+ sigma = self.sigmas[self.step_index]
148
+
149
+ sample = sample / ((sigma**2 + self.config.sigma_data**2) ** 0.5)
150
+
151
+ self.is_scale_input_called = True
152
+ return sample
153
+
154
+ def sigma_to_t(self, sigmas: Union[float, np.ndarray]):
155
+ """
156
+ Gets scaled timesteps from the Karras sigmas for input to the consistency model.
157
+
158
+ Args:
159
+ sigmas (`float` or `np.ndarray`):
160
+ A single Karras sigma or an array of Karras sigmas.
161
+
162
+ Returns:
163
+ `float` or `np.ndarray`:
164
+ A scaled input timestep or scaled input timestep array.
165
+ """
166
+ if not isinstance(sigmas, np.ndarray):
167
+ sigmas = np.array(sigmas, dtype=np.float64)
168
+
169
+ timesteps = 1000 * 0.25 * np.log(sigmas + 1e-44)
170
+
171
+ return timesteps
172
+
173
+ def set_timesteps(
174
+ self,
175
+ num_inference_steps: Optional[int] = None,
176
+ device: Union[str, torch.device] = None,
177
+ timesteps: Optional[List[int]] = None,
178
+ ):
179
+ """
180
+ Sets the timesteps used for the diffusion chain (to be run before inference).
181
+
182
+ Args:
183
+ num_inference_steps (`int`):
184
+ The number of diffusion steps used when generating samples with a pre-trained model.
185
+ device (`str` or `torch.device`, *optional*):
186
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
187
+ timesteps (`List[int]`, *optional*):
188
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
189
+ timestep spacing strategy of equal spacing between timesteps is used. If `timesteps` is passed,
190
+ `num_inference_steps` must be `None`.
191
+ """
192
+ if num_inference_steps is None and timesteps is None:
193
+ raise ValueError("Exactly one of `num_inference_steps` or `timesteps` must be supplied.")
194
+
195
+ if num_inference_steps is not None and timesteps is not None:
196
+ raise ValueError("Can only pass one of `num_inference_steps` or `timesteps`.")
197
+
198
+ # Follow DDPMScheduler custom timesteps logic
199
+ if timesteps is not None:
200
+ for i in range(1, len(timesteps)):
201
+ if timesteps[i] >= timesteps[i - 1]:
202
+ raise ValueError("`timesteps` must be in descending order.")
203
+
204
+ if timesteps[0] >= self.config.num_train_timesteps:
205
+ raise ValueError(
206
+ f"`timesteps` must start before `self.config.train_timesteps`: {self.config.num_train_timesteps}."
207
+ )
208
+
209
+ timesteps = np.array(timesteps, dtype=np.int64)
210
+ self.custom_timesteps = True
211
+ else:
212
+ if num_inference_steps > self.config.num_train_timesteps:
213
+ raise ValueError(
214
+ f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:"
215
+ f" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle"
216
+ f" maximal {self.config.num_train_timesteps} timesteps."
217
+ )
218
+
219
+ self.num_inference_steps = num_inference_steps
220
+
221
+ step_ratio = self.config.num_train_timesteps // self.num_inference_steps
222
+ timesteps = (np.arange(0, num_inference_steps) * step_ratio).round()[::-1].copy().astype(np.int64)
223
+ self.custom_timesteps = False
224
+
225
+ # Map timesteps to Karras sigmas directly for multistep sampling
226
+ # See https://github.com/openai/consistency_models/blob/main/cm/karras_diffusion.py#L675
227
+ num_train_timesteps = self.config.num_train_timesteps
228
+ ramp = timesteps[::-1].copy()
229
+ ramp = ramp / (num_train_timesteps - 1)
230
+ sigmas = self._convert_to_karras(ramp)
231
+ timesteps = self.sigma_to_t(sigmas)
232
+
233
+ sigmas = np.concatenate([sigmas, [self.config.sigma_min]]).astype(np.float32)
234
+ self.sigmas = torch.from_numpy(sigmas).to(device=device)
235
+
236
+ if str(device).startswith("mps"):
237
+ # mps does not support float64
238
+ self.timesteps = torch.from_numpy(timesteps).to(device, dtype=torch.float32)
239
+ else:
240
+ self.timesteps = torch.from_numpy(timesteps).to(device=device)
241
+
242
+ self._step_index = None
243
+ self._begin_index = None
244
+ self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
245
+
246
+ # Modified _convert_to_karras implementation that takes in ramp as argument
247
+ def _convert_to_karras(self, ramp):
248
+ """Constructs the noise schedule of Karras et al. (2022)."""
249
+
250
+ sigma_min: float = self.config.sigma_min
251
+ sigma_max: float = self.config.sigma_max
252
+
253
+ rho = self.config.rho
254
+ min_inv_rho = sigma_min ** (1 / rho)
255
+ max_inv_rho = sigma_max ** (1 / rho)
256
+ sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
257
+ return sigmas
258
+
259
+ def get_scalings(self, sigma):
260
+ sigma_data = self.config.sigma_data
261
+
262
+ c_skip = sigma_data**2 / (sigma**2 + sigma_data**2)
263
+ c_out = sigma * sigma_data / (sigma**2 + sigma_data**2) ** 0.5
264
+ return c_skip, c_out
265
+
266
+ def get_scalings_for_boundary_condition(self, sigma):
267
+ """
268
+ Gets the scalings used in the consistency model parameterization (from Appendix C of the
269
+ [paper](https://huggingface.co/papers/2303.01469)) to enforce boundary condition.
270
+
271
+ > [!TIP] > `epsilon` in the equations for `c_skip` and `c_out` is set to `sigma_min`.
272
+
273
+ Args:
274
+ sigma (`torch.Tensor`):
275
+ The current sigma in the Karras sigma schedule.
276
+
277
+ Returns:
278
+ `tuple`:
279
+ A two-element tuple where `c_skip` (which weights the current sample) is the first element and `c_out`
280
+ (which weights the consistency model output) is the second element.
281
+ """
282
+ sigma_min = self.config.sigma_min
283
+ sigma_data = self.config.sigma_data
284
+
285
+ c_skip = sigma_data**2 / ((sigma - sigma_min) ** 2 + sigma_data**2)
286
+ c_out = (sigma - sigma_min) * sigma_data / (sigma**2 + sigma_data**2) ** 0.5
287
+ return c_skip, c_out
288
+
289
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler.index_for_timestep
290
+ def index_for_timestep(
291
+ self, timestep: Union[float, torch.Tensor], schedule_timesteps: Optional[torch.Tensor] = None
292
+ ) -> int:
293
+ """
294
+ Find the index of a given timestep in the timestep schedule.
295
+
296
+ Args:
297
+ timestep (`float` or `torch.Tensor`):
298
+ The timestep value to find in the schedule.
299
+ schedule_timesteps (`torch.Tensor`, *optional*):
300
+ The timestep schedule to search in. If `None`, uses `self.timesteps`.
301
+
302
+ Returns:
303
+ `int`:
304
+ The index of the timestep in the schedule. For the very first step, returns the second index if
305
+ multiple matches exist to avoid skipping a sigma when starting mid-schedule (e.g., for image-to-image).
306
+ """
307
+ if schedule_timesteps is None:
308
+ schedule_timesteps = self.timesteps
309
+
310
+ indices = (schedule_timesteps == timestep).nonzero()
311
+
312
+ # The sigma index that is taken for the **very** first `step`
313
+ # is always the second index (or the last index if there is only 1)
314
+ # This way we can ensure we don't accidentally skip a sigma in
315
+ # case we start in the middle of the denoising schedule (e.g. for image-to-image)
316
+ pos = 1 if len(indices) > 1 else 0
317
+
318
+ return indices[pos].item()
319
+
320
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._init_step_index
321
+ def _init_step_index(self, timestep: Union[float, torch.Tensor]) -> None:
322
+ """
323
+ Initialize the step index for the scheduler based on the given timestep.
324
+
325
+ Args:
326
+ timestep (`float` or `torch.Tensor`):
327
+ The current timestep to initialize the step index from.
328
+ """
329
+ if self.begin_index is None:
330
+ if isinstance(timestep, torch.Tensor):
331
+ timestep = timestep.to(self.timesteps.device)
332
+ self._step_index = self.index_for_timestep(timestep)
333
+ else:
334
+ self._step_index = self._begin_index
335
+
336
+ def step(
337
+ self,
338
+ model_output: torch.Tensor,
339
+ timestep: Union[float, torch.Tensor],
340
+ sample: torch.Tensor,
341
+ generator: Optional[torch.Generator] = None,
342
+ return_dict: bool = True,
343
+ ) -> Union[CMStochasticIterativeSchedulerOutput, Tuple]:
344
+ """
345
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
346
+ process from the learned model outputs (most often the predicted noise).
347
+
348
+ Args:
349
+ model_output (`torch.Tensor`):
350
+ The direct output from the learned diffusion model.
351
+ timestep (`float`):
352
+ The current timestep in the diffusion chain.
353
+ sample (`torch.Tensor`):
354
+ A current instance of a sample created by the diffusion process.
355
+ generator (`torch.Generator`, *optional*):
356
+ A random number generator.
357
+ return_dict (`bool`, *optional*, defaults to `True`):
358
+ Whether or not to return a
359
+ [`~schedulers.scheduling_consistency_models.CMStochasticIterativeSchedulerOutput`] or `tuple`.
360
+
361
+ Returns:
362
+ [`~schedulers.scheduling_consistency_models.CMStochasticIterativeSchedulerOutput`] or `tuple`:
363
+ If return_dict is `True`,
364
+ [`~schedulers.scheduling_consistency_models.CMStochasticIterativeSchedulerOutput`] is returned,
365
+ otherwise a tuple is returned where the first element is the sample tensor.
366
+ """
367
+
368
+ if isinstance(timestep, (int, torch.IntTensor, torch.LongTensor)):
369
+ raise ValueError(
370
+ (
371
+ "Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
372
+ f" `{self.__class__}.step()` is not supported. Make sure to pass"
373
+ " one of the `scheduler.timesteps` as a timestep."
374
+ ),
375
+ )
376
+
377
+ if not self.is_scale_input_called:
378
+ logger.warning(
379
+ "The `scale_model_input` function should be called before `step` to ensure correct denoising. "
380
+ "See `StableDiffusionPipeline` for a usage example."
381
+ )
382
+
383
+ sigma_min = self.config.sigma_min
384
+ sigma_max = self.config.sigma_max
385
+
386
+ if self.step_index is None:
387
+ self._init_step_index(timestep)
388
+
389
+ # sigma_next corresponds to next_t in original implementation
390
+ sigma = self.sigmas[self.step_index]
391
+ if self.step_index + 1 < self.config.num_train_timesteps:
392
+ sigma_next = self.sigmas[self.step_index + 1]
393
+ else:
394
+ # Set sigma_next to sigma_min
395
+ sigma_next = self.sigmas[-1]
396
+
397
+ # Get scalings for boundary conditions
398
+ c_skip, c_out = self.get_scalings_for_boundary_condition(sigma)
399
+
400
+ # 1. Denoise model output using boundary conditions
401
+ denoised = c_out * model_output + c_skip * sample
402
+ if self.config.clip_denoised:
403
+ denoised = denoised.clamp(-1, 1)
404
+
405
+ # 2. Sample z ~ N(0, s_noise^2 * I)
406
+ # Noise is not used for onestep sampling.
407
+ if len(self.timesteps) > 1:
408
+ noise = randn_tensor(
409
+ model_output.shape, dtype=model_output.dtype, device=model_output.device, generator=generator
410
+ )
411
+ else:
412
+ noise = torch.zeros_like(model_output)
413
+ z = noise * self.config.s_noise
414
+
415
+ sigma_hat = sigma_next.clamp(min=sigma_min, max=sigma_max)
416
+
417
+ # 3. Return noisy sample
418
+ # tau = sigma_hat, eps = sigma_min
419
+ prev_sample = denoised + z * (sigma_hat**2 - sigma_min**2) ** 0.5
420
+
421
+ # upon completion increase step index by one
422
+ self._step_index += 1
423
+
424
+ if not return_dict:
425
+ return (prev_sample,)
426
+
427
+ return CMStochasticIterativeSchedulerOutput(prev_sample=prev_sample)
428
+
429
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler.add_noise
430
+ def add_noise(
431
+ self,
432
+ original_samples: torch.Tensor,
433
+ noise: torch.Tensor,
434
+ timesteps: torch.Tensor,
435
+ ) -> torch.Tensor:
436
+ """
437
+ Add noise to the original samples according to the noise schedule at the specified timesteps.
438
+
439
+ Args:
440
+ original_samples (`torch.Tensor`):
441
+ The original samples to which noise will be added.
442
+ noise (`torch.Tensor`):
443
+ The noise tensor to add to the original samples.
444
+ timesteps (`torch.Tensor`):
445
+ The timesteps at which to add noise, determining the noise level from the schedule.
446
+
447
+ Returns:
448
+ `torch.Tensor`:
449
+ The noisy samples with added noise scaled according to the timestep schedule.
450
+ """
451
+ # Make sure sigmas and timesteps have the same device and dtype as original_samples
452
+ sigmas = self.sigmas.to(device=original_samples.device, dtype=original_samples.dtype)
453
+ if original_samples.device.type == "mps" and torch.is_floating_point(timesteps):
454
+ # mps does not support float64
455
+ schedule_timesteps = self.timesteps.to(original_samples.device, dtype=torch.float32)
456
+ timesteps = timesteps.to(original_samples.device, dtype=torch.float32)
457
+ else:
458
+ schedule_timesteps = self.timesteps.to(original_samples.device)
459
+ timesteps = timesteps.to(original_samples.device)
460
+
461
+ # self.begin_index is None when scheduler is used for training, or pipeline does not implement set_begin_index
462
+ if self.begin_index is None:
463
+ step_indices = [self.index_for_timestep(t, schedule_timesteps) for t in timesteps]
464
+ elif self.step_index is not None:
465
+ # add_noise is called after first denoising step (for inpainting)
466
+ step_indices = [self.step_index] * timesteps.shape[0]
467
+ else:
468
+ # add noise is called before first denoising step to create initial latent(img2img)
469
+ step_indices = [self.begin_index] * timesteps.shape[0]
470
+
471
+ sigma = sigmas[step_indices].flatten()
472
+ while len(sigma.shape) < len(original_samples.shape):
473
+ sigma = sigma.unsqueeze(-1)
474
+
475
+ noisy_samples = original_samples + noise * sigma
476
+ return noisy_samples
477
+
478
+ def __len__(self):
479
+ return self.config.num_train_timesteps
tasks/tasksmith-83a0918520ec/environment/source/src/diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py ADDED
@@ -0,0 +1,601 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 TSAIL Team and 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
+ # DISCLAIMER: This file is strongly influenced by https://github.com/LuChengTHU/dpm-solver and https://github.com/NVlabs/edm
16
+
17
+ import math
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ import numpy as np
21
+ import torch
22
+
23
+ from ..configuration_utils import ConfigMixin, register_to_config
24
+ from .scheduling_dpmsolver_sde import BrownianTreeNoiseSampler
25
+ from .scheduling_utils import SchedulerMixin, SchedulerOutput
26
+
27
+
28
+ class CosineDPMSolverMultistepScheduler(SchedulerMixin, ConfigMixin):
29
+ """
30
+ Implements a variant of `DPMSolverMultistepScheduler` with cosine schedule, proposed by Nichol and Dhariwal (2021).
31
+ This scheduler was used in Stable Audio Open [1].
32
+
33
+ [1] Evans, Parker, et al. "Stable Audio Open" https://huggingface.co/papers/2407.14358
34
+
35
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
36
+ methods the library implements for all schedulers such as loading and saving.
37
+
38
+ Args:
39
+ sigma_min (`float`, *optional*, defaults to 0.3):
40
+ Minimum noise magnitude in the sigma schedule. This was set to 0.3 in Stable Audio Open [1].
41
+ sigma_max (`float`, *optional*, defaults to 500):
42
+ Maximum noise magnitude in the sigma schedule. This was set to 500 in Stable Audio Open [1].
43
+ sigma_data (`float`, *optional*, defaults to 1.0):
44
+ The standard deviation of the data distribution. This is set to 1.0 in Stable Audio Open [1].
45
+ sigma_schedule (`str`, *optional*, defaults to `exponential`):
46
+ Sigma schedule to compute the `sigmas`. By default, we the schedule introduced in the EDM paper
47
+ (https://huggingface.co/papers/2206.00364). Other acceptable value is "exponential". The exponential
48
+ schedule was incorporated in this model: https://huggingface.co/stabilityai/cosxl.
49
+ num_train_timesteps (`int`, defaults to 1000):
50
+ The number of diffusion steps to train the model.
51
+ solver_order (`int`, defaults to 2):
52
+ The DPMSolver order which can be `1` or `2`. It is recommended to use `solver_order=2`.
53
+ prediction_type (`str`, defaults to `v_prediction`, *optional*):
54
+ Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
55
+ `sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
56
+ Video](https://imagen.research.google/video/paper.pdf) paper).
57
+ solver_type (`str`, defaults to `midpoint`):
58
+ Solver type for the second-order solver; can be `midpoint` or `heun`. The solver type slightly affects the
59
+ sample quality, especially for a small number of steps. It is recommended to use `midpoint` solvers.
60
+ lower_order_final (`bool`, defaults to `True`):
61
+ Whether to use lower-order solvers in the final steps. Only valid for < 15 inference steps. This can
62
+ stabilize the sampling of DPMSolver for steps < 15, especially for steps <= 10.
63
+ euler_at_final (`bool`, defaults to `False`):
64
+ Whether to use Euler's method in the final step. It is a trade-off between numerical stability and detail
65
+ richness. This can stabilize the sampling of the SDE variant of DPMSolver for small number of inference
66
+ steps, but sometimes may result in blurring.
67
+ final_sigmas_type (`str`, defaults to `"zero"`):
68
+ The final `sigma` value for the noise schedule during the sampling process. If `"sigma_min"`, the final
69
+ sigma is the same as the last sigma in the training schedule. If `zero`, the final sigma is set to 0.
70
+ """
71
+
72
+ _compatibles = []
73
+ order = 1
74
+
75
+ @register_to_config
76
+ def __init__(
77
+ self,
78
+ sigma_min: float = 0.3,
79
+ sigma_max: float = 500,
80
+ sigma_data: float = 1.0,
81
+ sigma_schedule: str = "exponential",
82
+ num_train_timesteps: int = 1000,
83
+ solver_order: int = 2,
84
+ prediction_type: str = "v_prediction",
85
+ rho: float = 7.0,
86
+ solver_type: str = "midpoint",
87
+ lower_order_final: bool = True,
88
+ euler_at_final: bool = False,
89
+ final_sigmas_type: Optional[str] = "zero", # "zero", "sigma_min"
90
+ ):
91
+ if solver_type not in ["midpoint", "heun"]:
92
+ if solver_type in ["logrho", "bh1", "bh2"]:
93
+ self.register_to_config(solver_type="midpoint")
94
+ else:
95
+ raise NotImplementedError(f"{solver_type} is not implemented for {self.__class__}")
96
+
97
+ ramp = torch.linspace(0, 1, num_train_timesteps)
98
+ if sigma_schedule == "karras":
99
+ sigmas = self._compute_karras_sigmas(ramp)
100
+ elif sigma_schedule == "exponential":
101
+ sigmas = self._compute_exponential_sigmas(ramp)
102
+
103
+ self.timesteps = self.precondition_noise(sigmas)
104
+
105
+ self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])
106
+
107
+ # setable values
108
+ self.num_inference_steps = None
109
+ self.model_outputs = [None] * solver_order
110
+ self.lower_order_nums = 0
111
+ self._step_index = None
112
+ self._begin_index = None
113
+ self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
114
+
115
+ @property
116
+ def init_noise_sigma(self):
117
+ # standard deviation of the initial noise distribution
118
+ return (self.config.sigma_max**2 + 1) ** 0.5
119
+
120
+ @property
121
+ def step_index(self):
122
+ """
123
+ The index counter for current timestep. It will increase 1 after each scheduler step.
124
+ """
125
+ return self._step_index
126
+
127
+ @property
128
+ def begin_index(self):
129
+ """
130
+ The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
131
+ """
132
+ return self._begin_index
133
+
134
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
135
+ def set_begin_index(self, begin_index: int = 0):
136
+ """
137
+ Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
138
+
139
+ Args:
140
+ begin_index (`int`, defaults to `0`):
141
+ The begin index for the scheduler.
142
+ """
143
+ self._begin_index = begin_index
144
+
145
+ # Copied from diffusers.schedulers.scheduling_edm_euler.EDMEulerScheduler.precondition_inputs
146
+ def precondition_inputs(self, sample, sigma):
147
+ c_in = self._get_conditioning_c_in(sigma)
148
+ scaled_sample = sample * c_in
149
+ return scaled_sample
150
+
151
+ def precondition_noise(self, sigma):
152
+ if not isinstance(sigma, torch.Tensor):
153
+ sigma = torch.tensor([sigma])
154
+
155
+ return sigma.atan() / math.pi * 2
156
+
157
+ # Copied from diffusers.schedulers.scheduling_edm_euler.EDMEulerScheduler.precondition_outputs
158
+ def precondition_outputs(self, sample, model_output, sigma):
159
+ sigma_data = self.config.sigma_data
160
+ c_skip = sigma_data**2 / (sigma**2 + sigma_data**2)
161
+
162
+ if self.config.prediction_type == "epsilon":
163
+ c_out = sigma * sigma_data / (sigma**2 + sigma_data**2) ** 0.5
164
+ elif self.config.prediction_type == "v_prediction":
165
+ c_out = -sigma * sigma_data / (sigma**2 + sigma_data**2) ** 0.5
166
+ else:
167
+ raise ValueError(f"Prediction type {self.config.prediction_type} is not supported.")
168
+
169
+ denoised = c_skip * sample + c_out * model_output
170
+
171
+ return denoised
172
+
173
+ # Copied from diffusers.schedulers.scheduling_edm_euler.EDMEulerScheduler.scale_model_input
174
+ def scale_model_input(self, sample: torch.Tensor, timestep: Union[float, torch.Tensor]) -> torch.Tensor:
175
+ """
176
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
177
+ current timestep. Scales the denoising model input by `(sigma**2 + 1) ** 0.5` to match the Euler algorithm.
178
+
179
+ Args:
180
+ sample (`torch.Tensor`):
181
+ The input sample.
182
+ timestep (`int`, *optional*):
183
+ The current timestep in the diffusion chain.
184
+
185
+ Returns:
186
+ `torch.Tensor`:
187
+ A scaled input sample.
188
+ """
189
+ if self.step_index is None:
190
+ self._init_step_index(timestep)
191
+
192
+ sigma = self.sigmas[self.step_index]
193
+ sample = self.precondition_inputs(sample, sigma)
194
+
195
+ self.is_scale_input_called = True
196
+ return sample
197
+
198
+ def set_timesteps(self, num_inference_steps: int = None, device: Union[str, torch.device] = None):
199
+ """
200
+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
201
+
202
+ Args:
203
+ num_inference_steps (`int`):
204
+ The number of diffusion steps used when generating samples with a pre-trained model.
205
+ device (`str` or `torch.device`, *optional*):
206
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
207
+ """
208
+
209
+ self.num_inference_steps = num_inference_steps
210
+
211
+ ramp = torch.linspace(0, 1, self.num_inference_steps)
212
+ if self.config.sigma_schedule == "karras":
213
+ sigmas = self._compute_karras_sigmas(ramp)
214
+ elif self.config.sigma_schedule == "exponential":
215
+ sigmas = self._compute_exponential_sigmas(ramp)
216
+
217
+ sigmas = sigmas.to(dtype=torch.float32, device=device)
218
+ self.timesteps = self.precondition_noise(sigmas)
219
+
220
+ if self.config.final_sigmas_type == "sigma_min":
221
+ sigma_last = self.config.sigma_min
222
+ elif self.config.final_sigmas_type == "zero":
223
+ sigma_last = 0
224
+ else:
225
+ raise ValueError(
226
+ f"`final_sigmas_type` must be one of 'zero', or 'sigma_min', but got {self.config.final_sigmas_type}"
227
+ )
228
+
229
+ self.sigmas = torch.cat([sigmas, torch.tensor([sigma_last], dtype=torch.float32, device=device)])
230
+
231
+ self.model_outputs = [
232
+ None,
233
+ ] * self.config.solver_order
234
+ self.lower_order_nums = 0
235
+
236
+ # add an index counter for schedulers that allow duplicated timesteps
237
+ self._step_index = None
238
+ self._begin_index = None
239
+ self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
240
+
241
+ # if a noise sampler is used, reinitialise it
242
+ self.noise_sampler = None
243
+
244
+ # Copied from diffusers.schedulers.scheduling_edm_euler.EDMEulerScheduler._compute_karras_sigmas
245
+ def _compute_karras_sigmas(self, ramp, sigma_min=None, sigma_max=None) -> torch.Tensor:
246
+ """Constructs the noise schedule of Karras et al. (2022)."""
247
+ sigma_min = sigma_min or self.config.sigma_min
248
+ sigma_max = sigma_max or self.config.sigma_max
249
+
250
+ rho = self.config.rho
251
+ min_inv_rho = sigma_min ** (1 / rho)
252
+ max_inv_rho = sigma_max ** (1 / rho)
253
+ sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
254
+ return sigmas
255
+
256
+ # Copied from diffusers.schedulers.scheduling_edm_euler.EDMEulerScheduler._compute_exponential_sigmas
257
+ def _compute_exponential_sigmas(self, ramp, sigma_min=None, sigma_max=None) -> torch.Tensor:
258
+ """Implementation closely follows k-diffusion.
259
+
260
+ https://github.com/crowsonkb/k-diffusion/blob/6ab5146d4a5ef63901326489f31f1d8e7dd36b48/k_diffusion/sampling.py#L26
261
+ """
262
+ sigma_min = sigma_min or self.config.sigma_min
263
+ sigma_max = sigma_max or self.config.sigma_max
264
+ sigmas = torch.linspace(math.log(sigma_min), math.log(sigma_max), len(ramp)).exp().flip(0)
265
+ return sigmas
266
+
267
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._sigma_to_t
268
+ def _sigma_to_t(self, sigma, log_sigmas):
269
+ """
270
+ Convert sigma values to corresponding timestep values through interpolation.
271
+
272
+ Args:
273
+ sigma (`np.ndarray`):
274
+ The sigma value(s) to convert to timestep(s).
275
+ log_sigmas (`np.ndarray`):
276
+ The logarithm of the sigma schedule used for interpolation.
277
+
278
+ Returns:
279
+ `np.ndarray`:
280
+ The interpolated timestep value(s) corresponding to the input sigma(s).
281
+ """
282
+ # get log sigma
283
+ log_sigma = np.log(np.maximum(sigma, 1e-10))
284
+
285
+ # get distribution
286
+ dists = log_sigma - log_sigmas[:, np.newaxis]
287
+
288
+ # get sigmas range
289
+ low_idx = np.cumsum((dists >= 0), axis=0).argmax(axis=0).clip(max=log_sigmas.shape[0] - 2)
290
+ high_idx = low_idx + 1
291
+
292
+ low = log_sigmas[low_idx]
293
+ high = log_sigmas[high_idx]
294
+
295
+ # interpolate sigmas
296
+ w = (low - log_sigma) / (low - high)
297
+ w = np.clip(w, 0, 1)
298
+
299
+ # transform interpolation to time range
300
+ t = (1 - w) * low_idx + w * high_idx
301
+ t = t.reshape(sigma.shape)
302
+ return t
303
+
304
+ def _sigma_to_alpha_sigma_t(self, sigma):
305
+ alpha_t = torch.tensor(1) # Inputs are pre-scaled before going into unet, so alpha_t = 1
306
+ sigma_t = sigma
307
+
308
+ return alpha_t, sigma_t
309
+
310
+ def convert_model_output(
311
+ self,
312
+ model_output: torch.Tensor,
313
+ sample: torch.Tensor = None,
314
+ ) -> torch.Tensor:
315
+ """
316
+ Convert the model output to the corresponding type the DPMSolver/DPMSolver++ algorithm needs. DPM-Solver is
317
+ designed to discretize an integral of the noise prediction model, and DPM-Solver++ is designed to discretize an
318
+ integral of the data prediction model.
319
+
320
+ > [!TIP] > The algorithm and model type are decoupled. You can use either DPMSolver or DPMSolver++ for both
321
+ noise > prediction and data prediction models.
322
+
323
+ Args:
324
+ model_output (`torch.Tensor`):
325
+ The direct output from the learned diffusion model.
326
+ sample (`torch.Tensor`):
327
+ A current instance of a sample created by the diffusion process.
328
+
329
+ Returns:
330
+ `torch.Tensor`:
331
+ The converted model output.
332
+ """
333
+ sigma = self.sigmas[self.step_index]
334
+ x0_pred = self.precondition_outputs(sample, model_output, sigma)
335
+
336
+ return x0_pred
337
+
338
+ def dpm_solver_first_order_update(
339
+ self,
340
+ model_output: torch.Tensor,
341
+ sample: torch.Tensor = None,
342
+ noise: Optional[torch.Tensor] = None,
343
+ ) -> torch.Tensor:
344
+ """
345
+ One step for the first-order DPMSolver (equivalent to DDIM).
346
+
347
+ Args:
348
+ model_output (`torch.Tensor`):
349
+ The direct output from the learned diffusion model.
350
+ sample (`torch.Tensor`):
351
+ A current instance of a sample created by the diffusion process.
352
+
353
+ Returns:
354
+ `torch.Tensor`:
355
+ The sample tensor at the previous timestep.
356
+ """
357
+ sigma_t, sigma_s = self.sigmas[self.step_index + 1], self.sigmas[self.step_index]
358
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
359
+ alpha_s, sigma_s = self._sigma_to_alpha_sigma_t(sigma_s)
360
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
361
+ lambda_s = torch.log(alpha_s) - torch.log(sigma_s)
362
+
363
+ h = lambda_t - lambda_s
364
+ assert noise is not None
365
+ x_t = (
366
+ (sigma_t / sigma_s * torch.exp(-h)) * sample
367
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * model_output
368
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
369
+ )
370
+
371
+ return x_t
372
+
373
+ def multistep_dpm_solver_second_order_update(
374
+ self,
375
+ model_output_list: List[torch.Tensor],
376
+ sample: torch.Tensor = None,
377
+ noise: Optional[torch.Tensor] = None,
378
+ ) -> torch.Tensor:
379
+ """
380
+ One step for the second-order multistep DPMSolver.
381
+
382
+ Args:
383
+ model_output_list (`List[torch.Tensor]`):
384
+ The direct outputs from learned diffusion model at current and latter timesteps.
385
+ sample (`torch.Tensor`):
386
+ A current instance of a sample created by the diffusion process.
387
+
388
+ Returns:
389
+ `torch.Tensor`:
390
+ The sample tensor at the previous timestep.
391
+ """
392
+ sigma_t, sigma_s0, sigma_s1 = (
393
+ self.sigmas[self.step_index + 1],
394
+ self.sigmas[self.step_index],
395
+ self.sigmas[self.step_index - 1],
396
+ )
397
+
398
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
399
+ alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
400
+ alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1)
401
+
402
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
403
+ lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
404
+ lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1)
405
+
406
+ m0, m1 = model_output_list[-1], model_output_list[-2]
407
+
408
+ h, h_0 = lambda_t - lambda_s0, lambda_s0 - lambda_s1
409
+ r0 = h_0 / h
410
+ D0, D1 = m0, (1.0 / r0) * (m0 - m1)
411
+
412
+ # sde-dpmsolver++
413
+ assert noise is not None
414
+ if self.config.solver_type == "midpoint":
415
+ x_t = (
416
+ (sigma_t / sigma_s0 * torch.exp(-h)) * sample
417
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
418
+ + 0.5 * (alpha_t * (1 - torch.exp(-2.0 * h))) * D1
419
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
420
+ )
421
+ elif self.config.solver_type == "heun":
422
+ x_t = (
423
+ (sigma_t / sigma_s0 * torch.exp(-h)) * sample
424
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
425
+ + (alpha_t * ((1.0 - torch.exp(-2.0 * h)) / (-2.0 * h) + 1.0)) * D1
426
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
427
+ )
428
+
429
+ return x_t
430
+
431
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.index_for_timestep
432
+ def index_for_timestep(self, timestep, schedule_timesteps=None):
433
+ if schedule_timesteps is None:
434
+ schedule_timesteps = self.timesteps
435
+
436
+ index_candidates = (schedule_timesteps == timestep).nonzero()
437
+
438
+ if len(index_candidates) == 0:
439
+ step_index = len(self.timesteps) - 1
440
+ # The sigma index that is taken for the **very** first `step`
441
+ # is always the second index (or the last index if there is only 1)
442
+ # This way we can ensure we don't accidentally skip a sigma in
443
+ # case we start in the middle of the denoising schedule (e.g. for image-to-image)
444
+ elif len(index_candidates) > 1:
445
+ step_index = index_candidates[1].item()
446
+ else:
447
+ step_index = index_candidates[0].item()
448
+
449
+ return step_index
450
+
451
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler._init_step_index
452
+ def _init_step_index(self, timestep):
453
+ """
454
+ Initialize the step_index counter for the scheduler.
455
+ """
456
+
457
+ if self.begin_index is None:
458
+ if isinstance(timestep, torch.Tensor):
459
+ timestep = timestep.to(self.timesteps.device)
460
+ self._step_index = self.index_for_timestep(timestep)
461
+ else:
462
+ self._step_index = self._begin_index
463
+
464
+ def step(
465
+ self,
466
+ model_output: torch.Tensor,
467
+ timestep: Union[int, torch.Tensor],
468
+ sample: torch.Tensor,
469
+ generator=None,
470
+ return_dict: bool = True,
471
+ ) -> Union[SchedulerOutput, Tuple]:
472
+ """
473
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with
474
+ the multistep DPMSolver.
475
+
476
+ Args:
477
+ model_output (`torch.Tensor`):
478
+ The direct output from learned diffusion model.
479
+ timestep (`int`):
480
+ The current discrete timestep in the diffusion chain.
481
+ sample (`torch.Tensor`):
482
+ A current instance of a sample created by the diffusion process.
483
+ generator (`torch.Generator`, *optional*):
484
+ A random number generator.
485
+ return_dict (`bool`):
486
+ Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`.
487
+
488
+ Returns:
489
+ [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`:
490
+ If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] is returned, otherwise a
491
+ tuple is returned where the first element is the sample tensor.
492
+
493
+ """
494
+ if self.num_inference_steps is None:
495
+ raise ValueError(
496
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
497
+ )
498
+
499
+ if self.step_index is None:
500
+ self._init_step_index(timestep)
501
+
502
+ # Improve numerical stability for small number of steps
503
+ lower_order_final = (self.step_index == len(self.timesteps) - 1) and (
504
+ self.config.euler_at_final
505
+ or (self.config.lower_order_final and len(self.timesteps) < 15)
506
+ or self.config.final_sigmas_type == "zero"
507
+ )
508
+ lower_order_second = (
509
+ (self.step_index == len(self.timesteps) - 2) and self.config.lower_order_final and len(self.timesteps) < 15
510
+ )
511
+
512
+ model_output = self.convert_model_output(model_output, sample=sample)
513
+ for i in range(self.config.solver_order - 1):
514
+ self.model_outputs[i] = self.model_outputs[i + 1]
515
+ self.model_outputs[-1] = model_output
516
+
517
+ if self.noise_sampler is None:
518
+ seed = None
519
+ if generator is not None:
520
+ seed = (
521
+ [g.initial_seed() for g in generator] if isinstance(generator, list) else generator.initial_seed()
522
+ )
523
+ self.noise_sampler = BrownianTreeNoiseSampler(
524
+ model_output, sigma_min=self.config.sigma_min, sigma_max=self.config.sigma_max, seed=seed
525
+ )
526
+ noise = self.noise_sampler(self.sigmas[self.step_index], self.sigmas[self.step_index + 1]).to(
527
+ model_output.device
528
+ )
529
+
530
+ if self.config.solver_order == 1 or self.lower_order_nums < 1 or lower_order_final:
531
+ prev_sample = self.dpm_solver_first_order_update(model_output, sample=sample, noise=noise)
532
+ elif self.config.solver_order == 2 or self.lower_order_nums < 2 or lower_order_second:
533
+ prev_sample = self.multistep_dpm_solver_second_order_update(self.model_outputs, sample=sample, noise=noise)
534
+
535
+ if self.lower_order_nums < self.config.solver_order:
536
+ self.lower_order_nums += 1
537
+
538
+ # upon completion increase step index by one
539
+ self._step_index += 1
540
+
541
+ if not return_dict:
542
+ return (prev_sample,)
543
+
544
+ return SchedulerOutput(prev_sample=prev_sample)
545
+
546
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler.add_noise
547
+ def add_noise(
548
+ self,
549
+ original_samples: torch.Tensor,
550
+ noise: torch.Tensor,
551
+ timesteps: torch.Tensor,
552
+ ) -> torch.Tensor:
553
+ """
554
+ Add noise to the original samples according to the noise schedule at the specified timesteps.
555
+
556
+ Args:
557
+ original_samples (`torch.Tensor`):
558
+ The original samples to which noise will be added.
559
+ noise (`torch.Tensor`):
560
+ The noise tensor to add to the original samples.
561
+ timesteps (`torch.Tensor`):
562
+ The timesteps at which to add noise, determining the noise level from the schedule.
563
+
564
+ Returns:
565
+ `torch.Tensor`:
566
+ The noisy samples with added noise scaled according to the timestep schedule.
567
+ """
568
+ # Make sure sigmas and timesteps have the same device and dtype as original_samples
569
+ sigmas = self.sigmas.to(device=original_samples.device, dtype=original_samples.dtype)
570
+ if original_samples.device.type == "mps" and torch.is_floating_point(timesteps):
571
+ # mps does not support float64
572
+ schedule_timesteps = self.timesteps.to(original_samples.device, dtype=torch.float32)
573
+ timesteps = timesteps.to(original_samples.device, dtype=torch.float32)
574
+ else:
575
+ schedule_timesteps = self.timesteps.to(original_samples.device)
576
+ timesteps = timesteps.to(original_samples.device)
577
+
578
+ # self.begin_index is None when scheduler is used for training, or pipeline does not implement set_begin_index
579
+ if self.begin_index is None:
580
+ step_indices = [self.index_for_timestep(t, schedule_timesteps) for t in timesteps]
581
+ elif self.step_index is not None:
582
+ # add_noise is called after first denoising step (for inpainting)
583
+ step_indices = [self.step_index] * timesteps.shape[0]
584
+ else:
585
+ # add noise is called before first denoising step to create initial latent(img2img)
586
+ step_indices = [self.begin_index] * timesteps.shape[0]
587
+
588
+ sigma = sigmas[step_indices].flatten()
589
+ while len(sigma.shape) < len(original_samples.shape):
590
+ sigma = sigma.unsqueeze(-1)
591
+
592
+ noisy_samples = original_samples + noise * sigma
593
+ return noisy_samples
594
+
595
+ # Copied from diffusers.schedulers.scheduling_edm_euler.EDMEulerScheduler._get_conditioning_c_in
596
+ def _get_conditioning_c_in(self, sigma):
597
+ c_in = 1 / ((sigma**2 + self.config.sigma_data**2) ** 0.5)
598
+ return c_in
599
+
600
+ def __len__(self):
601
+ return self.config.num_train_timesteps