MohamedRashad commited on
Commit
91e099c
·
verified ·
1 Parent(s): a5b36a6

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. text_encoder/Glyph-SDXL-v2/assets/Arial.ttf +3 -0
  3. text_encoder/Glyph-SDXL-v2/assets/teaser/teaser_multilingual_2.webp +0 -0
  4. text_encoder/Glyph-SDXL-v2/assets/teaser/teaser_multilingual_3.webp +0 -0
  5. text_encoder/Glyph-SDXL-v2/assets/teaser/teaser_multilingual_4.webp +0 -0
  6. text_encoder/Glyph-SDXL-v2/checkpoints/byt5_mapper.pt +3 -0
  7. text_encoder/Glyph-SDXL-v2/checkpoints/byt5_model.pt +3 -0
  8. text_encoder/Glyph-SDXL-v2/checkpoints/unet_inserted_attn.pt +3 -0
  9. text_encoder/Glyph-SDXL-v2/checkpoints/unet_lora.pt +3 -0
  10. text_encoder/Glyph-SDXL-v2/glyph_sdxl/custom_diffusers/__init__.py +2 -0
  11. text_encoder/Glyph-SDXL-v2/glyph_sdxl/custom_diffusers/models/__init__.py +3 -0
  12. text_encoder/Glyph-SDXL-v2/glyph_sdxl/custom_diffusers/models/cross_attn_insert_transformer_blocks.py +377 -0
  13. text_encoder/Glyph-SDXL-v2/glyph_sdxl/custom_diffusers/pipelines/__init__.py +5 -0
  14. text_encoder/Glyph-SDXL-v2/glyph_sdxl/custom_diffusers/pipelines/pipeline_stable_diffusion_glyph_xl.py +922 -0
  15. text_encoder/Glyph-SDXL-v2/glyph_sdxl/modules/__init__.py +7 -0
  16. text_encoder/Glyph-SDXL-v2/glyph_sdxl/modules/byt5_block_byt5_mapper.py +151 -0
  17. text_encoder/Glyph-SDXL-v2/glyph_sdxl/modules/simple_byt5_mapper.py +16 -0
  18. text_encoder/Glyph-SDXL-v2/glyph_sdxl/utils/__init__.py +23 -0
  19. text_encoder/Glyph-SDXL-v2/glyph_sdxl/utils/constants.py +5 -0
  20. text_encoder/Glyph-SDXL-v2/glyph_sdxl/utils/format_prompt.py +113 -0
  21. text_encoder/Glyph-SDXL-v2/glyph_sdxl/utils/load_pretrained_byt5.py +60 -0
  22. text_encoder/Glyph-SDXL-v2/glyph_sdxl/utils/parse_config.py +17 -0
  23. text_encoder/byt5-small/flax_model.msgpack +3 -0
  24. text_encoder/byt5-small/pytorch_model.bin +3 -0
  25. text_encoder/byt5-small/tf_model.h5 +3 -0
  26. text_encoder/llm/model-00001-of-00005.safetensors +3 -0
  27. text_encoder/llm/model-00002-of-00005.safetensors +3 -0
  28. text_encoder/llm/model-00003-of-00005.safetensors +3 -0
  29. text_encoder/llm/model-00004-of-00005.safetensors +3 -0
  30. text_encoder/llm/model-00005-of-00005.safetensors +3 -0
  31. transformer/1080p_sr_distilled/config.json +43 -0
  32. transformer/1080p_sr_distilled/diffusion_pytorch_model.safetensors +3 -0
  33. transformer/480p_i2v/config.json +43 -0
  34. transformer/480p_i2v/diffusion_pytorch_model.safetensors +3 -0
  35. transformer/480p_i2v_distilled/config.json +43 -0
  36. transformer/480p_i2v_distilled/diffusion_pytorch_model.safetensors +3 -0
  37. transformer/480p_t2v/config.json +43 -0
  38. transformer/480p_t2v/diffusion_pytorch_model.safetensors +3 -0
  39. transformer/480p_t2v_distilled/config.json +43 -0
  40. transformer/480p_t2v_distilled/diffusion_pytorch_model.safetensors +3 -0
  41. transformer/720p_i2v/config.json +43 -0
  42. transformer/720p_i2v/diffusion_pytorch_model.safetensors +3 -0
  43. transformer/720p_i2v_distilled/config.json +43 -0
  44. transformer/720p_i2v_distilled/diffusion_pytorch_model.safetensors +3 -0
  45. transformer/720p_i2v_distilled_sparse/config.json +67 -0
  46. transformer/720p_i2v_distilled_sparse/diffusion_pytorch_model.safetensors +3 -0
  47. transformer/720p_sr_distilled/config.json +43 -0
  48. transformer/720p_sr_distilled/diffusion_pytorch_model.safetensors +3 -0
  49. transformer/720p_t2v/config.json +43 -0
  50. transformer/720p_t2v/diffusion_pytorch_model.safetensors +3 -0
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ vision_encoder/siglip/redux.png filter=lfs diff=lfs merge=lfs -text
37
+ text_encoder/Glyph-SDXL-v2/assets/Arial.ttf filter=lfs diff=lfs merge=lfs -text
text_encoder/Glyph-SDXL-v2/assets/Arial.ttf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:35c0f3559d8db569e36c31095b8a60d441643d95f59139de40e23fada819b833
3
+ size 275572
text_encoder/Glyph-SDXL-v2/assets/teaser/teaser_multilingual_2.webp ADDED
text_encoder/Glyph-SDXL-v2/assets/teaser/teaser_multilingual_3.webp ADDED
text_encoder/Glyph-SDXL-v2/assets/teaser/teaser_multilingual_4.webp ADDED
text_encoder/Glyph-SDXL-v2/checkpoints/byt5_mapper.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6d5911cf07328d949eff29cc08ca7637dc4fe5312a8fa351ca4bec07d357b1c5
3
+ size 301553807
text_encoder/Glyph-SDXL-v2/checkpoints/byt5_model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca8c97c89136f767d4534449bbf3f25296d390574e0af1cc16f09774a901d6db
3
+ size 877308845
text_encoder/Glyph-SDXL-v2/checkpoints/unet_inserted_attn.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5b6af4376281be262f3b52ca0b16b0244099161693f65a7db352f53878481767
3
+ size 908
text_encoder/Glyph-SDXL-v2/checkpoints/unet_lora.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:47ae2328a9c4892a24c4a66f25780ab61a55cbd8eb693a1966cc99e674e832be
3
+ size 743590514
text_encoder/Glyph-SDXL-v2/glyph_sdxl/custom_diffusers/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .pipelines import *
2
+ from .models import *
text_encoder/Glyph-SDXL-v2/glyph_sdxl/custom_diffusers/models/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .cross_attn_insert_transformer_blocks import CrossAttnInsertBasicTransformerBlock
2
+
3
+ __all__ = ['CrossAttnInsertBasicTransformerBlock']
text_encoder/Glyph-SDXL-v2/glyph_sdxl/custom_diffusers/models/cross_attn_insert_transformer_blocks.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Dict, Any
2
+ import copy
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+
7
+ from diffusers.models.attention import (
8
+ BasicTransformerBlock,
9
+ SinusoidalPositionalEmbedding,
10
+ AdaLayerNorm,
11
+ AdaLayerNormZero,
12
+ AdaLayerNormContinuous,
13
+ Attention,
14
+ FeedForward,
15
+ GatedSelfAttentionDense,
16
+ GELU,
17
+ GEGLU,
18
+ ApproximateGELU,
19
+ _chunked_feed_forward,
20
+ )
21
+
22
+ class CrossAttnInsertBasicTransformerBlock(BasicTransformerBlock):
23
+ def __init__(
24
+ self,
25
+ dim: int,
26
+ num_attention_heads: int,
27
+ attention_head_dim: int,
28
+ dropout=0.0,
29
+ cross_attention_dim: Optional[int] = None,
30
+ glyph_cross_attention_dim: Optional[int] = None,
31
+ activation_fn: str = "geglu",
32
+ num_embeds_ada_norm: Optional[int] = None,
33
+ attention_bias: bool = False,
34
+ only_cross_attention: bool = False,
35
+ double_self_attention: bool = False,
36
+ upcast_attention: bool = False,
37
+ norm_elementwise_affine: bool = True,
38
+ norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single', 'layer_norm_i2vgen'
39
+ norm_eps: float = 1e-5,
40
+ final_dropout: bool = False,
41
+ attention_type: str = "default",
42
+ positional_embeddings: Optional[str] = None,
43
+ num_positional_embeddings: Optional[int] = None,
44
+ ada_norm_continous_conditioning_embedding_dim: Optional[int] = None,
45
+ ada_norm_bias: Optional[int] = None,
46
+ ff_inner_dim: Optional[int] = None,
47
+ ff_bias: bool = True,
48
+ attention_out_bias: bool = True,
49
+ ):
50
+ super(BasicTransformerBlock, self).__init__()
51
+ self.only_cross_attention = only_cross_attention
52
+
53
+ if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
54
+ raise ValueError(
55
+ f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
56
+ f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
57
+ )
58
+
59
+ self.norm_type = norm_type
60
+ self.num_embeds_ada_norm = num_embeds_ada_norm
61
+
62
+ if positional_embeddings and (num_positional_embeddings is None):
63
+ raise ValueError(
64
+ "If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined."
65
+ )
66
+
67
+ if positional_embeddings == "sinusoidal":
68
+ self.pos_embed = SinusoidalPositionalEmbedding(dim, max_seq_length=num_positional_embeddings)
69
+ else:
70
+ self.pos_embed = None
71
+
72
+ # Define 3 blocks. Each block has its own normalization layer.
73
+ # 1. Self-Attn
74
+ if norm_type == "ada_norm":
75
+ self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
76
+ elif norm_type == "ada_norm_zero":
77
+ self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
78
+ elif norm_type == "ada_norm_continuous":
79
+ self.norm1 = AdaLayerNormContinuous(
80
+ dim,
81
+ ada_norm_continous_conditioning_embedding_dim,
82
+ norm_elementwise_affine,
83
+ norm_eps,
84
+ ada_norm_bias,
85
+ "rms_norm",
86
+ )
87
+ else:
88
+ self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
89
+
90
+ self.attn1 = Attention(
91
+ query_dim=dim,
92
+ heads=num_attention_heads,
93
+ dim_head=attention_head_dim,
94
+ dropout=dropout,
95
+ bias=attention_bias,
96
+ cross_attention_dim=cross_attention_dim if only_cross_attention else None,
97
+ upcast_attention=upcast_attention,
98
+ out_bias=attention_out_bias,
99
+ )
100
+
101
+ # 2. Cross-Attn
102
+ if cross_attention_dim is not None or double_self_attention:
103
+ # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
104
+ # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
105
+ # the second cross attention block.
106
+ if norm_type == "ada_norm":
107
+ self.norm2 = AdaLayerNorm(dim, num_embeds_ada_norm)
108
+ elif norm_type == "ada_norm_continuous":
109
+ self.norm2 = AdaLayerNormContinuous(
110
+ dim,
111
+ ada_norm_continous_conditioning_embedding_dim,
112
+ norm_elementwise_affine,
113
+ norm_eps,
114
+ ada_norm_bias,
115
+ "rms_norm",
116
+ )
117
+ else:
118
+ self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
119
+
120
+ self.attn2 = Attention(
121
+ query_dim=dim,
122
+ cross_attention_dim=cross_attention_dim if not double_self_attention else None,
123
+ heads=num_attention_heads,
124
+ dim_head=attention_head_dim,
125
+ dropout=dropout,
126
+ bias=attention_bias,
127
+ upcast_attention=upcast_attention,
128
+ out_bias=attention_out_bias,
129
+ ) # is self-attn if encoder_hidden_states is none
130
+ else:
131
+ self.norm2 = None
132
+ self.attn2 = None
133
+
134
+ # 3. Feed-forward
135
+ if norm_type == "ada_norm_continuous":
136
+ self.norm3 = AdaLayerNormContinuous(
137
+ dim,
138
+ ada_norm_continous_conditioning_embedding_dim,
139
+ norm_elementwise_affine,
140
+ norm_eps,
141
+ ada_norm_bias,
142
+ "layer_norm",
143
+ )
144
+
145
+ elif norm_type in ["ada_norm_zero", "ada_norm", "layer_norm", "ada_norm_continuous"]:
146
+ self.norm3 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
147
+ elif norm_type == "layer_norm_i2vgen":
148
+ self.norm3 = None
149
+
150
+ self.ff = FeedForward(
151
+ dim,
152
+ dropout=dropout,
153
+ activation_fn=activation_fn,
154
+ final_dropout=final_dropout,
155
+ inner_dim=ff_inner_dim,
156
+ bias=ff_bias,
157
+ )
158
+
159
+ # 4. Fuser
160
+ if attention_type == "gated" or attention_type == "gated-text-image":
161
+ self.fuser = GatedSelfAttentionDense(dim, cross_attention_dim, num_attention_heads, attention_head_dim)
162
+
163
+ # 5. Scale-shift for PixArt-Alpha.
164
+ if norm_type == "ada_norm_single":
165
+ self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)
166
+
167
+ # let chunk size default to None
168
+ self._chunk_size = None
169
+ self._chunk_dim = 0
170
+
171
+ def get_inserted_modules(self):
172
+ return ()
173
+
174
+ def get_inserted_modules_names(self):
175
+ return ()
176
+
177
+ def get_origin_modules(self):
178
+ inserted_modules = self.get_inserted_modules()
179
+ origin_modules = []
180
+ for module in self.children():
181
+ if module not in inserted_modules:
182
+ origin_modules.append(module)
183
+ return tuple(origin_modules)
184
+
185
+
186
+ @classmethod
187
+ def from_transformer_block(
188
+ cls,
189
+ transformer_block,
190
+ glyph_cross_attention_dim,
191
+ ):
192
+ inner_dim = transformer_block.attn1.query_dim
193
+ num_attention_heads = transformer_block.attn1.heads
194
+ attention_head_dim = transformer_block.attn1.inner_dim // num_attention_heads
195
+ dropout = transformer_block.attn1.dropout
196
+ cross_attention_dim = transformer_block.attn2.cross_attention_dim
197
+ if isinstance(transformer_block.ff.net[0], GELU):
198
+ if transformer_block.ff.net[0].approximate == "tanh":
199
+ activation_fn = "gelu-approximate"
200
+ else:
201
+ activation_fn = "gelu"
202
+ elif isinstance(transformer_block.ff.net[0], GEGLU):
203
+ activation_fn = "geglu"
204
+ elif isinstance(transformer_block.ff.net[0], ApproximateGELU):
205
+ activation_fn = "geglu-approximate"
206
+ num_embeds_ada_norm = transformer_block.num_embeds_ada_norm
207
+ attention_bias = transformer_block.attn1.to_q.bias is not None
208
+ only_cross_attention = transformer_block.only_cross_attention
209
+ double_self_attention = transformer_block.attn2.cross_attention_dim is None
210
+ upcast_attention = transformer_block.attn1.upcast_attention
211
+ norm_type = transformer_block.norm_type
212
+ assert isinstance(transformer_block.norm1, nn.LayerNorm)
213
+ norm_elementwise_affine = transformer_block.norm1.elementwise_affine
214
+ norm_eps = transformer_block.norm1.eps
215
+ assert getattr(transformer_block, 'fuser', None) is None
216
+ attention_type = "default"
217
+ model = cls(
218
+ inner_dim,
219
+ num_attention_heads,
220
+ attention_head_dim,
221
+ dropout=dropout,
222
+ cross_attention_dim=cross_attention_dim,
223
+ glyph_cross_attention_dim=glyph_cross_attention_dim,
224
+ activation_fn=activation_fn,
225
+ num_embeds_ada_norm=num_embeds_ada_norm,
226
+ attention_bias=attention_bias,
227
+ only_cross_attention=only_cross_attention,
228
+ double_self_attention=double_self_attention,
229
+ upcast_attention=upcast_attention,
230
+ norm_type=norm_type,
231
+ norm_elementwise_affine=norm_elementwise_affine,
232
+ norm_eps=norm_eps,
233
+ attention_type=attention_type,
234
+ )
235
+ missing_keys, unexpected_keys = model.load_state_dict(
236
+ transformer_block.state_dict(),
237
+ strict=False,
238
+ )
239
+ assert len(unexpected_keys) == 0
240
+ assert all(i.startswith('glyph') for i in missing_keys)
241
+
242
+ return model
243
+
244
+ def forward(
245
+ self,
246
+ hidden_states: torch.FloatTensor,
247
+ attention_mask: Optional[torch.FloatTensor] = None,
248
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
249
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
250
+ timestep: Optional[torch.LongTensor] = None,
251
+ cross_attention_kwargs: Dict[str, Any] = None,
252
+ class_labels: Optional[torch.LongTensor] = None,
253
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
254
+ ) -> torch.FloatTensor:
255
+ # Notice that normalization is always applied before the real computation in the following blocks.
256
+ # 0. Self-Attention
257
+ batch_size = hidden_states.shape[0]
258
+
259
+ if self.norm_type == "ada_norm":
260
+ norm_hidden_states = self.norm1(hidden_states, timestep)
261
+ elif self.norm_type == "ada_norm_zero":
262
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
263
+ hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
264
+ )
265
+ elif self.norm_type in ["layer_norm", "layer_norm_i2vgen"]:
266
+ norm_hidden_states = self.norm1(hidden_states)
267
+ elif self.norm_type == "ada_norm_continuous":
268
+ norm_hidden_states = self.norm1(hidden_states, added_cond_kwargs["pooled_text_emb"])
269
+ elif self.norm_type == "ada_norm_single":
270
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
271
+ self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
272
+ ).chunk(6, dim=1)
273
+ norm_hidden_states = self.norm1(hidden_states)
274
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
275
+ norm_hidden_states = norm_hidden_states.squeeze(1)
276
+ else:
277
+ raise ValueError("Incorrect norm used")
278
+
279
+ if self.pos_embed is not None:
280
+ norm_hidden_states = self.pos_embed(norm_hidden_states)
281
+
282
+ # 1. Retrieve lora scale.
283
+ lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
284
+
285
+ # 2. Prepare GLIGEN inputs
286
+ cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
287
+ gligen_kwargs = cross_attention_kwargs.pop("gligen", None)
288
+
289
+ glyph_encoder_hidden_states = cross_attention_kwargs.pop("glyph_encoder_hidden_states", None)
290
+ # a dict. visual_feat_len: tensor(b, visual_feat_len,text—_feat_len)
291
+ glyph_attn_mask = cross_attention_kwargs.pop("glyph_attn_masks_dict", None)
292
+ bg_attn_mask = cross_attention_kwargs.pop("bg_attn_masks_dict", None)
293
+ if glyph_attn_mask is not None:
294
+ glyph_attn_mask = glyph_attn_mask[hidden_states.shape[1]]
295
+ if bg_attn_mask is not None:
296
+ bg_attn_mask = bg_attn_mask[hidden_states.shape[1]]
297
+ assert encoder_attention_mask is None, "encoder_attention_mask is not supported in this block."
298
+
299
+ attn_output = self.attn1(
300
+ norm_hidden_states,
301
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
302
+ attention_mask=attention_mask,
303
+ **cross_attention_kwargs,
304
+ )
305
+ if self.norm_type == "ada_norm_zero":
306
+ attn_output = gate_msa.unsqueeze(1) * attn_output
307
+ elif self.norm_type == "ada_norm_single":
308
+ attn_output = gate_msa * attn_output
309
+
310
+ hidden_states = attn_output + hidden_states
311
+ if hidden_states.ndim == 4:
312
+ hidden_states = hidden_states.squeeze(1)
313
+
314
+ # 2.5 GLIGEN Control
315
+ if gligen_kwargs is not None:
316
+ hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"])
317
+
318
+ # 3. Cross-Attention
319
+ if self.attn2 is not None:
320
+ if self.norm_type == "ada_norm":
321
+ norm_hidden_states = self.norm2(hidden_states, timestep)
322
+ elif self.norm_type in ["ada_norm_zero", "layer_norm", "layer_norm_i2vgen"]:
323
+ norm_hidden_states = self.norm2(hidden_states)
324
+ elif self.norm_type == "ada_norm_single":
325
+ # For PixArt norm2 isn't applied here:
326
+ # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
327
+ norm_hidden_states = hidden_states
328
+ elif self.norm_type == "ada_norm_continuous":
329
+ norm_hidden_states = self.norm2(hidden_states, added_cond_kwargs["pooled_text_emb"])
330
+ else:
331
+ raise ValueError("Incorrect norm")
332
+
333
+ if self.pos_embed is not None and self.norm_type != "ada_norm_single":
334
+ norm_hidden_states = self.pos_embed(norm_hidden_states)
335
+
336
+ attn_output = self.attn2(
337
+ norm_hidden_states,
338
+ encoder_hidden_states=torch.cat([encoder_hidden_states, glyph_encoder_hidden_states], dim=1),
339
+ attention_mask=torch.cat([bg_attn_mask, glyph_attn_mask], dim=-1),
340
+ **cross_attention_kwargs,
341
+ )
342
+
343
+ hidden_states = attn_output + hidden_states
344
+
345
+ # 4. Feed-forward
346
+ # i2vgen doesn't have this norm 🤷‍♂️
347
+ if self.norm_type == "ada_norm_continuous":
348
+ norm_hidden_states = self.norm3(hidden_states, added_cond_kwargs["pooled_text_emb"])
349
+ elif not self.norm_type == "ada_norm_single":
350
+ norm_hidden_states = self.norm3(hidden_states)
351
+
352
+ if self.norm_type == "ada_norm_zero":
353
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
354
+
355
+ if self.norm_type == "ada_norm_single":
356
+ norm_hidden_states = self.norm2(hidden_states)
357
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
358
+
359
+ if self._chunk_size is not None:
360
+ # "feed_forward_chunk_size" can be used to save memory
361
+ ff_output = _chunked_feed_forward(
362
+ self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size, lora_scale=lora_scale
363
+ )
364
+ else:
365
+ ff_output = self.ff(norm_hidden_states, scale=lora_scale)
366
+
367
+ if self.norm_type == "ada_norm_zero":
368
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
369
+ elif self.norm_type == "ada_norm_single":
370
+ ff_output = gate_mlp * ff_output
371
+
372
+ hidden_states = ff_output + hidden_states
373
+ if hidden_states.ndim == 4:
374
+ hidden_states = hidden_states.squeeze(1)
375
+
376
+ return hidden_states
377
+
text_encoder/Glyph-SDXL-v2/glyph_sdxl/custom_diffusers/pipelines/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .pipeline_stable_diffusion_glyph_xl import StableDiffusionGlyphXLPipeline
2
+
3
+ __all__ = [
4
+ 'StableDiffusionGlyphXLPipeline',
5
+ ]
text_encoder/Glyph-SDXL-v2/glyph_sdxl/custom_diffusers/pipelines/pipeline_stable_diffusion_glyph_xl.py ADDED
@@ -0,0 +1,922 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from typing import Optional, List, Union, Dict, Tuple, Callable, Any
3
+ import torch
4
+
5
+ from transformers import T5EncoderModel, T5Tokenizer
6
+ import torch.nn.functional as F
7
+
8
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl import (
9
+ StableDiffusionXLPipeline,
10
+ AutoencoderKL,
11
+ CLIPTextModel,
12
+ CLIPTextModelWithProjection,
13
+ CLIPTokenizer,
14
+ UNet2DConditionModel,
15
+ KarrasDiffusionSchedulers,
16
+ CLIPVisionModelWithProjection,
17
+ CLIPImageProcessor,
18
+ VaeImageProcessor,
19
+ is_invisible_watermark_available,
20
+ StableDiffusionXLLoraLoaderMixin,
21
+ PipelineImageInput,
22
+ adjust_lora_scale_text_encoder,
23
+ scale_lora_layers,
24
+ unscale_lora_layers,
25
+ USE_PEFT_BACKEND,
26
+ StableDiffusionXLPipelineOutput,
27
+ ImageProjection,
28
+ logging,
29
+ rescale_noise_cfg,
30
+ retrieve_timesteps,
31
+ deprecate,
32
+ )
33
+ import numpy as np
34
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
35
+
36
+ from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
37
+
38
+ class StableDiffusionGlyphXLPipeline(StableDiffusionXLPipeline):
39
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->byt5_text_encoder->image_encoder->unet->byt5_mapper->vae"
40
+ _optional_components = [
41
+ "tokenizer",
42
+ "tokenizer_2",
43
+ "byt5_tokenizer",
44
+ "text_encoder",
45
+ "text_encoder_2",
46
+ "byt5_text_encoder",
47
+ "byt5_mapper",
48
+ "image_encoder",
49
+ "feature_extractor",
50
+ ]
51
+ _callback_tensor_inputs = [
52
+ "latents",
53
+ "prompt_embeds",
54
+ "negative_prompt_embeds",
55
+ "add_text_embeds",
56
+ "add_time_ids",
57
+ "negative_pooled_prompt_embeds",
58
+ "negative_add_time_ids",
59
+ ]
60
+ def __init__(
61
+ self,
62
+ vae: AutoencoderKL,
63
+ text_encoder: CLIPTextModel,
64
+ text_encoder_2: CLIPTextModelWithProjection,
65
+ byt5_text_encoder: T5EncoderModel,
66
+ tokenizer: CLIPTokenizer,
67
+ tokenizer_2: CLIPTokenizer,
68
+ byt5_tokenizer: T5Tokenizer,
69
+ byt5_mapper,
70
+ unet: UNet2DConditionModel,
71
+ scheduler: KarrasDiffusionSchedulers,
72
+ byt5_max_length: int = 512,
73
+ image_encoder: CLIPVisionModelWithProjection = None,
74
+ feature_extractor: CLIPImageProcessor = None,
75
+ force_zeros_for_empty_prompt: bool = True,
76
+ add_watermarker: Optional[bool] = None,
77
+ ):
78
+ super(StableDiffusionXLPipeline, self).__init__()
79
+
80
+ self.register_modules(
81
+ vae=vae,
82
+ text_encoder=text_encoder,
83
+ text_encoder_2=text_encoder_2,
84
+ byt5_text_encoder=byt5_text_encoder,
85
+ tokenizer=tokenizer,
86
+ tokenizer_2=tokenizer_2,
87
+ byt5_tokenizer=byt5_tokenizer,
88
+ byt5_mapper=byt5_mapper,
89
+ unet=unet,
90
+ scheduler=scheduler,
91
+ image_encoder=image_encoder,
92
+ feature_extractor=feature_extractor,
93
+ )
94
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
95
+ self.register_to_config(byt5_max_length=byt5_max_length)
96
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
97
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
98
+ self.byt5_max_length = byt5_max_length
99
+
100
+ self.default_sample_size = self.unet.config.sample_size
101
+
102
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
103
+
104
+ if add_watermarker:
105
+ self.watermark = StableDiffusionXLWatermarker()
106
+ else:
107
+ self.watermark = None
108
+
109
+ def encode_prompt(
110
+ self,
111
+ prompt: str,
112
+ prompt_2: Optional[str] = None,
113
+ text_prompt = None,
114
+ device: Optional[torch.device] = None,
115
+ num_images_per_prompt: int = 1,
116
+ do_classifier_free_guidance: bool = True,
117
+ negative_prompt: Optional[str] = None,
118
+ negative_prompt_2: Optional[str] = None,
119
+ prompt_embeds: Optional[torch.FloatTensor] = None,
120
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
121
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
122
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
123
+ lora_scale: Optional[float] = None,
124
+ clip_skip: Optional[int] = None,
125
+ text_attn_mask: Optional[torch.LongTensor] = None,
126
+ byt5_prompt_embeds: Optional[torch.FloatTensor] = None,
127
+ ):
128
+ r"""
129
+ Encodes the prompt into text encoder hidden states.
130
+
131
+ Args:
132
+ prompt (`str` or `List[str]`, *optional*):
133
+ prompt to be encoded
134
+ prompt_2 (`str` or `List[str]`, *optional*):
135
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
136
+ used in both text-encoders
137
+ device: (`torch.device`):
138
+ torch device
139
+ num_images_per_prompt (`int`):
140
+ number of images that should be generated per prompt
141
+ do_classifier_free_guidance (`bool`):
142
+ whether to use classifier free guidance or not
143
+ negative_prompt (`str` or `List[str]`, *optional*):
144
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
145
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
146
+ less than `1`).
147
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
148
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
149
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
150
+ prompt_embeds (`torch.FloatTensor`, *optional*):
151
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
152
+ provided, text embeddings will be generated from `prompt` input argument.
153
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
154
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
155
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
156
+ argument.
157
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
158
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
159
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
160
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
161
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
162
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
163
+ input argument.
164
+ lora_scale (`float`, *optional*):
165
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
166
+ clip_skip (`int`, *optional*):
167
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
168
+ the output of the pre-final layer will be used for computing the prompt embeddings.
169
+ """
170
+ device = device or self._execution_device
171
+
172
+ # set lora scale so that monkey patched LoRA
173
+ # function of text encoder can correctly access it
174
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
175
+ self._lora_scale = lora_scale
176
+
177
+ # dynamically adjust the LoRA scale
178
+ if self.text_encoder is not None:
179
+ if not USE_PEFT_BACKEND:
180
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
181
+ else:
182
+ scale_lora_layers(self.text_encoder, lora_scale)
183
+
184
+ if self.text_encoder_2 is not None:
185
+ if not USE_PEFT_BACKEND:
186
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
187
+ else:
188
+ scale_lora_layers(self.text_encoder_2, lora_scale)
189
+
190
+ prompt = [prompt] if isinstance(prompt, str) else prompt
191
+
192
+ if prompt is not None:
193
+ batch_size = len(prompt)
194
+ else:
195
+ batch_size = prompt_embeds.shape[0]
196
+
197
+ # Define tokenizers and text encoders
198
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
199
+ text_encoders = (
200
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
201
+ )
202
+
203
+ if prompt_embeds is None:
204
+ assert len(prompt) == 1
205
+ prompt_2 = prompt_2 or prompt
206
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
207
+
208
+ text_prompt = [text_prompt] if isinstance(text_prompt, str) else text_prompt
209
+
210
+ # textual inversion: procecss multi-vector tokens if necessary
211
+ prompt_embeds_list = []
212
+ prompts = [prompt, prompt_2]
213
+ text_input_id_batchs = []
214
+ for prompt, tokenizer in zip(prompts, tokenizers):
215
+ pad_token = tokenizer.pad_token_id
216
+ total_tokens = tokenizer(prompt, truncation=False)['input_ids'][0]
217
+ bos = total_tokens[0]
218
+ eos = total_tokens[-1]
219
+ total_tokens = total_tokens[1:-1]
220
+ new_total_tokens = []
221
+ empty_flag = True
222
+ while len(total_tokens) >= 75:
223
+ head_75_tokens = [total_tokens.pop(0) for _ in range(75)]
224
+ temp_77_token_ids = [bos] + head_75_tokens + [eos]
225
+ new_total_tokens.append(temp_77_token_ids)
226
+ empty_flag = False
227
+ if len(total_tokens) > 0 or empty_flag:
228
+ padding_len = 75 - len(total_tokens)
229
+ temp_77_token_ids = [bos] + total_tokens + [eos] + [pad_token] * padding_len
230
+ new_total_tokens.append(temp_77_token_ids)
231
+ # 1,segment_len, 77
232
+ new_total_tokens = torch.tensor(new_total_tokens, dtype=torch.long).unsqueeze(0)
233
+ text_input_id_batchs.append(new_total_tokens)
234
+ if text_input_id_batchs[0].shape[1] > text_input_id_batchs[1].shape[1]:
235
+ tokenizer = tokenizers[1]
236
+ pad_token = tokenizer.pad_token_id
237
+ bos = tokenizer.bos_token_id
238
+ eos = tokenizer.eos_token_id
239
+ padding_len = text_input_id_batchs[0].shape[1] - text_input_id_batchs[1].shape[1]
240
+ # padding_len, 77
241
+ padding_part = torch.tensor([[bos] + [eos] + [pad_token] * 75 for _ in range(padding_len)])
242
+ # 1, padding_len, 77
243
+ padding_part = padding_part.unsqueeze(0)
244
+ text_input_id_batchs[1] = torch.cat((text_input_id_batchs[1],padding_part), dim=1)
245
+ elif text_input_id_batchs[0].shape[1] < text_input_id_batchs[1].shape[1]:
246
+ tokenizer = tokenizers[0]
247
+ pad_token = tokenizer.pad_token_id
248
+ bos = tokenizer.bos_token_id
249
+ eos = tokenizer.eos_token_id
250
+ padding_len = text_input_id_batchs[1].shape[1] - text_input_id_batchs[0].shape[1]
251
+ # padding_len, 77
252
+ padding_part = torch.tensor([[bos] + [eos] + [pad_token] * 75 for _ in range(padding_len)])
253
+ # 1, padding_len, 77
254
+ padding_part = padding_part.unsqueeze(0)
255
+ text_input_id_batchs[0] = torch.cat((text_input_id_batchs[0],padding_part), dim=1)
256
+
257
+ embeddings = []
258
+ for segment_idx in range(text_input_id_batchs[0].shape[1]):
259
+ prompt_embeds_list = []
260
+ for i, text_encoder in enumerate(text_encoders):
261
+ # 1, segment_len, sequence_len
262
+ text_input_ids = text_input_id_batchs[i].to(text_encoder.device)
263
+ # 1, sequence_len, dim
264
+ prompt_embeds = text_encoder(
265
+ text_input_ids[:, segment_idx],
266
+ output_hidden_states=True,
267
+ )
268
+
269
+ # We are only ALWAYS interested in the pooled output of the final text encoder
270
+ temp_pooled_prompt_embeds = prompt_embeds[0]
271
+ if clip_skip is None:
272
+ prompt_embeds = prompt_embeds.hidden_states[-2]
273
+ else:
274
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
275
+ bs_embed, seq_len, _ = prompt_embeds.shape
276
+ prompt_embeds = prompt_embeds.view(bs_embed, seq_len, -1)
277
+ prompt_embeds_list.append(prompt_embeds)
278
+ # b, sequence_len, dim
279
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
280
+ embeddings.append(prompt_embeds)
281
+ if segment_idx == 0:
282
+ # use the first segment's pooled prompt embeddings as
283
+ # the pooled prompt embeddings
284
+ # b, dim->b, dim
285
+ pooled_prompt_embeds = temp_pooled_prompt_embeds.view(bs_embed, -1)
286
+ # b, segment_len * sequence_len, dim
287
+ prompt_embeds = torch.cat(embeddings, dim=1)
288
+
289
+ if byt5_prompt_embeds is None:
290
+ byt5_text_inputs = self.byt5_tokenizer(
291
+ text_prompt,
292
+ padding="max_length",
293
+ max_length=self.byt5_max_length,
294
+ truncation=True,
295
+ add_special_tokens=True,
296
+ return_tensors="pt",
297
+ )
298
+ byt5_text_input_ids = byt5_text_inputs.input_ids
299
+ byt5_attention_mask = byt5_text_inputs.attention_mask.to(self.byt5_text_encoder.device) if text_attn_mask is None else text_attn_mask.to(self.byt5_text_encoder.device, dtype=byt5_text_inputs.attention_mask.dtype)
300
+ with torch.cuda.amp.autocast(enabled=False):
301
+ byt5_prompt_embeds = self.byt5_text_encoder(
302
+ byt5_text_input_ids.to(self.byt5_text_encoder.device),
303
+ attention_mask=byt5_attention_mask.float(),
304
+ )
305
+ byt5_prompt_embeds = byt5_prompt_embeds[0]
306
+ byt5_prompt_embeds = self.byt5_mapper(byt5_prompt_embeds, byt5_attention_mask)
307
+
308
+ # get unconditional embeddings for classifier free guidance
309
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
310
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
311
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
312
+ negative_byt5_prompt_embeds = torch.zeros_like(byt5_prompt_embeds)
313
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
314
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
315
+ raise NotImplementedError
316
+
317
+ if self.text_encoder_2 is not None:
318
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
319
+ else:
320
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
321
+
322
+ bs_embed, seq_len, _ = prompt_embeds.shape
323
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
324
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
325
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
326
+
327
+ if do_classifier_free_guidance:
328
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
329
+ seq_len = negative_prompt_embeds.shape[1]
330
+ byt5_seq_len = negative_byt5_prompt_embeds.shape[1]
331
+
332
+ if self.text_encoder_2 is not None:
333
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
334
+ else:
335
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
336
+ negative_byt5_prompt_embeds = negative_byt5_prompt_embeds.to(dtype=self.byt5_text_encoder.dtype, device=device)
337
+
338
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
339
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
340
+ negative_byt5_prompt_embeds = negative_byt5_prompt_embeds.repeat(1, num_images_per_prompt, 1)
341
+ negative_byt5_prompt_embeds = negative_byt5_prompt_embeds.view(batch_size * num_images_per_prompt, byt5_seq_len, -1)
342
+
343
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
344
+ bs_embed * num_images_per_prompt, -1
345
+ )
346
+ if do_classifier_free_guidance:
347
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
348
+ bs_embed * num_images_per_prompt, -1
349
+ )
350
+
351
+ if self.text_encoder is not None:
352
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
353
+ # Retrieve the original scale by scaling back the LoRA layers
354
+ unscale_lora_layers(self.text_encoder, lora_scale)
355
+
356
+ if self.text_encoder_2 is not None:
357
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
358
+ # Retrieve the original scale by scaling back the LoRA layers
359
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
360
+
361
+ return (
362
+ prompt_embeds,
363
+ negative_prompt_embeds,
364
+ pooled_prompt_embeds,
365
+ negative_pooled_prompt_embeds,
366
+ byt5_prompt_embeds,
367
+ negative_byt5_prompt_embeds,
368
+ )
369
+
370
+ @torch.no_grad()
371
+ def __call__(
372
+ self,
373
+ prompt: Union[str, List[str]] = None,
374
+ prompt_2: Optional[Union[str, List[str]]] = None,
375
+ text_prompt = None,
376
+ texts = None,
377
+ bboxes = None,
378
+ height: Optional[int] = None,
379
+ width: Optional[int] = None,
380
+ num_inference_steps: int = 50,
381
+ timesteps: List[int] = None,
382
+ denoising_end: Optional[float] = None,
383
+ guidance_scale: float = 5.0,
384
+ negative_prompt: Optional[Union[str, List[str]]] = None,
385
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
386
+ num_images_per_prompt: Optional[int] = 1,
387
+ eta: float = 0.0,
388
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
389
+ latents: Optional[torch.FloatTensor] = None,
390
+ prompt_embeds: Optional[torch.FloatTensor] = None,
391
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
392
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
393
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
394
+ ip_adapter_image: Optional[PipelineImageInput] = None,
395
+ output_type: Optional[str] = "pil",
396
+ return_dict: bool = True,
397
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
398
+ guidance_rescale: float = 0.0,
399
+ original_size: Optional[Tuple[int, int]] = None,
400
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
401
+ target_size: Optional[Tuple[int, int]] = None,
402
+ negative_original_size: Optional[Tuple[int, int]] = None,
403
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
404
+ negative_target_size: Optional[Tuple[int, int]] = None,
405
+ clip_skip: Optional[int] = None,
406
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
407
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
408
+ text_attn_mask: torch.LongTensor = None,
409
+ denoising_start: Optional[float] = None,
410
+ byt5_prompt_embeds: Optional[torch.FloatTensor] = None,
411
+ **kwargs,
412
+ ):
413
+ r"""
414
+ Function invoked when calling the pipeline for generation.
415
+
416
+ Args:
417
+ prompt (`str` or `List[str]`, *optional*):
418
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
419
+ instead.
420
+ prompt_2 (`str` or `List[str]`, *optional*):
421
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
422
+ used in both text-encoders
423
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
424
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
425
+ Anything below 512 pixels won't work well for
426
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
427
+ and checkpoints that are not specifically fine-tuned on low resolutions.
428
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
429
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
430
+ Anything below 512 pixels won't work well for
431
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
432
+ and checkpoints that are not specifically fine-tuned on low resolutions.
433
+ num_inference_steps (`int`, *optional*, defaults to 50):
434
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
435
+ expense of slower inference.
436
+ timesteps (`List[int]`, *optional*):
437
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
438
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
439
+ passed will be used. Must be in descending order.
440
+ denoising_end (`float`, *optional*):
441
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
442
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
443
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
444
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
445
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
446
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
447
+ guidance_scale (`float`, *optional*, defaults to 5.0):
448
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
449
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
450
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
451
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
452
+ usually at the expense of lower image quality.
453
+ negative_prompt (`str` or `List[str]`, *optional*):
454
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
455
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
456
+ less than `1`).
457
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
458
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
459
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
460
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
461
+ The number of images to generate per prompt.
462
+ eta (`float`, *optional*, defaults to 0.0):
463
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
464
+ [`schedulers.DDIMScheduler`], will be ignored for others.
465
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
466
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
467
+ to make generation deterministic.
468
+ latents (`torch.FloatTensor`, *optional*):
469
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
470
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
471
+ tensor will ge generated by sampling using the supplied random `generator`.
472
+ prompt_embeds (`torch.FloatTensor`, *optional*):
473
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
474
+ provided, text embeddings will be generated from `prompt` input argument.
475
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
476
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
477
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
478
+ argument.
479
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
480
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
481
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
482
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
483
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
484
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
485
+ input argument.
486
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
487
+ output_type (`str`, *optional*, defaults to `"pil"`):
488
+ The output format of the generate image. Choose between
489
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
490
+ return_dict (`bool`, *optional*, defaults to `True`):
491
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
492
+ of a plain tuple.
493
+ cross_attention_kwargs (`dict`, *optional*):
494
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
495
+ `self.processor` in
496
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
497
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
498
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
499
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
500
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
501
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
502
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
503
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
504
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
505
+ explained in section 2.2 of
506
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
507
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
508
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
509
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
510
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
511
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
512
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
513
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
514
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
515
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
516
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
517
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
518
+ micro-conditioning as explained in section 2.2 of
519
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
520
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
521
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
522
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
523
+ micro-conditioning as explained in section 2.2 of
524
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
525
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
526
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
527
+ To negatively condition the generation process based on a target image resolution. It should be as same
528
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
529
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
530
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
531
+ callback_on_step_end (`Callable`, *optional*):
532
+ A function that calls at the end of each denoising steps during the inference. The function is called
533
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
534
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
535
+ `callback_on_step_end_tensor_inputs`.
536
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
537
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
538
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
539
+ `._callback_tensor_inputs` attribute of your pipeline class.
540
+
541
+ Examples:
542
+
543
+ Returns:
544
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
545
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
546
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
547
+ """
548
+
549
+ callback = kwargs.pop("callback", None)
550
+ callback_steps = kwargs.pop("callback_steps", None)
551
+
552
+ if callback is not None:
553
+ deprecate(
554
+ "callback",
555
+ "1.0.0",
556
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
557
+ )
558
+ if callback_steps is not None:
559
+ deprecate(
560
+ "callback_steps",
561
+ "1.0.0",
562
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
563
+ )
564
+
565
+ # 0. Default height and width to unet
566
+ height = height or self.default_sample_size * self.vae_scale_factor
567
+ width = width or self.default_sample_size * self.vae_scale_factor
568
+
569
+ original_size = original_size or (height, width)
570
+ target_size = target_size or (height, width)
571
+
572
+ # 1. Check inputs. Raise error if not correct
573
+ self.check_inputs(
574
+ prompt,
575
+ prompt_2,
576
+ height,
577
+ width,
578
+ callback_steps,
579
+ negative_prompt,
580
+ negative_prompt_2,
581
+ prompt_embeds,
582
+ negative_prompt_embeds,
583
+ pooled_prompt_embeds,
584
+ negative_pooled_prompt_embeds,
585
+ callback_on_step_end_tensor_inputs,
586
+ )
587
+
588
+ self._guidance_scale = guidance_scale
589
+ self._guidance_rescale = guidance_rescale
590
+ self._clip_skip = clip_skip
591
+ self._cross_attention_kwargs = cross_attention_kwargs
592
+ self._denoising_end = denoising_end
593
+ self._interrupt = False
594
+
595
+ # 2. Define call parameters
596
+ if prompt is not None and isinstance(prompt, str):
597
+ batch_size = 1
598
+ elif prompt is not None and isinstance(prompt, list):
599
+ batch_size = len(prompt)
600
+ else:
601
+ batch_size = prompt_embeds.shape[0]
602
+
603
+ device = self._execution_device
604
+
605
+ # 3. Encode input prompt
606
+ lora_scale = (
607
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
608
+ )
609
+
610
+ (
611
+ prompt_embeds,
612
+ negative_prompt_embeds,
613
+ pooled_prompt_embeds,
614
+ negative_pooled_prompt_embeds,
615
+ byt5_prompt_embeds,
616
+ negative_byt5_prompt_embeds,
617
+ ) = self.encode_prompt(
618
+ prompt=prompt,
619
+ prompt_2=prompt_2,
620
+ text_prompt=text_prompt,
621
+ device=device,
622
+ num_images_per_prompt=num_images_per_prompt,
623
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
624
+ negative_prompt=negative_prompt,
625
+ negative_prompt_2=negative_prompt_2,
626
+ prompt_embeds=prompt_embeds,
627
+ negative_prompt_embeds=negative_prompt_embeds,
628
+ pooled_prompt_embeds=pooled_prompt_embeds,
629
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
630
+ lora_scale=lora_scale,
631
+ clip_skip=self.clip_skip,
632
+ text_attn_mask=text_attn_mask,
633
+ byt5_prompt_embeds=byt5_prompt_embeds,
634
+ )
635
+
636
+ # 4. Prepare timesteps
637
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
638
+
639
+ # 5. Prepare latent variables
640
+ num_channels_latents = self.unet.config.in_channels
641
+ latents = self.prepare_latents(
642
+ batch_size * num_images_per_prompt,
643
+ num_channels_latents,
644
+ height,
645
+ width,
646
+ prompt_embeds.dtype,
647
+ device,
648
+ generator,
649
+ latents,
650
+ )
651
+
652
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
653
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
654
+
655
+ # 7. Prepare added time ids & embeddings
656
+ add_text_embeds = pooled_prompt_embeds
657
+ if self.text_encoder_2 is None:
658
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
659
+ else:
660
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
661
+
662
+ add_time_ids = self._get_add_time_ids(
663
+ original_size,
664
+ crops_coords_top_left,
665
+ target_size,
666
+ dtype=prompt_embeds.dtype,
667
+ text_encoder_projection_dim=text_encoder_projection_dim,
668
+ )
669
+ if negative_original_size is not None and negative_target_size is not None:
670
+ negative_add_time_ids = self._get_add_time_ids(
671
+ negative_original_size,
672
+ negative_crops_coords_top_left,
673
+ negative_target_size,
674
+ dtype=prompt_embeds.dtype,
675
+ text_encoder_projection_dim=text_encoder_projection_dim,
676
+ )
677
+ else:
678
+ negative_add_time_ids = add_time_ids
679
+
680
+ if self.do_classifier_free_guidance:
681
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
682
+ byt5_prompt_embeds = torch.cat([negative_byt5_prompt_embeds, byt5_prompt_embeds], dim=0)
683
+
684
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
685
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
686
+
687
+ prompt_embeds = prompt_embeds.to(device)
688
+ byt5_prompt_embeds = byt5_prompt_embeds.to(device)
689
+ add_text_embeds = add_text_embeds.to(device)
690
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
691
+
692
+ if ip_adapter_image is not None:
693
+ output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
694
+ image_embeds, negative_image_embeds = self.encode_image(
695
+ ip_adapter_image, device, num_images_per_prompt, output_hidden_state
696
+ )
697
+ if self.do_classifier_free_guidance:
698
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
699
+ image_embeds = image_embeds.to(device)
700
+
701
+ # 8. Denoising loop
702
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
703
+
704
+ # 8.1 Apply denoising_end
705
+ if (
706
+ self.denoising_end is not None
707
+ and isinstance(self.denoising_end, float)
708
+ and self.denoising_end > 0
709
+ and self.denoising_end < 1
710
+ ):
711
+ discrete_timestep_cutoff = int(
712
+ round(
713
+ self.scheduler.config.num_train_timesteps
714
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
715
+ )
716
+ )
717
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
718
+ timesteps = timesteps[:num_inference_steps]
719
+
720
+ # 9. Optionally get Guidance Scale Embedding
721
+ timestep_cond = None
722
+ if self.unet.config.time_cond_proj_dim is not None:
723
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
724
+ timestep_cond = self.get_guidance_scale_embedding(
725
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
726
+ ).to(device=device, dtype=latents.dtype)
727
+
728
+ assert batch_size == 1, "batch_size > 1 is not supported"
729
+ if texts is not None:
730
+ glyph_attn_mask = self.get_glyph_attn_mask(texts, bboxes)
731
+ # h,w
732
+ bg_attn_mask = glyph_attn_mask.sum(-1) == 0
733
+ # 1,h,w,byt5_max_len
734
+ glyph_attn_masks = glyph_attn_mask.unsqueeze(0).to(device)
735
+ # 1,h,w
736
+ bg_attn_masks = bg_attn_mask.unsqueeze(0).to(glyph_attn_masks.dtype).to(device)
737
+
738
+ # b, h, w, text_feat_len
739
+ glyph_attn_masks = (1 - glyph_attn_masks) * -10000.0
740
+ # b, h, w
741
+ bg_attn_masks = (1 - bg_attn_masks) * -10000.0
742
+ num_down_sample = sum(1 if i == 'CrossAttnDownBlock2D' else 0 for i in self.unet.config['down_block_types']) - 1
743
+ initial_resolution = self.default_sample_size
744
+ initial_resolution = initial_resolution // 2**sum(1 if i == 'DownBlock2D' else 0 for i in self.unet.config['down_block_types'])
745
+ resolution_list = [initial_resolution] + [initial_resolution // 2**i for i in range(1, num_down_sample + 1)]
746
+ glyph_attn_masks_dict = dict()
747
+ bg_attn_masks_dict = dict()
748
+ # b, text_fet_len, h, w
749
+ glyph_attn_masks = glyph_attn_masks.permute(0, 3, 1, 2)
750
+ # b, 1, h, w
751
+ bg_attn_masks = bg_attn_masks.unsqueeze(1)
752
+ for mask_resolution in resolution_list:
753
+ down_scaled_glyph_attn_masks = F.interpolate(
754
+ glyph_attn_masks, size=(mask_resolution, mask_resolution), mode='nearest',
755
+ )
756
+ # b, text_fet_len, h, w->b, h, w, text_fet_len->b, h*w, text_fet_len
757
+ down_scaled_glyph_attn_masks = down_scaled_glyph_attn_masks.permute(0, 2, 3, 1).flatten(1, 2)
758
+ glyph_attn_masks_dict[mask_resolution * mask_resolution] = down_scaled_glyph_attn_masks
759
+
760
+ down_scaled_bg_attn_masks = F.interpolate(
761
+ bg_attn_masks, size=(mask_resolution, mask_resolution), mode='nearest',
762
+ )
763
+ # b,1,h,w->b,h,w->b,h,w,1->b,h*w,1->b,h*w,clip_feat_len
764
+ down_scaled_bg_attn_masks = down_scaled_bg_attn_masks.squeeze(1).unsqueeze(-1)
765
+ down_scaled_bg_attn_masks = down_scaled_bg_attn_masks.flatten(1, 2)
766
+ down_scaled_bg_attn_masks = down_scaled_bg_attn_masks.repeat(1, 1, prompt_embeds.shape[1])
767
+ bg_attn_masks_dict[mask_resolution * mask_resolution] = down_scaled_bg_attn_masks
768
+ if self.do_classifier_free_guidance:
769
+ for key in glyph_attn_masks_dict:
770
+ glyph_attn_masks_dict[key] = torch.cat([
771
+ torch.zeros_like(glyph_attn_masks_dict[key]),
772
+ glyph_attn_masks_dict[key]],
773
+ dim=0)
774
+ for key in bg_attn_masks_dict:
775
+ bg_attn_masks_dict[key] = torch.cat([
776
+ torch.zeros_like(bg_attn_masks_dict[key]),
777
+ bg_attn_masks_dict[key]],
778
+ dim=0)
779
+ else:
780
+ glyph_attn_masks_dict = None
781
+ bg_attn_masks_dict = None
782
+
783
+ self._num_timesteps = len(timesteps)
784
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
785
+ for i, t in enumerate(timesteps):
786
+ if self.interrupt:
787
+ continue
788
+
789
+ # expand the latents if we are doing classifier free guidance
790
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
791
+
792
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
793
+
794
+ # predict the noise residual
795
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
796
+ if ip_adapter_image is not None:
797
+ added_cond_kwargs["image_embeds"] = image_embeds
798
+ if self.cross_attention_kwargs is None:
799
+ cross_attention_kwargs = {}
800
+ else:
801
+ cross_attention_kwargs = self.cross_attention_kwargs
802
+ cross_attention_kwargs['glyph_encoder_hidden_states'] = byt5_prompt_embeds
803
+ cross_attention_kwargs['glyph_attn_masks_dict'] = glyph_attn_masks_dict
804
+ cross_attention_kwargs['bg_attn_masks_dict'] = bg_attn_masks_dict
805
+
806
+ noise_pred = self.unet(
807
+ latent_model_input,
808
+ t,
809
+ encoder_hidden_states=prompt_embeds,
810
+ timestep_cond=timestep_cond,
811
+ cross_attention_kwargs=cross_attention_kwargs,
812
+ added_cond_kwargs=added_cond_kwargs,
813
+ return_dict=False,
814
+ )[0]
815
+
816
+ # perform guidance
817
+ if self.do_classifier_free_guidance:
818
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
819
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
820
+
821
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
822
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
823
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
824
+
825
+ # compute the previous noisy sample x_t -> x_t-1
826
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
827
+
828
+ if callback_on_step_end is not None:
829
+ callback_kwargs = {}
830
+ for k in callback_on_step_end_tensor_inputs:
831
+ callback_kwargs[k] = locals()[k]
832
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
833
+
834
+ latents = callback_outputs.pop("latents", latents)
835
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
836
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
837
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
838
+ negative_pooled_prompt_embeds = callback_outputs.pop(
839
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
840
+ )
841
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
842
+ negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
843
+
844
+ # call the callback, if provided
845
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
846
+ progress_bar.update()
847
+ if callback is not None and i % callback_steps == 0:
848
+ step_idx = i // getattr(self.scheduler, "order", 1)
849
+ callback(step_idx, t, latents)
850
+
851
+ if not output_type == "latent":
852
+ # make sure the VAE is in float32 mode, as it overflows in float16
853
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
854
+
855
+ if needs_upcasting:
856
+ self.upcast_vae()
857
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
858
+
859
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
860
+
861
+ # cast back to fp16 if needed
862
+ if needs_upcasting:
863
+ self.vae.to(dtype=torch.float16)
864
+ else:
865
+ image = latents
866
+
867
+ if not output_type == "latent":
868
+ # apply watermark if available
869
+ if self.watermark is not None:
870
+ image = self.watermark.apply_watermark(image)
871
+
872
+ image = self.image_processor.postprocess(image, output_type=output_type)
873
+
874
+ # Offload all models
875
+ self.maybe_free_model_hooks()
876
+
877
+ if not return_dict:
878
+ return (image,)
879
+
880
+ return StableDiffusionXLPipelineOutput(images=image)
881
+
882
+ def get_glyph_attn_mask(self, texts, bboxes):
883
+ resolution = self.default_sample_size
884
+ text_idx_list = self.get_text_start_pos(texts)
885
+ mask_tensor = torch.zeros(
886
+ resolution, resolution, self.byt5_max_length,
887
+ )
888
+ for idx, bbox in enumerate(bboxes):
889
+ # box is in [x, y, w, h] format
890
+ # area of [y:y+h, x:x+w]
891
+ bbox = [int(v * resolution + 0.5) for v in bbox]
892
+ bbox[2] = max(bbox[2], 1)
893
+ bbox[3] = max(bbox[3], 1)
894
+ bbox[0: 2] = np.clip(bbox[0: 2], 0, resolution - 1).tolist()
895
+ bbox[2: 4] = np.clip(bbox[2: 4], 1, resolution).tolist()
896
+ mask_tensor[
897
+ bbox[1]: bbox[1] + bbox[3],
898
+ bbox[0]: bbox[0] + bbox[2],
899
+ text_idx_list[idx]: text_idx_list[idx + 1]
900
+ ] = 1
901
+ return mask_tensor
902
+
903
+ def get_text_start_pos(self, texts):
904
+ prompt = "".encode('utf-8')
905
+ '''
906
+ Text "{text}" in {color}, {type}.
907
+ '''
908
+ pos_list = []
909
+ for text in texts:
910
+ pos_list.append(len(prompt))
911
+ text_prompt = f'Text "{text}"'
912
+
913
+ attr_list = ['0', '1']
914
+
915
+ attr_suffix = ", ".join(attr_list)
916
+ text_prompt += " in " + attr_suffix
917
+ text_prompt += ". "
918
+ text_prompt = text_prompt.encode('utf-8')
919
+
920
+ prompt = prompt + text_prompt
921
+ pos_list.append(len(prompt))
922
+ return pos_list
text_encoder/Glyph-SDXL-v2/glyph_sdxl/modules/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from .simple_byt5_mapper import ByT5Mapper
2
+ from .byt5_block_byt5_mapper import T5EncoderBlockByT5Mapper
3
+
4
+ __all__ = [
5
+ 'ByT5Mapper',
6
+ 'T5EncoderBlockByT5Mapper',
7
+ ]
text_encoder/Glyph-SDXL-v2/glyph_sdxl/modules/byt5_block_byt5_mapper.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
4
+
5
+ import warnings
6
+
7
+ import logging
8
+ from torch import Tensor
9
+ from diffusers import ModelMixin
10
+ from transformers.models.t5.modeling_t5 import T5LayerSelfAttention, T5LayerFF, T5LayerNorm
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ class T5EncoderBlock(nn.Module):
15
+ def __init__(self, config, has_relative_attention_bias=False):
16
+ super().__init__()
17
+ self.layer = nn.ModuleList()
18
+ self.layer.append(T5LayerSelfAttention(config, has_relative_attention_bias=has_relative_attention_bias))
19
+ self.layer.append(T5LayerFF(config))
20
+
21
+ def forward(
22
+ self,
23
+ hidden_states,
24
+ attention_mask=None,
25
+ position_bias=None,
26
+ layer_head_mask=None,
27
+ output_attentions=False,
28
+ ):
29
+ self_attn_past_key_value, cross_attn_past_key_value = None, None
30
+
31
+ self_attention_outputs = self.layer[0](
32
+ hidden_states,
33
+ attention_mask=attention_mask,
34
+ position_bias=position_bias,
35
+ layer_head_mask=layer_head_mask,
36
+ past_key_value=self_attn_past_key_value,
37
+ use_cache=False,
38
+ output_attentions=output_attentions,
39
+ )
40
+ hidden_states, present_key_value_state = self_attention_outputs[:2]
41
+ attention_outputs = self_attention_outputs[2:] # Keep self-attention outputs and relative position weights
42
+
43
+ # clamp inf values to enable fp16 training
44
+ if hidden_states.dtype == torch.float16:
45
+ clamp_value = torch.where(
46
+ torch.isinf(hidden_states).any(),
47
+ torch.finfo(hidden_states.dtype).max - 1000,
48
+ torch.finfo(hidden_states.dtype).max,
49
+ )
50
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
51
+
52
+ # Apply Feed Forward layer
53
+ hidden_states = self.layer[-1](hidden_states)
54
+
55
+ # clamp inf values to enable fp16 training
56
+ if hidden_states.dtype == torch.float16:
57
+ clamp_value = torch.where(
58
+ torch.isinf(hidden_states).any(),
59
+ torch.finfo(hidden_states.dtype).max - 1000,
60
+ torch.finfo(hidden_states.dtype).max,
61
+ )
62
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
63
+
64
+ outputs = (hidden_states,) + attention_outputs
65
+
66
+ return outputs # hidden-states, present_key_value_states, (self-attention position bias), (self-attention weights), (cross-attention position bias), (cross-attention weights)
67
+
68
+ class T5EncoderBlockByT5Mapper(ModelMixin):
69
+ def __init__(self, byt5_config, num_layers, sdxl_channels=None):
70
+ super().__init__()
71
+ if num_layers > 0:
72
+ self.blocks = nn.ModuleList(
73
+ [
74
+ T5EncoderBlock(
75
+ byt5_config,
76
+ has_relative_attention_bias=bool(i == 0))
77
+ for i in range(num_layers)
78
+ ]
79
+ )
80
+ else:
81
+ self.blocks = None
82
+ self.layer_norm = T5LayerNorm(byt5_config.d_model, eps=byt5_config.layer_norm_epsilon)
83
+ if sdxl_channels is not None:
84
+ self.channel_mapper = nn.Linear(byt5_config.d_model, sdxl_channels)
85
+ self.final_layer_norm = T5LayerNorm(sdxl_channels, eps=byt5_config.layer_norm_epsilon)
86
+ else:
87
+ self.channel_mapper = None
88
+ self.final_layer_norm = None
89
+
90
+ def get_extended_attention_mask(
91
+ self, attention_mask: Tensor, input_shape: Tuple[int], device: torch.device = None, dtype: torch.float = None
92
+ ) -> Tensor:
93
+ """
94
+ Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
95
+
96
+ Arguments:
97
+ attention_mask (`torch.Tensor`):
98
+ Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
99
+ input_shape (`Tuple[int]`):
100
+ The shape of the input to the model.
101
+
102
+ Returns:
103
+ `torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`.
104
+ """
105
+ if dtype is None:
106
+ dtype = self.dtype
107
+
108
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
109
+ # ourselves in which case we just need to make it broadcastable to all heads.
110
+ if attention_mask.dim() == 3:
111
+ extended_attention_mask = attention_mask[:, None, :, :]
112
+ elif attention_mask.dim() == 2:
113
+ # Provided a padding mask of dimensions [batch_size, seq_length]
114
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
115
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
116
+ extended_attention_mask = attention_mask[:, None, None, :]
117
+ else:
118
+ raise ValueError(
119
+ f"Wrong shape for input_ids (shape {input_shape}) or attention_mask (shape {attention_mask.shape})"
120
+ )
121
+
122
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
123
+ # masked positions, this operation will create a tensor which is 0.0 for
124
+ # positions we want to attend and the dtype's smallest value for masked positions.
125
+ # Since we are adding it to the raw scores before the softmax, this is
126
+ # effectively the same as removing these entirely.
127
+ extended_attention_mask = extended_attention_mask.to(dtype=dtype) # fp16 compatibility
128
+ extended_attention_mask = (1.0 - extended_attention_mask) * torch.finfo(dtype).min
129
+ return extended_attention_mask
130
+
131
+
132
+ def forward(self, inputs_embeds, attention_mask):
133
+ input_shape = inputs_embeds.size()[:-1]
134
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
135
+
136
+ hidden_states = inputs_embeds
137
+ position_bias = None
138
+
139
+ if self.blocks is not None:
140
+ for layer_module in self.blocks:
141
+ layer_outputs = layer_module(
142
+ hidden_states,
143
+ attention_mask=extended_attention_mask,
144
+ position_bias=position_bias,
145
+ )
146
+ hidden_states, position_bias = layer_outputs
147
+ hidden_states = self.layer_norm(hidden_states)
148
+ if self.channel_mapper is not None:
149
+ hidden_states = self.channel_mapper(hidden_states)
150
+ hidden_states = self.final_layer_norm(hidden_states)
151
+ return hidden_states
text_encoder/Glyph-SDXL-v2/glyph_sdxl/modules/simple_byt5_mapper.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusers import ModelMixin
2
+ import torch.nn as nn
3
+
4
+ class ByT5Mapper(ModelMixin):
5
+ def __init__(self, byt5_output_dim, sdxl_text_dim):
6
+ super().__init__()
7
+ self.mapper = nn.Sequential(
8
+ nn.LayerNorm(byt5_output_dim),
9
+ nn.Linear(byt5_output_dim, sdxl_text_dim),
10
+ nn.ReLU(),
11
+ nn.Linear(sdxl_text_dim, sdxl_text_dim)
12
+ )
13
+
14
+ def forward(self, byt5_embedding):
15
+ return self.mapper(byt5_embedding)
16
+
text_encoder/Glyph-SDXL-v2/glyph_sdxl/utils/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .parse_config import parse_config
2
+ from .constants import (
3
+ UNET_CKPT_NAME,
4
+ BYT5_CKPT_NAME,
5
+ BYT5_MAPPER_CKPT_NAME,
6
+ INSERTED_ATTN_CKPT_NAME,
7
+ huggingface_cache_dir,
8
+ )
9
+ from .load_pretrained_byt5 import load_byt5_and_byt5_tokenizer
10
+ from .format_prompt import PromptFormat, MultilingualPromptFormat
11
+
12
+ __all__ = [
13
+ 'parse_config',
14
+ 'UNET_CKPT_NAME',
15
+ 'BYT5_CKPT_NAME',
16
+ 'BYT5_MAPPER_CKPT_NAME',
17
+ 'huggingface_cache_dir',
18
+ 'load_byt5_and_byt5_tokenizer',
19
+ 'INSERTED_ATTN_CKPT_NAME',
20
+ 'PromptFormat',
21
+ 'MultilingualPromptFormat',
22
+ ]
23
+
text_encoder/Glyph-SDXL-v2/glyph_sdxl/utils/constants.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ UNET_CKPT_NAME = "unet_lora.pt"
2
+ INSERTED_ATTN_CKPT_NAME = "unet_inserted_attn.pt"
3
+ BYT5_CKPT_NAME = "byt5_model.pt"
4
+ BYT5_MAPPER_CKPT_NAME = "byt5_mapper.pt"
5
+ huggingface_cache_dir = None
text_encoder/Glyph-SDXL-v2/glyph_sdxl/utils/format_prompt.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import webcolors
3
+
4
+
5
+ def closest_color(requested_color):
6
+ min_colors = {}
7
+ for key, name in webcolors.CSS3_HEX_TO_NAMES.items():
8
+ r_c, g_c, b_c = webcolors.hex_to_rgb(key)
9
+ rd = (r_c - requested_color[0]) ** 2
10
+ gd = (g_c - requested_color[1]) ** 2
11
+ bd = (b_c - requested_color[2]) ** 2
12
+ min_colors[(rd + gd + bd)] = name
13
+ return min_colors[min(min_colors.keys())]
14
+
15
+ def convert_rgb_to_names(rgb_tuple):
16
+ try:
17
+ color_name = webcolors.rgb_to_name(rgb_tuple)
18
+ except ValueError:
19
+ color_name = closest_color(rgb_tuple)
20
+ return color_name
21
+
22
+ class PromptFormat():
23
+ def __init__(
24
+ self,
25
+ font_path: str = 'assets/font_idx_512.json',
26
+ color_path: str = 'assets/color_idx.json',
27
+ ):
28
+ with open(font_path, 'r') as f:
29
+ self.font_dict = json.load(f)
30
+ with open(color_path, 'r') as f:
31
+ self.color_dict = json.load(f)
32
+
33
+ def format_checker(self, texts, styles):
34
+ assert len(texts) == len(styles), 'length of texts must be equal to length of styles'
35
+ for style in styles:
36
+ assert style['font-family'] in self.font_dict, f"invalid font-family: {style['font-family']}"
37
+ rgb_color = webcolors.hex_to_rgb(style['color'])
38
+ color_name = convert_rgb_to_names(rgb_color)
39
+ assert color_name in self.color_dict, f"invalid color hex {color_name}"
40
+
41
+ def format_prompt(self, texts, styles):
42
+ self.format_checker(texts, styles)
43
+
44
+ prompt = ""
45
+ '''
46
+ Text "{text}" in {color}, {type}.
47
+ '''
48
+ for text, style in zip(texts, styles):
49
+ text_prompt = f'Text "{text}"'
50
+
51
+ attr_list = []
52
+
53
+ # format color
54
+ hex_color = style["color"]
55
+ rgb_color = webcolors.hex_to_rgb(hex_color)
56
+ color_name = convert_rgb_to_names(rgb_color)
57
+ attr_list.append(f"<color-{self.color_dict[color_name]}>")
58
+
59
+ # format font
60
+ attr_list.append(f"<font-{self.font_dict[style['font-family']]}>")
61
+ attr_suffix = ", ".join(attr_list)
62
+ text_prompt += " in " + attr_suffix
63
+ text_prompt += ". "
64
+
65
+ prompt = prompt + text_prompt
66
+ return prompt
67
+
68
+
69
+ class MultilingualPromptFormat():
70
+ def __init__(
71
+ self,
72
+ font_path: str = 'assets/multilingual_10-lang_idx.json',
73
+ color_path: str = 'assets/color_idx.json',
74
+ ):
75
+ with open(font_path, 'r') as f:
76
+ self.font_dict = json.load(f)
77
+ with open(color_path, 'r') as f:
78
+ self.color_dict = json.load(f)
79
+
80
+ def format_checker(self, texts, styles):
81
+ assert len(texts) == len(styles), 'length of texts must be equal to length of styles'
82
+ for style in styles:
83
+ assert style['font-family'] in self.font_dict, f"invalid font-family: {style['font-family']}"
84
+ rgb_color = webcolors.hex_to_rgb(style['color'])
85
+ color_name = convert_rgb_to_names(rgb_color)
86
+ assert color_name in self.color_dict, f"invalid color hex {color_name}"
87
+
88
+ def format_prompt(self, texts, styles):
89
+ self.format_checker(texts, styles)
90
+
91
+ prompt = ""
92
+ '''
93
+ Text "{text}" in {color}, {type}.
94
+ '''
95
+ for text, style in zip(texts, styles):
96
+ text_prompt = f'Text "{text}"'
97
+
98
+ attr_list = []
99
+
100
+ # format color
101
+ hex_color = style["color"]
102
+ rgb_color = webcolors.hex_to_rgb(hex_color)
103
+ color_name = convert_rgb_to_names(rgb_color)
104
+ attr_list.append(f"<color-{self.color_dict[color_name]}>")
105
+
106
+ # format font
107
+ attr_list.append(f"<{style['font-family'][:2]}-font-{self.font_dict[style['font-family']]}>")
108
+ attr_suffix = ", ".join(attr_list)
109
+ text_prompt += " in " + attr_suffix
110
+ text_prompt += ". "
111
+
112
+ prompt = prompt + text_prompt
113
+ return prompt
text_encoder/Glyph-SDXL-v2/glyph_sdxl/utils/load_pretrained_byt5.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ from transformers import AutoTokenizer, T5ForConditionalGeneration
4
+ from diffusers.utils import logging
5
+
6
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
7
+
8
+ def add_special_token(tokenizer, text_encoder, add_color, add_font, color_ann_path, font_ann_path, multilingual=False):
9
+ with open(font_ann_path, 'r') as f:
10
+ idx_font_dict = json.load(f)
11
+ with open(color_ann_path, 'r') as f:
12
+ idx_color_dict = json.load(f)
13
+
14
+ if multilingual:
15
+ font_token = []
16
+ for font_code in idx_font_dict:
17
+ prefix = font_code[:2]
18
+ font_token.append(f'<{prefix}-font-{idx_font_dict[font_code]}>')
19
+ else:
20
+ font_token = [f'<font-{i}>' for i in range(len(idx_font_dict))]
21
+ color_token = [f'<color-{i}>' for i in range(len(idx_color_dict))]
22
+ additional_special_tokens = []
23
+ if add_color:
24
+ additional_special_tokens += color_token
25
+ if add_font:
26
+ additional_special_tokens += font_token
27
+ tokenizer.add_tokens(additional_special_tokens, special_tokens=True)
28
+ text_encoder.resize_token_embeddings(len(tokenizer))
29
+
30
+ def load_byt5_and_byt5_tokenizer(
31
+ byt5_name='google/byt5-small',
32
+ special_token=False,
33
+ color_special_token=False,
34
+ font_special_token=False,
35
+ color_ann_path='assets/color_idx.json',
36
+ font_ann_path='assets/font_idx_512.json',
37
+ huggingface_cache_dir=None,
38
+ multilingual=False,
39
+ ):
40
+ byt5_tokenizer = AutoTokenizer.from_pretrained(
41
+ byt5_name, cache_dir=huggingface_cache_dir,
42
+ )
43
+ byt5_text_encoder = T5ForConditionalGeneration.from_pretrained(
44
+ byt5_name, cache_dir=huggingface_cache_dir,
45
+ ).get_encoder()
46
+
47
+ if special_token:
48
+ add_special_token(
49
+ byt5_tokenizer,
50
+ byt5_text_encoder,
51
+ add_color=color_special_token,
52
+ add_font=font_special_token,
53
+ color_ann_path=color_ann_path,
54
+ font_ann_path=font_ann_path,
55
+ multilingual=multilingual,
56
+ )
57
+
58
+ logger.info(f'Loaded original byt5 weight')
59
+
60
+ return byt5_text_encoder, byt5_tokenizer
text_encoder/Glyph-SDXL-v2/glyph_sdxl/utils/parse_config.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import os.path as osp
4
+ from mmengine.config import Config
5
+
6
+
7
+ def parse_config(path=None):
8
+ if path is None:
9
+ parser = argparse.ArgumentParser()
10
+ parser.add_argument('config_dir', type=str)
11
+ args = parser.parse_args()
12
+ path = args.config_dir
13
+ config = Config.fromfile(path)
14
+
15
+ config.config_dir = path
16
+
17
+ return config
text_encoder/byt5-small/flax_model.msgpack ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b3aafee96d60e98aa18b3c7f73a2c5a2360f1f2f6df79361190a4c9e05c5ab21
3
+ size 1198558445
text_encoder/byt5-small/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5c5aaf56299d6f2d4eaadad550a40765198828ead4d74f0a15f91cbe0961931a
3
+ size 1198627927
text_encoder/byt5-small/tf_model.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f97320dd5eb49cb2323a21d584cef7c1cfc9a0976efa978fcef438676b952bc2
3
+ size 1198900664
text_encoder/llm/model-00001-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e97b877e47fde53a6c6e77aafb36e58e91ee9d95c4a3eeac6f1b5c0e6a1c986e
3
+ size 3900233256
text_encoder/llm/model-00002-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a9a300a43b4724eee2abe7c18ceb26768d0ab011eb0cad19d9bfd2476a24d024
3
+ size 3864726320
text_encoder/llm/model-00003-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:111223d173e00bbee81cba1216fad28668df3476706b7fd26f4d5b50f8b3a507
3
+ size 3864726424
text_encoder/llm/model-00004-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef47f634fa57d46ee134edcc09f34085a47da1e16c12a2abe0d67118be6d72ed
3
+ size 3864733680
text_encoder/llm/model-00005-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0c859795ad3a627a9b95bcb762e059d5b768a4a36fdd4affeff269d93fdecc67
3
+ size 1089994880
transformer/1080p_sr_distilled/config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "HunyuanVideo_1_5_DiffusionTransformer",
3
+ "_diffusers_version": "0.35.0",
4
+ "attn_mode": "flash",
5
+ "attn_param": null,
6
+ "concat_condition": false,
7
+ "glyph_byT5_v2": true,
8
+ "guidance_embed": false,
9
+ "heads_num": 16,
10
+ "hidden_size": 2048,
11
+ "ideal_resolution": "1080p",
12
+ "ideal_task": null,
13
+ "in_channels": 98,
14
+ "is_reshape_temporal_channels": false,
15
+ "mlp_act_type": "gelu_tanh",
16
+ "mlp_width_ratio": 4,
17
+ "mm_double_blocks_depth": 54,
18
+ "mm_single_blocks_depth": 0,
19
+ "out_channels": 32,
20
+ "patch_size": [
21
+ 1,
22
+ 1,
23
+ 1
24
+ ],
25
+ "qk_norm": true,
26
+ "qk_norm_type": "rms",
27
+ "qkv_bias": true,
28
+ "rope_dim_list": [
29
+ 16,
30
+ 56,
31
+ 56
32
+ ],
33
+ "rope_theta": 256,
34
+ "text_pool_type": null,
35
+ "text_projection": "single_refiner",
36
+ "text_states_dim": 3584,
37
+ "text_states_dim_2": null,
38
+ "use_attention_mask": true,
39
+ "use_cond_type_embedding": true,
40
+ "use_meanflow": true,
41
+ "vision_projection": "linear",
42
+ "vision_states_dim": 1152
43
+ }
transformer/1080p_sr_distilled/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:691dc1b81b49d942e2eb95e6d61b91321e17b868536eaa4e843db6e406390411
3
+ size 33325793672
transformer/480p_i2v/config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "HunyuanVideo_1_5_DiffusionTransformer",
3
+ "_diffusers_version": "0.35.0",
4
+ "attn_mode": "flash",
5
+ "attn_param": null,
6
+ "concat_condition": true,
7
+ "glyph_byT5_v2": true,
8
+ "guidance_embed": false,
9
+ "heads_num": 16,
10
+ "hidden_size": 2048,
11
+ "ideal_resolution": "480p",
12
+ "ideal_task": "i2v",
13
+ "in_channels": 32,
14
+ "is_reshape_temporal_channels": false,
15
+ "mlp_act_type": "gelu_tanh",
16
+ "mlp_width_ratio": 4,
17
+ "mm_double_blocks_depth": 54,
18
+ "mm_single_blocks_depth": 0,
19
+ "out_channels": 32,
20
+ "patch_size": [
21
+ 1,
22
+ 1,
23
+ 1
24
+ ],
25
+ "qk_norm": true,
26
+ "qk_norm_type": "rms",
27
+ "qkv_bias": true,
28
+ "rope_dim_list": [
29
+ 16,
30
+ 56,
31
+ 56
32
+ ],
33
+ "rope_theta": 256,
34
+ "text_pool_type": null,
35
+ "text_projection": "single_refiner",
36
+ "text_states_dim": 3584,
37
+ "text_states_dim_2": null,
38
+ "use_attention_mask": true,
39
+ "use_cond_type_embedding": true,
40
+ "use_meanflow": false,
41
+ "vision_projection": "linear",
42
+ "vision_states_dim": 1152
43
+ }
transformer/480p_i2v/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f4d7d3e61404f5c742b57260f1b6a3bc41bb12fc880438252bf37913487dec56
3
+ size 33306632192
transformer/480p_i2v_distilled/config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "HunyuanVideo_1_5_DiffusionTransformer",
3
+ "_diffusers_version": "0.35.0",
4
+ "attn_mode": "flash",
5
+ "attn_param": null,
6
+ "concat_condition": true,
7
+ "glyph_byT5_v2": true,
8
+ "guidance_embed": false,
9
+ "heads_num": 16,
10
+ "hidden_size": 2048,
11
+ "ideal_resolution": "480p",
12
+ "ideal_task": "i2v",
13
+ "in_channels": 32,
14
+ "is_reshape_temporal_channels": false,
15
+ "mlp_act_type": "gelu_tanh",
16
+ "mlp_width_ratio": 4,
17
+ "mm_double_blocks_depth": 54,
18
+ "mm_single_blocks_depth": 0,
19
+ "out_channels": 32,
20
+ "patch_size": [
21
+ 1,
22
+ 1,
23
+ 1
24
+ ],
25
+ "qk_norm": true,
26
+ "qk_norm_type": "rms",
27
+ "qkv_bias": true,
28
+ "rope_dim_list": [
29
+ 16,
30
+ 56,
31
+ 56
32
+ ],
33
+ "rope_theta": 256,
34
+ "text_pool_type": null,
35
+ "text_projection": "single_refiner",
36
+ "text_states_dim": 3584,
37
+ "text_states_dim_2": null,
38
+ "use_attention_mask": true,
39
+ "use_cond_type_embedding": true,
40
+ "use_meanflow": false,
41
+ "vision_projection": "linear",
42
+ "vision_states_dim": 1152
43
+ }
transformer/480p_i2v_distilled/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f51fe1c4302be44e25afcd1a9186385606482da8a77e2ee7793b0e8385b9cd57
3
+ size 33306632192
transformer/480p_t2v/config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "HunyuanVideo_1_5_DiffusionTransformer",
3
+ "_diffusers_version": "0.35.0",
4
+ "attn_mode": "flash",
5
+ "attn_param": null,
6
+ "concat_condition": true,
7
+ "glyph_byT5_v2": true,
8
+ "guidance_embed": false,
9
+ "heads_num": 16,
10
+ "hidden_size": 2048,
11
+ "ideal_resolution": "480p",
12
+ "ideal_task": "t2v",
13
+ "in_channels": 32,
14
+ "is_reshape_temporal_channels": false,
15
+ "mlp_act_type": "gelu_tanh",
16
+ "mlp_width_ratio": 4,
17
+ "mm_double_blocks_depth": 54,
18
+ "mm_single_blocks_depth": 0,
19
+ "out_channels": 32,
20
+ "patch_size": [
21
+ 1,
22
+ 1,
23
+ 1
24
+ ],
25
+ "qk_norm": true,
26
+ "qk_norm_type": "rms",
27
+ "qkv_bias": true,
28
+ "rope_dim_list": [
29
+ 16,
30
+ 56,
31
+ 56
32
+ ],
33
+ "rope_theta": 256,
34
+ "text_pool_type": null,
35
+ "text_projection": "single_refiner",
36
+ "text_states_dim": 3584,
37
+ "text_states_dim_2": null,
38
+ "use_attention_mask": true,
39
+ "use_cond_type_embedding": true,
40
+ "use_meanflow": false,
41
+ "vision_projection": "linear",
42
+ "vision_states_dim": 1152
43
+ }
transformer/480p_t2v/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:71f9affa1115fef2b14bd41fba30eab966fe80c9ed98e0fcba495dbc6d8fff86
3
+ size 33306632192
transformer/480p_t2v_distilled/config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "HunyuanVideo_1_5_DiffusionTransformer",
3
+ "_diffusers_version": "0.35.0",
4
+ "attn_mode": "flash",
5
+ "attn_param": null,
6
+ "concat_condition": true,
7
+ "glyph_byT5_v2": true,
8
+ "guidance_embed": false,
9
+ "heads_num": 16,
10
+ "hidden_size": 2048,
11
+ "ideal_resolution": "480p",
12
+ "ideal_task": "t2v",
13
+ "in_channels": 32,
14
+ "is_reshape_temporal_channels": false,
15
+ "mlp_act_type": "gelu_tanh",
16
+ "mlp_width_ratio": 4,
17
+ "mm_double_blocks_depth": 54,
18
+ "mm_single_blocks_depth": 0,
19
+ "out_channels": 32,
20
+ "patch_size": [
21
+ 1,
22
+ 1,
23
+ 1
24
+ ],
25
+ "qk_norm": true,
26
+ "qk_norm_type": "rms",
27
+ "qkv_bias": true,
28
+ "rope_dim_list": [
29
+ 16,
30
+ 56,
31
+ 56
32
+ ],
33
+ "rope_theta": 256,
34
+ "text_pool_type": null,
35
+ "text_projection": "single_refiner",
36
+ "text_states_dim": 3584,
37
+ "text_states_dim_2": null,
38
+ "use_attention_mask": true,
39
+ "use_cond_type_embedding": true,
40
+ "use_meanflow": false,
41
+ "vision_projection": "linear",
42
+ "vision_states_dim": 1152
43
+ }
transformer/480p_t2v_distilled/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0f35dc10a4037a618b22fef4ee20f8a9d972b4cf2e684764ed8f442fc7a2583f
3
+ size 33306632192
transformer/720p_i2v/config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "HunyuanVideo_1_5_DiffusionTransformer",
3
+ "_diffusers_version": "0.35.0",
4
+ "attn_mode": "flash",
5
+ "attn_param": null,
6
+ "concat_condition": true,
7
+ "glyph_byT5_v2": true,
8
+ "guidance_embed": false,
9
+ "heads_num": 16,
10
+ "hidden_size": 2048,
11
+ "ideal_resolution": "720p",
12
+ "ideal_task": "i2v",
13
+ "in_channels": 32,
14
+ "is_reshape_temporal_channels": false,
15
+ "mlp_act_type": "gelu_tanh",
16
+ "mlp_width_ratio": 4,
17
+ "mm_double_blocks_depth": 54,
18
+ "mm_single_blocks_depth": 0,
19
+ "out_channels": 32,
20
+ "patch_size": [
21
+ 1,
22
+ 1,
23
+ 1
24
+ ],
25
+ "qk_norm": true,
26
+ "qk_norm_type": "rms",
27
+ "qkv_bias": true,
28
+ "rope_dim_list": [
29
+ 16,
30
+ 56,
31
+ 56
32
+ ],
33
+ "rope_theta": 256,
34
+ "text_pool_type": null,
35
+ "text_projection": "single_refiner",
36
+ "text_states_dim": 3584,
37
+ "text_states_dim_2": null,
38
+ "use_attention_mask": true,
39
+ "use_cond_type_embedding": true,
40
+ "use_meanflow": false,
41
+ "vision_projection": "linear",
42
+ "vision_states_dim": 1152
43
+ }
transformer/720p_i2v/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ffd6e2e1c2de585fd011ace1a64105804830aa331ddb25a2fb4a32497f159a4
3
+ size 33306632192
transformer/720p_i2v_distilled/config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "HunyuanVideo_1_5_DiffusionTransformer",
3
+ "_diffusers_version": "0.35.0",
4
+ "attn_mode": "flash",
5
+ "attn_param": null,
6
+ "concat_condition": true,
7
+ "glyph_byT5_v2": true,
8
+ "guidance_embed": false,
9
+ "heads_num": 16,
10
+ "hidden_size": 2048,
11
+ "ideal_resolution": "720p",
12
+ "ideal_task": "i2v",
13
+ "in_channels": 32,
14
+ "is_reshape_temporal_channels": false,
15
+ "mlp_act_type": "gelu_tanh",
16
+ "mlp_width_ratio": 4,
17
+ "mm_double_blocks_depth": 54,
18
+ "mm_single_blocks_depth": 0,
19
+ "out_channels": 32,
20
+ "patch_size": [
21
+ 1,
22
+ 1,
23
+ 1
24
+ ],
25
+ "qk_norm": true,
26
+ "qk_norm_type": "rms",
27
+ "qkv_bias": true,
28
+ "rope_dim_list": [
29
+ 16,
30
+ 56,
31
+ 56
32
+ ],
33
+ "rope_theta": 256,
34
+ "text_pool_type": null,
35
+ "text_projection": "single_refiner",
36
+ "text_states_dim": 3584,
37
+ "text_states_dim_2": null,
38
+ "use_attention_mask": true,
39
+ "use_cond_type_embedding": true,
40
+ "use_meanflow": false,
41
+ "vision_projection": "linear",
42
+ "vision_states_dim": 1152
43
+ }
transformer/720p_i2v_distilled/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:542a9a4367ebfe5c584d925308f63f11070d044e3615b07af95edd4e0500240a
3
+ size 33306632192
transformer/720p_i2v_distilled_sparse/config.json ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "HunyuanVideo_1_5_DiffusionTransformer",
3
+ "_diffusers_version": "0.35.0",
4
+ "attn_mode": "flex-block-attn",
5
+ "attn_param": {
6
+ "attn_mask_share_within_head": 0,
7
+ "attn_pad_type": "zero",
8
+ "attn_sparse_type": "ssta",
9
+ "attn_use_text_mask": 1,
10
+ "ssta_adaptive_pool": null,
11
+ "ssta_lambda": 0.7,
12
+ "ssta_sampling_type": "importance",
13
+ "ssta_threshold": 0.0,
14
+ "ssta_topk": 64,
15
+ "tile_size": [
16
+ 6,
17
+ 8,
18
+ 8
19
+ ],
20
+ "win_ratio": 10,
21
+ "win_size": [
22
+ [
23
+ 3,
24
+ 3,
25
+ 3
26
+ ]
27
+ ],
28
+ "win_type": "fixed"
29
+ },
30
+ "concat_condition": true,
31
+ "glyph_byT5_v2": true,
32
+ "guidance_embed": false,
33
+ "heads_num": 16,
34
+ "hidden_size": 2048,
35
+ "ideal_resolution": "720p",
36
+ "ideal_task": "i2v",
37
+ "in_channels": 32,
38
+ "is_reshape_temporal_channels": false,
39
+ "mlp_act_type": "gelu_tanh",
40
+ "mlp_width_ratio": 4,
41
+ "mm_double_blocks_depth": 54,
42
+ "mm_single_blocks_depth": 0,
43
+ "out_channels": 32,
44
+ "patch_size": [
45
+ 1,
46
+ 1,
47
+ 1
48
+ ],
49
+ "qk_norm": true,
50
+ "qk_norm_type": "rms",
51
+ "qkv_bias": true,
52
+ "rope_dim_list": [
53
+ 16,
54
+ 56,
55
+ 56
56
+ ],
57
+ "rope_theta": 256,
58
+ "text_pool_type": null,
59
+ "text_projection": "single_refiner",
60
+ "text_states_dim": 3584,
61
+ "text_states_dim_2": null,
62
+ "use_attention_mask": true,
63
+ "use_cond_type_embedding": true,
64
+ "use_meanflow": false,
65
+ "vision_projection": "linear",
66
+ "vision_states_dim": 1152
67
+ }
transformer/720p_i2v_distilled_sparse/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:47345844cc15df1e64a38cc9715fa31471c2c1c68a2857404eda027d60f355a6
3
+ size 33306632192
transformer/720p_sr_distilled/config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "HunyuanVideo_1_5_DiffusionTransformer",
3
+ "_diffusers_version": "0.35.0",
4
+ "attn_mode": "flash",
5
+ "attn_param": null,
6
+ "concat_condition": false,
7
+ "glyph_byT5_v2": true,
8
+ "guidance_embed": false,
9
+ "heads_num": 16,
10
+ "hidden_size": 2048,
11
+ "ideal_resolution": "720p",
12
+ "ideal_task": null,
13
+ "in_channels": 98,
14
+ "is_reshape_temporal_channels": false,
15
+ "mlp_act_type": "gelu_tanh",
16
+ "mlp_width_ratio": 4,
17
+ "mm_double_blocks_depth": 54,
18
+ "mm_single_blocks_depth": 0,
19
+ "out_channels": 32,
20
+ "patch_size": [
21
+ 1,
22
+ 1,
23
+ 1
24
+ ],
25
+ "qk_norm": true,
26
+ "qk_norm_type": "rms",
27
+ "qkv_bias": true,
28
+ "rope_dim_list": [
29
+ 16,
30
+ 56,
31
+ 56
32
+ ],
33
+ "rope_theta": 256,
34
+ "text_pool_type": null,
35
+ "text_projection": "single_refiner",
36
+ "text_states_dim": 3584,
37
+ "text_states_dim_2": null,
38
+ "use_attention_mask": true,
39
+ "use_cond_type_embedding": true,
40
+ "use_meanflow": true,
41
+ "vision_projection": "linear",
42
+ "vision_states_dim": 1152
43
+ }
transformer/720p_sr_distilled/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8fcab24a2404731a5e42d5f4adf7731a69771a3b2fc7786f90233f599947794a
3
+ size 33325793672
transformer/720p_t2v/config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "HunyuanVideo_1_5_DiffusionTransformer",
3
+ "_diffusers_version": "0.35.0",
4
+ "attn_mode": "flash",
5
+ "attn_param": null,
6
+ "concat_condition": true,
7
+ "glyph_byT5_v2": true,
8
+ "guidance_embed": false,
9
+ "heads_num": 16,
10
+ "hidden_size": 2048,
11
+ "ideal_resolution": "720p",
12
+ "ideal_task": "t2v",
13
+ "in_channels": 32,
14
+ "is_reshape_temporal_channels": false,
15
+ "mlp_act_type": "gelu_tanh",
16
+ "mlp_width_ratio": 4,
17
+ "mm_double_blocks_depth": 54,
18
+ "mm_single_blocks_depth": 0,
19
+ "out_channels": 32,
20
+ "patch_size": [
21
+ 1,
22
+ 1,
23
+ 1
24
+ ],
25
+ "qk_norm": true,
26
+ "qk_norm_type": "rms",
27
+ "qkv_bias": true,
28
+ "rope_dim_list": [
29
+ 16,
30
+ 56,
31
+ 56
32
+ ],
33
+ "rope_theta": 256,
34
+ "text_pool_type": null,
35
+ "text_projection": "single_refiner",
36
+ "text_states_dim": 3584,
37
+ "text_states_dim_2": null,
38
+ "use_attention_mask": true,
39
+ "use_cond_type_embedding": true,
40
+ "use_meanflow": false,
41
+ "vision_projection": "linear",
42
+ "vision_states_dim": 1152
43
+ }
transformer/720p_t2v/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:acb0a23ccd0b6c662a22bcc9783544fd917418227a5bdf5e2cbecb22a142c3cc
3
+ size 33306632192