jbilcke-hf HF Staff commited on
Commit
fa8e04c
·
verified ·
1 Parent(s): 0a515a6

Upload 30 files

Browse files
hyvideo/__init__.py ADDED
File without changes
hyvideo/config.py ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from .constants import *
3
+ import re
4
+ from .modules.models import HUNYUAN_VIDEO_CONFIG
5
+
6
+
7
+ def parse_args(namespace=None):
8
+ parser = argparse.ArgumentParser(description="HunyuanVideo inference script")
9
+
10
+ parser = add_network_args(parser)
11
+ parser = add_extra_models_args(parser)
12
+ parser = add_denoise_schedule_args(parser)
13
+ parser = add_inference_args(parser)
14
+ parser = add_parallel_args(parser)
15
+
16
+ args = parser.parse_args(namespace=namespace)
17
+ args = sanity_check_args(args)
18
+
19
+ return args
20
+
21
+
22
+ def add_network_args(parser: argparse.ArgumentParser):
23
+ group = parser.add_argument_group(title="HunyuanVideo network args")
24
+
25
+
26
+ group.add_argument(
27
+ "--quantize-transformer",
28
+ action="store_true",
29
+ help="On the fly 'transformer' quantization"
30
+ )
31
+
32
+
33
+ group.add_argument(
34
+ "--lora-dir-i2v",
35
+ type=str,
36
+ default="loras_i2v",
37
+ help="Path to a directory that contains Loras for i2v"
38
+ )
39
+
40
+ group.add_argument(
41
+ "--lora-weight-i2v",
42
+ nargs='+',
43
+ default=[],
44
+ help="List of individual Lora files paths for i2v"
45
+ )
46
+
47
+ group.add_argument(
48
+ "--lora-multiplier-i2v",
49
+ nargs='+',
50
+ default=[],
51
+ help="List of Lora multipliers for i2v"
52
+ )
53
+
54
+
55
+ group.add_argument(
56
+ "--lora-dir",
57
+ type=str,
58
+ default="loras",
59
+ help="Path to a directory that contains Loras"
60
+ )
61
+
62
+ group.add_argument(
63
+ "--lora-weight",
64
+ nargs='+',
65
+ default=[],
66
+ help="List of individual Lora files paths"
67
+ )
68
+
69
+ group.add_argument(
70
+ "--lora-multiplier",
71
+ nargs='+',
72
+ default=[],
73
+ help="List of Lora multipliers"
74
+ )
75
+
76
+ group.add_argument(
77
+ "--profile",
78
+ type=str,
79
+ default=-1,
80
+ help="Profile No"
81
+ )
82
+
83
+ group.add_argument(
84
+ "--verbose",
85
+ type=str,
86
+ default=1,
87
+ help="Verbose level"
88
+ )
89
+
90
+ group.add_argument(
91
+ "--server-port",
92
+ type=str,
93
+ default=0,
94
+ help="Server port"
95
+ )
96
+
97
+ group.add_argument(
98
+ "--server-name",
99
+ type=str,
100
+ default="",
101
+ help="Server name"
102
+ )
103
+
104
+ group.add_argument(
105
+ "--open-browser",
106
+ action="store_true",
107
+ help="open browser"
108
+ )
109
+
110
+ group.add_argument(
111
+ "--t2v",
112
+ action="store_true",
113
+ help="text to video mode"
114
+ )
115
+
116
+ group.add_argument(
117
+ "--i2v",
118
+ action="store_true",
119
+ help="image to video mode"
120
+ )
121
+
122
+ group.add_argument(
123
+ "--compile",
124
+ action="store_true",
125
+ help="Enable pytorch compilation"
126
+ )
127
+
128
+ group.add_argument(
129
+ "--fast",
130
+ action="store_true",
131
+ help="use Fast HunyuanVideo model"
132
+ )
133
+
134
+ group.add_argument(
135
+ "--fastest",
136
+ action="store_true",
137
+ help="activate the best config"
138
+ )
139
+
140
+ group.add_argument(
141
+ "--attention",
142
+ type=str,
143
+ default="",
144
+ help="attention mode"
145
+ )
146
+
147
+ group.add_argument(
148
+ "--vae-config",
149
+ type=str,
150
+ default="",
151
+ help="vae config mode"
152
+ )
153
+ # Main model
154
+ group.add_argument(
155
+ "--model",
156
+ type=str,
157
+ choices=list(HUNYUAN_VIDEO_CONFIG.keys()),
158
+ default="HYVideo-T/2-cfgdistill",
159
+ )
160
+ group.add_argument(
161
+ "--latent-channels",
162
+ type=str,
163
+ default=16,
164
+ help="Number of latent channels of DiT. If None, it will be determined by `vae`. If provided, "
165
+ "it still needs to match the latent channels of the VAE model.",
166
+ )
167
+ group.add_argument(
168
+ "--precision",
169
+ type=str,
170
+ default="bf16",
171
+ choices=PRECISIONS,
172
+ help="Precision mode. Options: fp32, fp16, bf16. Applied to the backbone model and optimizer.",
173
+ )
174
+
175
+ # RoPE
176
+ group.add_argument(
177
+ "--rope-theta", type=int, default=256, help="Theta used in RoPE."
178
+ )
179
+ return parser
180
+
181
+
182
+ def add_extra_models_args(parser: argparse.ArgumentParser):
183
+ group = parser.add_argument_group(
184
+ title="Extra models args, including vae, text encoders and tokenizers)"
185
+ )
186
+
187
+ # - VAE
188
+ group.add_argument(
189
+ "--vae",
190
+ type=str,
191
+ default="884-16c-hy",
192
+ choices=list(VAE_PATH),
193
+ help="Name of the VAE model.",
194
+ )
195
+ group.add_argument(
196
+ "--vae-precision",
197
+ type=str,
198
+ default="fp16",
199
+ choices=PRECISIONS,
200
+ help="Precision mode for the VAE model.",
201
+ )
202
+ group.add_argument(
203
+ "--vae-tiling",
204
+ action="store_true",
205
+ help="Enable tiling for the VAE model to save GPU memory.",
206
+ )
207
+ group.set_defaults(vae_tiling=True)
208
+
209
+ group.add_argument(
210
+ "--text-encoder",
211
+ type=str,
212
+ default="llm",
213
+ choices=list(TEXT_ENCODER_PATH),
214
+ help="Name of the text encoder model.",
215
+ )
216
+ group.add_argument(
217
+ "--text-encoder-precision",
218
+ type=str,
219
+ default="fp16",
220
+ choices=PRECISIONS,
221
+ help="Precision mode for the text encoder model.",
222
+ )
223
+ group.add_argument(
224
+ "--text-states-dim",
225
+ type=int,
226
+ default=4096,
227
+ help="Dimension of the text encoder hidden states.",
228
+ )
229
+ group.add_argument(
230
+ "--text-len", type=int, default=256, help="Maximum length of the text input."
231
+ )
232
+ group.add_argument(
233
+ "--tokenizer",
234
+ type=str,
235
+ default="llm",
236
+ choices=list(TOKENIZER_PATH),
237
+ help="Name of the tokenizer model.",
238
+ )
239
+ group.add_argument(
240
+ "--prompt-template",
241
+ type=str,
242
+ default="dit-llm-encode",
243
+ choices=PROMPT_TEMPLATE,
244
+ help="Image prompt template for the decoder-only text encoder model.",
245
+ )
246
+ group.add_argument(
247
+ "--prompt-template-video",
248
+ type=str,
249
+ default="dit-llm-encode-video",
250
+ choices=PROMPT_TEMPLATE,
251
+ help="Video prompt template for the decoder-only text encoder model.",
252
+ )
253
+ group.add_argument(
254
+ "--hidden-state-skip-layer",
255
+ type=int,
256
+ default=2,
257
+ help="Skip layer for hidden states.",
258
+ )
259
+ group.add_argument(
260
+ "--apply-final-norm",
261
+ action="store_true",
262
+ help="Apply final normalization to the used text encoder hidden states.",
263
+ )
264
+
265
+ # - CLIP
266
+ group.add_argument(
267
+ "--text-encoder-2",
268
+ type=str,
269
+ default="clipL",
270
+ choices=list(TEXT_ENCODER_PATH),
271
+ help="Name of the second text encoder model.",
272
+ )
273
+ group.add_argument(
274
+ "--text-encoder-precision-2",
275
+ type=str,
276
+ default="fp16",
277
+ choices=PRECISIONS,
278
+ help="Precision mode for the second text encoder model.",
279
+ )
280
+ group.add_argument(
281
+ "--text-states-dim-2",
282
+ type=int,
283
+ default=768,
284
+ help="Dimension of the second text encoder hidden states.",
285
+ )
286
+ group.add_argument(
287
+ "--tokenizer-2",
288
+ type=str,
289
+ default="clipL",
290
+ choices=list(TOKENIZER_PATH),
291
+ help="Name of the second tokenizer model.",
292
+ )
293
+ group.add_argument(
294
+ "--text-len-2",
295
+ type=int,
296
+ default=77,
297
+ help="Maximum length of the second text input.",
298
+ )
299
+
300
+ return parser
301
+
302
+
303
+ def add_denoise_schedule_args(parser: argparse.ArgumentParser):
304
+ group = parser.add_argument_group(title="Denoise schedule args")
305
+
306
+ group.add_argument(
307
+ "--denoise-type",
308
+ type=str,
309
+ default="flow",
310
+ help="Denoise type for noised inputs.",
311
+ )
312
+
313
+ # Flow Matching
314
+ group.add_argument(
315
+ "--flow-shift",
316
+ type=float,
317
+ default=7.0,
318
+ help="Shift factor for flow matching schedulers.",
319
+ )
320
+ group.add_argument(
321
+ "--flow-reverse",
322
+ action="store_true",
323
+ help="If reverse, learning/sampling from t=1 -> t=0.",
324
+ )
325
+ group.add_argument(
326
+ "--flow-solver",
327
+ type=str,
328
+ default="euler",
329
+ help="Solver for flow matching.",
330
+ )
331
+ group.add_argument(
332
+ "--use-linear-quadratic-schedule",
333
+ action="store_true",
334
+ help="Use linear quadratic schedule for flow matching."
335
+ "Following MovieGen (https://ai.meta.com/static-resource/movie-gen-research-paper)",
336
+ )
337
+ group.add_argument(
338
+ "--linear-schedule-end",
339
+ type=int,
340
+ default=25,
341
+ help="End step for linear quadratic schedule for flow matching.",
342
+ )
343
+
344
+ return parser
345
+
346
+
347
+ def add_inference_args(parser: argparse.ArgumentParser):
348
+ group = parser.add_argument_group(title="Inference args")
349
+
350
+ # ======================== Model loads ========================
351
+ group.add_argument(
352
+ "--model-base",
353
+ type=str,
354
+ default="ckpts",
355
+ help="Root path of all the models, including t2v models and extra models.",
356
+ )
357
+ group.add_argument(
358
+ "--dit-weight",
359
+ type=str,
360
+ default="ckpts/hunyuan-video-t2v-720p/transformers/mp_rank_00_model_states.pt",
361
+ help="Path to the HunyuanVideo model. If None, search the model in the args.model_root."
362
+ "1. If it is a file, load the model directly."
363
+ "2. If it is a directory, search the model in the directory. Support two types of models: "
364
+ "1) named `pytorch_model_*.pt`"
365
+ "2) named `*_model_states.pt`, where * can be `mp_rank_00`.",
366
+ )
367
+ group.add_argument(
368
+ "--model-resolution",
369
+ type=str,
370
+ default="540p",
371
+ choices=["540p", "720p"],
372
+ help="Root path of all the models, including t2v models and extra models.",
373
+ )
374
+ group.add_argument(
375
+ "--load-key",
376
+ type=str,
377
+ default="module",
378
+ help="Key to load the model states. 'module' for the main model, 'ema' for the EMA model.",
379
+ )
380
+ group.add_argument(
381
+ "--use-cpu-offload",
382
+ action="store_true",
383
+ help="Use CPU offload for the model load.",
384
+ )
385
+
386
+ # ======================== Inference general setting ========================
387
+ group.add_argument(
388
+ "--batch-size",
389
+ type=int,
390
+ default=1,
391
+ help="Batch size for inference and evaluation.",
392
+ )
393
+ group.add_argument(
394
+ "--infer-steps",
395
+ type=int,
396
+ default=50,
397
+ help="Number of denoising steps for inference.",
398
+ )
399
+ group.add_argument(
400
+ "--disable-autocast",
401
+ action="store_true",
402
+ help="Disable autocast for denoising loop and vae decoding in pipeline sampling.",
403
+ )
404
+ group.add_argument(
405
+ "--save-path",
406
+ type=str,
407
+ default="./results",
408
+ help="Path to save the generated samples.",
409
+ )
410
+ group.add_argument(
411
+ "--save-path-suffix",
412
+ type=str,
413
+ default="",
414
+ help="Suffix for the directory of saved samples.",
415
+ )
416
+ group.add_argument(
417
+ "--name-suffix",
418
+ type=str,
419
+ default="",
420
+ help="Suffix for the names of saved samples.",
421
+ )
422
+ group.add_argument(
423
+ "--num-videos",
424
+ type=int,
425
+ default=1,
426
+ help="Number of videos to generate for each prompt.",
427
+ )
428
+ # ---sample size---
429
+ group.add_argument(
430
+ "--video-size",
431
+ type=int,
432
+ nargs="+",
433
+ default=(720, 1280),
434
+ help="Video size for training. If a single value is provided, it will be used for both height "
435
+ "and width. If two values are provided, they will be used for height and width "
436
+ "respectively.",
437
+ )
438
+ group.add_argument(
439
+ "--video-length",
440
+ type=int,
441
+ default=129,
442
+ help="How many frames to sample from a video. if using 3d vae, the number should be 4n+1",
443
+ )
444
+ # --- prompt ---
445
+ group.add_argument(
446
+ "--prompt",
447
+ type=str,
448
+ default=None,
449
+ help="Prompt for sampling during evaluation.",
450
+ )
451
+ group.add_argument(
452
+ "--seed-type",
453
+ type=str,
454
+ default="auto",
455
+ choices=["file", "random", "fixed", "auto"],
456
+ help="Seed type for evaluation. If file, use the seed from the CSV file. If random, generate a "
457
+ "random seed. If fixed, use the fixed seed given by `--seed`. If auto, `csv` will use the "
458
+ "seed column if available, otherwise use the fixed `seed` value. `prompt` will use the "
459
+ "fixed `seed` value.",
460
+ )
461
+ group.add_argument("--seed", type=int, default=None, help="Seed for evaluation.")
462
+
463
+ # Classifier-Free Guidance
464
+ group.add_argument(
465
+ "--neg-prompt", type=str, default=None, help="Negative prompt for sampling."
466
+ )
467
+ group.add_argument(
468
+ "--cfg-scale", type=float, default=1.0, help="Classifier free guidance scale."
469
+ )
470
+ group.add_argument(
471
+ "--embedded-cfg-scale",
472
+ type=float,
473
+ default=6.0,
474
+ help="Embeded classifier free guidance scale.",
475
+ )
476
+
477
+ group.add_argument(
478
+ "--reproduce",
479
+ action="store_true",
480
+ help="Enable reproducibility by setting random seeds and deterministic algorithms.",
481
+ )
482
+
483
+ return parser
484
+
485
+
486
+ def add_parallel_args(parser: argparse.ArgumentParser):
487
+ group = parser.add_argument_group(title="Parallel args")
488
+
489
+ # ======================== Model loads ========================
490
+ group.add_argument(
491
+ "--ulysses-degree",
492
+ type=int,
493
+ default=1,
494
+ help="Ulysses degree.",
495
+ )
496
+ group.add_argument(
497
+ "--ring-degree",
498
+ type=int,
499
+ default=1,
500
+ help="Ulysses degree.",
501
+ )
502
+
503
+ return parser
504
+
505
+
506
+ def sanity_check_args(args):
507
+ # VAE channels
508
+ vae_pattern = r"\d{2,3}-\d{1,2}c-\w+"
509
+ if not re.match(vae_pattern, args.vae):
510
+ raise ValueError(
511
+ f"Invalid VAE model: {args.vae}. Must be in the format of '{vae_pattern}'."
512
+ )
513
+ vae_channels = int(args.vae.split("-")[1][:-1])
514
+ if args.latent_channels is None:
515
+ args.latent_channels = vae_channels
516
+ if vae_channels != args.latent_channels:
517
+ raise ValueError(
518
+ f"Latent channels ({args.latent_channels}) must match the VAE channels ({vae_channels})."
519
+ )
520
+ return args
hyvideo/constants.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+
4
+ __all__ = [
5
+ "C_SCALE",
6
+ "PROMPT_TEMPLATE",
7
+ "MODEL_BASE",
8
+ "PRECISIONS",
9
+ "NORMALIZATION_TYPE",
10
+ "ACTIVATION_TYPE",
11
+ "VAE_PATH",
12
+ "TEXT_ENCODER_PATH",
13
+ "TOKENIZER_PATH",
14
+ "TEXT_PROJECTION",
15
+ "DATA_TYPE",
16
+ "NEGATIVE_PROMPT",
17
+ ]
18
+
19
+ PRECISION_TO_TYPE = {
20
+ 'fp32': torch.float32,
21
+ 'fp16': torch.float16,
22
+ 'bf16': torch.bfloat16,
23
+ }
24
+
25
+ # =================== Constant Values =====================
26
+ # Computation scale factor, 1P = 1_000_000_000_000_000. Tensorboard will display the value in PetaFLOPS to avoid
27
+ # overflow error when tensorboard logging values.
28
+ C_SCALE = 1_000_000_000_000_000
29
+
30
+ # When using decoder-only models, we must provide a prompt template to instruct the text encoder
31
+ # on how to generate the text.
32
+ # --------------------------------------------------------------------
33
+ PROMPT_TEMPLATE_ENCODE = (
34
+ "<|start_header_id|>system<|end_header_id|>\n\nDescribe the image by detailing the color, shape, size, texture, "
35
+ "quantity, text, spatial relationships of the objects and background:<|eot_id|>"
36
+ "<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>"
37
+ )
38
+ PROMPT_TEMPLATE_ENCODE_VIDEO = (
39
+ "<|start_header_id|>system<|end_header_id|>\n\nDescribe the video by detailing the following aspects: "
40
+ "1. The main content and theme of the video."
41
+ "2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects."
42
+ "3. Actions, events, behaviors temporal relationships, physical movement changes of the objects."
43
+ "4. background environment, light, style and atmosphere."
44
+ "5. camera angles, movements, and transitions used in the video:<|eot_id|>"
45
+ "<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>"
46
+ )
47
+
48
+ NEGATIVE_PROMPT = "Aerial view, aerial view, overexposed, low quality, deformation, a poor composition, bad hands, bad teeth, bad eyes, bad limbs, distortion"
49
+
50
+ PROMPT_TEMPLATE = {
51
+ "dit-llm-encode": {
52
+ "template": PROMPT_TEMPLATE_ENCODE,
53
+ "crop_start": 36,
54
+ },
55
+ "dit-llm-encode-video": {
56
+ "template": PROMPT_TEMPLATE_ENCODE_VIDEO,
57
+ "crop_start": 95,
58
+ },
59
+ }
60
+
61
+ # ======================= Model ======================
62
+ PRECISIONS = {"fp32", "fp16", "bf16"}
63
+ NORMALIZATION_TYPE = {"layer", "rms"}
64
+ ACTIVATION_TYPE = {"relu", "silu", "gelu", "gelu_tanh"}
65
+
66
+ # =================== Model Path =====================
67
+ MODEL_BASE = os.getenv("MODEL_BASE", "./ckpts")
68
+
69
+ # =================== Data =======================
70
+ DATA_TYPE = {"image", "video", "image_video"}
71
+
72
+ # 3D VAE
73
+ VAE_PATH = {"884-16c-hy": f"{MODEL_BASE}/hunyuan-video-t2v-720p/vae"}
74
+
75
+ # Text Encoder
76
+ TEXT_ENCODER_PATH = {
77
+ "clipL": f"{MODEL_BASE}/text_encoder_2",
78
+ "llm": f"{MODEL_BASE}/text_encoder",
79
+ }
80
+
81
+ # Tokenizer
82
+ TOKENIZER_PATH = {
83
+ "clipL": f"{MODEL_BASE}/text_encoder_2",
84
+ "llm": f"{MODEL_BASE}/text_encoder",
85
+ }
86
+
87
+ TEXT_PROJECTION = {
88
+ "linear", # Default, an nn.Linear() layer
89
+ "single_refiner", # Single TokenRefiner. Refer to LI-DiT
90
+ }
hyvideo/diffusion/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .pipelines import HunyuanVideoPipeline
2
+ from .schedulers import FlowMatchDiscreteScheduler
hyvideo/diffusion/pipelines/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .pipeline_hunyuan_video import HunyuanVideoPipeline
hyvideo/diffusion/pipelines/pipeline_hunyuan_video.py ADDED
@@ -0,0 +1,1131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ #
16
+ # Modified from diffusers==0.29.2
17
+ #
18
+ # ==============================================================================
19
+ import inspect
20
+ from typing import Any, Callable, Dict, List, Optional, Union, Tuple
21
+ import torch
22
+ import torch.distributed as dist
23
+ import numpy as np
24
+ from dataclasses import dataclass
25
+ from packaging import version
26
+
27
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
28
+ from diffusers.configuration_utils import FrozenDict
29
+ from diffusers.image_processor import VaeImageProcessor
30
+ from diffusers.loaders import LoraLoaderMixin, TextualInversionLoaderMixin
31
+ from diffusers.models import AutoencoderKL
32
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
33
+ from diffusers.schedulers import KarrasDiffusionSchedulers
34
+ from diffusers.utils import (
35
+ USE_PEFT_BACKEND,
36
+ deprecate,
37
+ logging,
38
+ replace_example_docstring,
39
+ scale_lora_layers,
40
+ unscale_lora_layers,
41
+ )
42
+ from diffusers.utils.torch_utils import randn_tensor
43
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
44
+ from diffusers.utils import BaseOutput
45
+
46
+ from ...constants import PRECISION_TO_TYPE
47
+ from ...vae.autoencoder_kl_causal_3d import AutoencoderKLCausal3D
48
+ from ...text_encoder import TextEncoder
49
+ from ...modules import HYVideoDiffusionTransformer
50
+ from mmgp import offload
51
+
52
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
53
+
54
+ EXAMPLE_DOC_STRING = """"""
55
+
56
+
57
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
58
+ """
59
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
60
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
61
+ """
62
+ std_text = noise_pred_text.std(
63
+ dim=list(range(1, noise_pred_text.ndim)), keepdim=True
64
+ )
65
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
66
+ # rescale the results from guidance (fixes overexposure)
67
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
68
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
69
+ noise_cfg = (
70
+ guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
71
+ )
72
+ return noise_cfg
73
+
74
+
75
+ def retrieve_timesteps(
76
+ scheduler,
77
+ num_inference_steps: Optional[int] = None,
78
+ device: Optional[Union[str, torch.device]] = None,
79
+ timesteps: Optional[List[int]] = None,
80
+ sigmas: Optional[List[float]] = None,
81
+ **kwargs,
82
+ ):
83
+ """
84
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
85
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
86
+
87
+ Args:
88
+ scheduler (`SchedulerMixin`):
89
+ The scheduler to get timesteps from.
90
+ num_inference_steps (`int`):
91
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
92
+ must be `None`.
93
+ device (`str` or `torch.device`, *optional*):
94
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
95
+ timesteps (`List[int]`, *optional*):
96
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
97
+ `num_inference_steps` and `sigmas` must be `None`.
98
+ sigmas (`List[float]`, *optional*):
99
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
100
+ `num_inference_steps` and `timesteps` must be `None`.
101
+
102
+ Returns:
103
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
104
+ second element is the number of inference steps.
105
+ """
106
+ if timesteps is not None and sigmas is not None:
107
+ raise ValueError(
108
+ "Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values"
109
+ )
110
+ if timesteps is not None:
111
+ accepts_timesteps = "timesteps" in set(
112
+ inspect.signature(scheduler.set_timesteps).parameters.keys()
113
+ )
114
+ if not accepts_timesteps:
115
+ raise ValueError(
116
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
117
+ f" timestep schedules. Please check whether you are using the correct scheduler."
118
+ )
119
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
120
+ timesteps = scheduler.timesteps
121
+ num_inference_steps = len(timesteps)
122
+ elif sigmas is not None:
123
+ accept_sigmas = "sigmas" in set(
124
+ inspect.signature(scheduler.set_timesteps).parameters.keys()
125
+ )
126
+ if not accept_sigmas:
127
+ raise ValueError(
128
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
129
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
130
+ )
131
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
132
+ timesteps = scheduler.timesteps
133
+ num_inference_steps = len(timesteps)
134
+ else:
135
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
136
+ timesteps = scheduler.timesteps
137
+ return timesteps, num_inference_steps
138
+
139
+
140
+ @dataclass
141
+ class HunyuanVideoPipelineOutput(BaseOutput):
142
+ videos: Union[torch.Tensor, np.ndarray]
143
+
144
+
145
+ class HunyuanVideoPipeline(DiffusionPipeline):
146
+ r"""
147
+ Pipeline for text-to-video generation using HunyuanVideo.
148
+
149
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
150
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
151
+
152
+ Args:
153
+ vae ([`AutoencoderKL`]):
154
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
155
+ text_encoder ([`TextEncoder`]):
156
+ Frozen text-encoder.
157
+ text_encoder_2 ([`TextEncoder`]):
158
+ Frozen text-encoder_2.
159
+ transformer ([`HYVideoDiffusionTransformer`]):
160
+ A `HYVideoDiffusionTransformer` to denoise the encoded video latents.
161
+ scheduler ([`SchedulerMixin`]):
162
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents.
163
+ """
164
+
165
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
166
+ _optional_components = ["text_encoder_2"]
167
+ _exclude_from_cpu_offload = ["transformer"]
168
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
169
+
170
+ def __init__(
171
+ self,
172
+ vae: AutoencoderKL,
173
+ text_encoder: TextEncoder,
174
+ transformer: HYVideoDiffusionTransformer,
175
+ scheduler: KarrasDiffusionSchedulers,
176
+ text_encoder_2: Optional[TextEncoder] = None,
177
+ progress_bar_config: Dict[str, Any] = None,
178
+ args=None,
179
+ ):
180
+ super().__init__()
181
+
182
+ # ==========================================================================================
183
+ if progress_bar_config is None:
184
+ progress_bar_config = {}
185
+ if not hasattr(self, "_progress_bar_config"):
186
+ self._progress_bar_config = {}
187
+ self._progress_bar_config.update(progress_bar_config)
188
+
189
+ self.args = args
190
+ # ==========================================================================================
191
+
192
+ if (
193
+ hasattr(scheduler.config, "steps_offset")
194
+ and scheduler.config.steps_offset != 1
195
+ ):
196
+ deprecation_message = (
197
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
198
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
199
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
200
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
201
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
202
+ " file"
203
+ )
204
+ deprecate(
205
+ "steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False
206
+ )
207
+ new_config = dict(scheduler.config)
208
+ new_config["steps_offset"] = 1
209
+ scheduler._internal_dict = FrozenDict(new_config)
210
+
211
+ if (
212
+ hasattr(scheduler.config, "clip_sample")
213
+ and scheduler.config.clip_sample is True
214
+ ):
215
+ deprecation_message = (
216
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
217
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
218
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
219
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
220
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
221
+ )
222
+ deprecate(
223
+ "clip_sample not set", "1.0.0", deprecation_message, standard_warn=False
224
+ )
225
+ new_config = dict(scheduler.config)
226
+ new_config["clip_sample"] = False
227
+ scheduler._internal_dict = FrozenDict(new_config)
228
+
229
+ self.register_modules(
230
+ vae=vae,
231
+ text_encoder=text_encoder,
232
+ transformer=transformer,
233
+ scheduler=scheduler,
234
+ text_encoder_2=text_encoder_2,
235
+ )
236
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
237
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
238
+
239
+ def encode_prompt(
240
+ self,
241
+ prompt,
242
+ device,
243
+ num_videos_per_prompt,
244
+ do_classifier_free_guidance,
245
+ negative_prompt=None,
246
+ prompt_embeds: Optional[torch.Tensor] = None,
247
+ attention_mask: Optional[torch.Tensor] = None,
248
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
249
+ negative_attention_mask: Optional[torch.Tensor] = None,
250
+ lora_scale: Optional[float] = None,
251
+ clip_skip: Optional[int] = None,
252
+ text_encoder: Optional[TextEncoder] = None,
253
+ data_type: Optional[str] = "image",
254
+ ):
255
+ r"""
256
+ Encodes the prompt into text encoder hidden states.
257
+
258
+ Args:
259
+ prompt (`str` or `List[str]`, *optional*):
260
+ prompt to be encoded
261
+ device: (`torch.device`):
262
+ torch device
263
+ num_videos_per_prompt (`int`):
264
+ number of videos that should be generated per prompt
265
+ do_classifier_free_guidance (`bool`):
266
+ whether to use classifier free guidance or not
267
+ negative_prompt (`str` or `List[str]`, *optional*):
268
+ The prompt or prompts not to guide the video generation. If not defined, one has to pass
269
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
270
+ less than `1`).
271
+ prompt_embeds (`torch.Tensor`, *optional*):
272
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
273
+ provided, text embeddings will be generated from `prompt` input argument.
274
+ attention_mask (`torch.Tensor`, *optional*):
275
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
276
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
277
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
278
+ argument.
279
+ negative_attention_mask (`torch.Tensor`, *optional*):
280
+ lora_scale (`float`, *optional*):
281
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
282
+ clip_skip (`int`, *optional*):
283
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
284
+ the output of the pre-final layer will be used for computing the prompt embeddings.
285
+ text_encoder (TextEncoder, *optional*):
286
+ data_type (`str`, *optional*):
287
+ """
288
+ if text_encoder is None:
289
+ text_encoder = self.text_encoder
290
+
291
+ # set lora scale so that monkey patched LoRA
292
+ # function of text encoder can correctly access it
293
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
294
+ self._lora_scale = lora_scale
295
+
296
+ # dynamically adjust the LoRA scale
297
+ if not USE_PEFT_BACKEND:
298
+ adjust_lora_scale_text_encoder(text_encoder.model, lora_scale)
299
+ else:
300
+ scale_lora_layers(text_encoder.model, lora_scale)
301
+
302
+ if prompt is not None and isinstance(prompt, str):
303
+ batch_size = 1
304
+ elif prompt is not None and isinstance(prompt, list):
305
+ batch_size = len(prompt)
306
+ else:
307
+ batch_size = prompt_embeds.shape[0]
308
+
309
+ if prompt_embeds is None:
310
+ # textual inversion: process multi-vector tokens if necessary
311
+ if isinstance(self, TextualInversionLoaderMixin):
312
+ prompt = self.maybe_convert_prompt(prompt, text_encoder.tokenizer)
313
+
314
+ text_inputs = text_encoder.text2tokens(prompt, data_type=data_type)
315
+
316
+ if clip_skip is None:
317
+ prompt_outputs = text_encoder.encode(
318
+ text_inputs, data_type=data_type, device=device
319
+ )
320
+ prompt_embeds = prompt_outputs.hidden_state
321
+ else:
322
+ prompt_outputs = text_encoder.encode(
323
+ text_inputs,
324
+ output_hidden_states=True,
325
+ data_type=data_type,
326
+ device=device,
327
+ )
328
+ # Access the `hidden_states` first, that contains a tuple of
329
+ # all the hidden states from the encoder layers. Then index into
330
+ # the tuple to access the hidden states from the desired layer.
331
+ prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]
332
+ # We also need to apply the final LayerNorm here to not mess with the
333
+ # representations. The `last_hidden_states` that we typically use for
334
+ # obtaining the final prompt representations passes through the LayerNorm
335
+ # layer.
336
+ prompt_embeds = text_encoder.model.text_model.final_layer_norm(
337
+ prompt_embeds
338
+ )
339
+
340
+ attention_mask = prompt_outputs.attention_mask
341
+ if attention_mask is not None:
342
+ attention_mask = attention_mask.to(device)
343
+ bs_embed, seq_len = attention_mask.shape
344
+ attention_mask = attention_mask.repeat(1, num_videos_per_prompt)
345
+ attention_mask = attention_mask.view(
346
+ bs_embed * num_videos_per_prompt, seq_len
347
+ )
348
+
349
+ if text_encoder is not None:
350
+ prompt_embeds_dtype = text_encoder.dtype
351
+ elif self.transformer is not None:
352
+ prompt_embeds_dtype = self.transformer.dtype
353
+ else:
354
+ prompt_embeds_dtype = prompt_embeds.dtype
355
+
356
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
357
+
358
+ if prompt_embeds.ndim == 2:
359
+ bs_embed, _ = prompt_embeds.shape
360
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
361
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt)
362
+ prompt_embeds = prompt_embeds.view(bs_embed * num_videos_per_prompt, -1)
363
+ else:
364
+ bs_embed, seq_len, _ = prompt_embeds.shape
365
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
366
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
367
+ prompt_embeds = prompt_embeds.view(
368
+ bs_embed * num_videos_per_prompt, seq_len, -1
369
+ )
370
+
371
+ # get unconditional embeddings for classifier free guidance
372
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
373
+ uncond_tokens: List[str]
374
+ if negative_prompt is None:
375
+ uncond_tokens = [""] * batch_size
376
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
377
+ raise TypeError(
378
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
379
+ f" {type(prompt)}."
380
+ )
381
+ elif isinstance(negative_prompt, str):
382
+ uncond_tokens = [negative_prompt]
383
+ elif batch_size != len(negative_prompt):
384
+ raise ValueError(
385
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
386
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
387
+ " the batch size of `prompt`."
388
+ )
389
+ else:
390
+ uncond_tokens = negative_prompt
391
+
392
+ # textual inversion: process multi-vector tokens if necessary
393
+ if isinstance(self, TextualInversionLoaderMixin):
394
+ uncond_tokens = self.maybe_convert_prompt(
395
+ uncond_tokens, text_encoder.tokenizer
396
+ )
397
+
398
+ # max_length = prompt_embeds.shape[1]
399
+ uncond_input = text_encoder.text2tokens(uncond_tokens, data_type=data_type)
400
+
401
+ negative_prompt_outputs = text_encoder.encode(
402
+ uncond_input, data_type=data_type, device=device
403
+ )
404
+ negative_prompt_embeds = negative_prompt_outputs.hidden_state
405
+
406
+ negative_attention_mask = negative_prompt_outputs.attention_mask
407
+ if negative_attention_mask is not None:
408
+ negative_attention_mask = negative_attention_mask.to(device)
409
+ _, seq_len = negative_attention_mask.shape
410
+ negative_attention_mask = negative_attention_mask.repeat(
411
+ 1, num_videos_per_prompt
412
+ )
413
+ negative_attention_mask = negative_attention_mask.view(
414
+ batch_size * num_videos_per_prompt, seq_len
415
+ )
416
+
417
+ if do_classifier_free_guidance:
418
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
419
+ seq_len = negative_prompt_embeds.shape[1]
420
+
421
+ negative_prompt_embeds = negative_prompt_embeds.to(
422
+ dtype=prompt_embeds_dtype, device=device
423
+ )
424
+
425
+ if negative_prompt_embeds.ndim == 2:
426
+ negative_prompt_embeds = negative_prompt_embeds.repeat(
427
+ 1, num_videos_per_prompt
428
+ )
429
+ negative_prompt_embeds = negative_prompt_embeds.view(
430
+ batch_size * num_videos_per_prompt, -1
431
+ )
432
+ else:
433
+ negative_prompt_embeds = negative_prompt_embeds.repeat(
434
+ 1, num_videos_per_prompt, 1
435
+ )
436
+ negative_prompt_embeds = negative_prompt_embeds.view(
437
+ batch_size * num_videos_per_prompt, seq_len, -1
438
+ )
439
+
440
+ if text_encoder is not None:
441
+ if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
442
+ # Retrieve the original scale by scaling back the LoRA layers
443
+ unscale_lora_layers(text_encoder.model, lora_scale)
444
+
445
+ return (
446
+ prompt_embeds,
447
+ negative_prompt_embeds,
448
+ attention_mask,
449
+ negative_attention_mask,
450
+ )
451
+
452
+ def decode_latents(self, latents, enable_tiling=True):
453
+ deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
454
+ deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
455
+
456
+ latents = 1 / self.vae.config.scaling_factor * latents
457
+ if enable_tiling:
458
+ self.vae.enable_tiling()
459
+ image = self.vae.decode(latents, return_dict=False)[0]
460
+ else:
461
+ image = self.vae.decode(latents, return_dict=False)[0]
462
+ image = (image / 2 + 0.5).clamp(0, 1)
463
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
464
+ if image.ndim == 4:
465
+ image = image.cpu().permute(0, 2, 3, 1).float()
466
+ else:
467
+ image = image.cpu().float()
468
+ return image
469
+
470
+ def prepare_extra_func_kwargs(self, func, kwargs):
471
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
472
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
473
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
474
+ # and should be between [0, 1]
475
+ extra_step_kwargs = {}
476
+
477
+ for k, v in kwargs.items():
478
+ accepts = k in set(inspect.signature(func).parameters.keys())
479
+ if accepts:
480
+ extra_step_kwargs[k] = v
481
+ return extra_step_kwargs
482
+
483
+ def check_inputs(
484
+ self,
485
+ prompt,
486
+ height,
487
+ width,
488
+ video_length,
489
+ callback_steps,
490
+ negative_prompt=None,
491
+ prompt_embeds=None,
492
+ negative_prompt_embeds=None,
493
+ callback_on_step_end_tensor_inputs=None,
494
+ vae_ver="88-4c-sd",
495
+ ):
496
+ if height % 8 != 0 or width % 8 != 0:
497
+ raise ValueError(
498
+ f"`height` and `width` have to be divisible by 8 but are {height} and {width}."
499
+ )
500
+
501
+ if video_length is not None:
502
+ if "884" in vae_ver:
503
+ if video_length != 1 and (video_length - 1) % 4 != 0:
504
+ raise ValueError(
505
+ f"`video_length` has to be 1 or a multiple of 4 but is {video_length}."
506
+ )
507
+ elif "888" in vae_ver:
508
+ if video_length != 1 and (video_length - 1) % 8 != 0:
509
+ raise ValueError(
510
+ f"`video_length` has to be 1 or a multiple of 8 but is {video_length}."
511
+ )
512
+
513
+ if callback_steps is not None and (
514
+ not isinstance(callback_steps, int) or callback_steps <= 0
515
+ ):
516
+ raise ValueError(
517
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
518
+ f" {type(callback_steps)}."
519
+ )
520
+ if callback_on_step_end_tensor_inputs is not None and not all(
521
+ k in self._callback_tensor_inputs
522
+ for k in callback_on_step_end_tensor_inputs
523
+ ):
524
+ raise ValueError(
525
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
526
+ )
527
+
528
+ if prompt is not None and prompt_embeds is not None:
529
+ raise ValueError(
530
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
531
+ " only forward one of the two."
532
+ )
533
+ elif prompt is None and prompt_embeds is None:
534
+ raise ValueError(
535
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
536
+ )
537
+ elif prompt is not None and (
538
+ not isinstance(prompt, str) and not isinstance(prompt, list)
539
+ ):
540
+ raise ValueError(
541
+ f"`prompt` has to be of type `str` or `list` but is {type(prompt)}"
542
+ )
543
+
544
+ if negative_prompt is not None and negative_prompt_embeds is not None:
545
+ raise ValueError(
546
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
547
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
548
+ )
549
+
550
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
551
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
552
+ raise ValueError(
553
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
554
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
555
+ f" {negative_prompt_embeds.shape}."
556
+ )
557
+
558
+
559
+ def prepare_latents(
560
+ self,
561
+ batch_size,
562
+ num_channels_latents,
563
+ height,
564
+ width,
565
+ video_length,
566
+ dtype,
567
+ device,
568
+ generator,
569
+ latents=None,
570
+ ):
571
+ shape = (
572
+ batch_size,
573
+ num_channels_latents,
574
+ video_length,
575
+ int(height) // self.vae_scale_factor,
576
+ int(width) // self.vae_scale_factor,
577
+ )
578
+ if isinstance(generator, list) and len(generator) != batch_size:
579
+ raise ValueError(
580
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
581
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
582
+ )
583
+
584
+ if latents is None:
585
+ # latents = randn_tensor(
586
+ # shape, generator=generator, device=device, dtype=dtype
587
+ # )
588
+ # make first N frames to be the same ####################################
589
+ shape_or_frame = (1, num_channels_latents, 1, height // self.vae_scale_factor, width // self.vae_scale_factor)
590
+ latents = []
591
+ for i in range(video_length):
592
+ latents.append(randn_tensor(shape_or_frame, generator=generator, device=device, dtype=dtype))
593
+ latents = torch.cat(latents, dim=2)
594
+
595
+
596
+ else:
597
+ latents = latents.to(device)
598
+
599
+ # Check existence to make it compatible with FlowMatchEulerDiscreteScheduler
600
+ if hasattr(self.scheduler, "init_noise_sigma"):
601
+ # scale the initial noise by the standard deviation required by the scheduler
602
+ latents = latents * self.scheduler.init_noise_sigma
603
+ return latents
604
+
605
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
606
+ def get_guidance_scale_embedding(
607
+ self,
608
+ w: torch.Tensor,
609
+ embedding_dim: int = 512,
610
+ dtype: torch.dtype = torch.float32,
611
+ ) -> torch.Tensor:
612
+ """
613
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
614
+
615
+ Args:
616
+ w (`torch.Tensor`):
617
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
618
+ embedding_dim (`int`, *optional*, defaults to 512):
619
+ Dimension of the embeddings to generate.
620
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
621
+ Data type of the generated embeddings.
622
+
623
+ Returns:
624
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
625
+ """
626
+ assert len(w.shape) == 1
627
+ w = w * 1000.0
628
+
629
+ half_dim = embedding_dim // 2
630
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
631
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
632
+ emb = w.to(dtype)[:, None] * emb[None, :]
633
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
634
+ if embedding_dim % 2 == 1: # zero pad
635
+ emb = torch.nn.functional.pad(emb, (0, 1))
636
+ assert emb.shape == (w.shape[0], embedding_dim)
637
+ return emb
638
+
639
+ @property
640
+ def guidance_scale(self):
641
+ return self._guidance_scale
642
+
643
+ @property
644
+ def guidance_rescale(self):
645
+ return self._guidance_rescale
646
+
647
+ @property
648
+ def clip_skip(self):
649
+ return self._clip_skip
650
+
651
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
652
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
653
+ # corresponds to doing no classifier free guidance.
654
+ @property
655
+ def do_classifier_free_guidance(self):
656
+ # return self._guidance_scale > 1 and self.transformer.config.time_cond_proj_dim is None
657
+ return self._guidance_scale > 1
658
+
659
+ @property
660
+ def cross_attention_kwargs(self):
661
+ return self._cross_attention_kwargs
662
+
663
+ @property
664
+ def num_timesteps(self):
665
+ return self._num_timesteps
666
+
667
+ @property
668
+ def interrupt(self):
669
+ return self._interrupt
670
+
671
+ @torch.no_grad()
672
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
673
+ def __call__(
674
+ self,
675
+ prompt: Union[str, List[str]],
676
+ height: int,
677
+ width: int,
678
+ video_length: int,
679
+ data_type: str = "video",
680
+ num_inference_steps: int = 50,
681
+ timesteps: List[int] = None,
682
+ sigmas: List[float] = None,
683
+ guidance_scale: float = 7.5,
684
+ negative_prompt: Optional[Union[str, List[str]]] = None,
685
+ num_videos_per_prompt: Optional[int] = 1,
686
+ eta: float = 0.0,
687
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
688
+ latents: Optional[torch.Tensor] = None,
689
+ prompt_embeds: Optional[torch.Tensor] = None,
690
+ attention_mask: Optional[torch.Tensor] = None,
691
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
692
+ negative_attention_mask: Optional[torch.Tensor] = None,
693
+ output_type: Optional[str] = "pil",
694
+ return_dict: bool = True,
695
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
696
+ guidance_rescale: float = 0.0,
697
+ clip_skip: Optional[int] = None,
698
+ callback_on_step_end: Optional[
699
+ Union[
700
+ Callable[[int, int, Dict], None],
701
+ PipelineCallback,
702
+ MultiPipelineCallbacks,
703
+ ]
704
+ ] = None,
705
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
706
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
707
+ vae_ver: str = "88-4c-sd",
708
+ enable_tiling: bool = False,
709
+ n_tokens: Optional[int] = None,
710
+ embedded_guidance_scale: Optional[float] = None,
711
+ **kwargs,
712
+ ):
713
+ r"""
714
+ The call function to the pipeline for generation.
715
+
716
+ Args:
717
+ prompt (`str` or `List[str]`):
718
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
719
+ height (`int`):
720
+ The height in pixels of the generated image.
721
+ width (`int`):
722
+ The width in pixels of the generated image.
723
+ video_length (`int`):
724
+ The number of frames in the generated video.
725
+ num_inference_steps (`int`, *optional*, defaults to 50):
726
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
727
+ expense of slower inference.
728
+ timesteps (`List[int]`, *optional*):
729
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
730
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
731
+ passed will be used. Must be in descending order.
732
+ sigmas (`List[float]`, *optional*):
733
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
734
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
735
+ will be used.
736
+ guidance_scale (`float`, *optional*, defaults to 7.5):
737
+ A higher guidance scale value encourages the model to generate images closely linked to the text
738
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
739
+ negative_prompt (`str` or `List[str]`, *optional*):
740
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
741
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
742
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
743
+ The number of images to generate per prompt.
744
+ eta (`float`, *optional*, defaults to 0.0):
745
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
746
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
747
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
748
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
749
+ generation deterministic.
750
+ latents (`torch.Tensor`, *optional*):
751
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
752
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
753
+ tensor is generated by sampling using the supplied random `generator`.
754
+ prompt_embeds (`torch.Tensor`, *optional*):
755
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
756
+ provided, text embeddings are generated from the `prompt` input argument.
757
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
758
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
759
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
760
+
761
+ output_type (`str`, *optional*, defaults to `"pil"`):
762
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
763
+ return_dict (`bool`, *optional*, defaults to `True`):
764
+ Whether or not to return a [`HunyuanVideoPipelineOutput`] instead of a
765
+ plain tuple.
766
+ cross_attention_kwargs (`dict`, *optional*):
767
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
768
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
769
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
770
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
771
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
772
+ using zero terminal SNR.
773
+ clip_skip (`int`, *optional*):
774
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
775
+ the output of the pre-final layer will be used for computing the prompt embeddings.
776
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
777
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
778
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
779
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
780
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
781
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
782
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
783
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
784
+ `._callback_tensor_inputs` attribute of your pipeline class.
785
+
786
+ Examples:
787
+
788
+ Returns:
789
+ [`~HunyuanVideoPipelineOutput`] or `tuple`:
790
+ If `return_dict` is `True`, [`HunyuanVideoPipelineOutput`] is returned,
791
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
792
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
793
+ "not-safe-for-work" (nsfw) content.
794
+ """
795
+ callback = kwargs.pop("callback", None)
796
+ callback_steps = kwargs.pop("callback_steps", None)
797
+
798
+ # if callback is not None:
799
+ # deprecate(
800
+ # "callback",
801
+ # "1.0.0",
802
+ # "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
803
+ # )
804
+ # if callback_steps is not None:
805
+ # deprecate(
806
+ # "callback_steps",
807
+ # "1.0.0",
808
+ # "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
809
+ # )
810
+
811
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
812
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
813
+
814
+ # 0. Default height and width to unet
815
+ # height = height or self.transformer.config.sample_size * self.vae_scale_factor
816
+ # width = width or self.transformer.config.sample_size * self.vae_scale_factor
817
+ # to deal with lora scaling and other possible forward hooks
818
+
819
+ # 1. Check inputs. Raise error if not correct
820
+ self.check_inputs(
821
+ prompt,
822
+ height,
823
+ width,
824
+ video_length,
825
+ callback_steps,
826
+ negative_prompt,
827
+ prompt_embeds,
828
+ negative_prompt_embeds,
829
+ callback_on_step_end_tensor_inputs,
830
+ vae_ver=vae_ver,
831
+ )
832
+
833
+ self._guidance_scale = guidance_scale
834
+ self._guidance_rescale = guidance_rescale
835
+ self._clip_skip = clip_skip
836
+ self._cross_attention_kwargs = cross_attention_kwargs
837
+ self._interrupt = False
838
+
839
+ # 2. Define call parameters
840
+ if prompt is not None and isinstance(prompt, str):
841
+ batch_size = 1
842
+ elif prompt is not None and isinstance(prompt, list):
843
+ batch_size = len(prompt)
844
+ else:
845
+ batch_size = prompt_embeds.shape[0]
846
+
847
+ device = torch.device(f"cuda:{dist.get_rank()}") if dist.is_initialized() else self._execution_device
848
+
849
+ # 3. Encode input prompt
850
+ lora_scale = (
851
+ self.cross_attention_kwargs.get("scale", None)
852
+ if self.cross_attention_kwargs is not None
853
+ else None
854
+ )
855
+
856
+ (
857
+ prompt_embeds,
858
+ negative_prompt_embeds,
859
+ prompt_mask,
860
+ negative_prompt_mask,
861
+ ) = self.encode_prompt(
862
+ prompt,
863
+ device,
864
+ num_videos_per_prompt,
865
+ self.do_classifier_free_guidance,
866
+ negative_prompt,
867
+ prompt_embeds=prompt_embeds,
868
+ attention_mask=attention_mask,
869
+ negative_prompt_embeds=negative_prompt_embeds,
870
+ negative_attention_mask=negative_attention_mask,
871
+ lora_scale=lora_scale,
872
+ clip_skip=self.clip_skip,
873
+ data_type=data_type,
874
+ )
875
+ if self.text_encoder_2 is not None:
876
+ (
877
+ prompt_embeds_2,
878
+ negative_prompt_embeds_2,
879
+ prompt_mask_2,
880
+ negative_prompt_mask_2,
881
+ ) = self.encode_prompt(
882
+ prompt,
883
+ device,
884
+ num_videos_per_prompt,
885
+ self.do_classifier_free_guidance,
886
+ negative_prompt,
887
+ prompt_embeds=None,
888
+ attention_mask=None,
889
+ negative_prompt_embeds=None,
890
+ negative_attention_mask=None,
891
+ lora_scale=lora_scale,
892
+ clip_skip=self.clip_skip,
893
+ text_encoder=self.text_encoder_2,
894
+ data_type=data_type,
895
+ )
896
+ else:
897
+ prompt_embeds_2 = None
898
+ negative_prompt_embeds_2 = None
899
+ prompt_mask_2 = None
900
+ negative_prompt_mask_2 = None
901
+
902
+ # For classifier free guidance, we need to do two forward passes.
903
+ # Here we concatenate the unconditional and text embeddings into a single batch
904
+ # to avoid doing two forward passes
905
+ if self.do_classifier_free_guidance:
906
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
907
+ if prompt_mask is not None:
908
+ prompt_mask = torch.cat([negative_prompt_mask, prompt_mask])
909
+ if prompt_embeds_2 is not None:
910
+ prompt_embeds_2 = torch.cat([negative_prompt_embeds_2, prompt_embeds_2])
911
+ if prompt_mask_2 is not None:
912
+ prompt_mask_2 = torch.cat([negative_prompt_mask_2, prompt_mask_2])
913
+
914
+
915
+ # 4. Prepare timesteps
916
+ extra_set_timesteps_kwargs = self.prepare_extra_func_kwargs(
917
+ self.scheduler.set_timesteps, {"n_tokens": n_tokens}
918
+ )
919
+ timesteps, num_inference_steps = retrieve_timesteps(
920
+ self.scheduler,
921
+ num_inference_steps,
922
+ device,
923
+ timesteps,
924
+ sigmas,
925
+ **extra_set_timesteps_kwargs,
926
+ )
927
+
928
+ if "884" in vae_ver:
929
+ video_length = (video_length - 1) // 4 + 1
930
+ elif "888" in vae_ver:
931
+ video_length = (video_length - 1) // 8 + 1
932
+ else:
933
+ video_length = video_length
934
+
935
+ # 5. Prepare latent variables
936
+ num_channels_latents = self.transformer.config.in_channels
937
+ latents = self.prepare_latents(
938
+ batch_size * num_videos_per_prompt,
939
+ num_channels_latents,
940
+ height,
941
+ width,
942
+ video_length,
943
+ prompt_embeds.dtype,
944
+ device,
945
+ generator,
946
+ latents,
947
+ )
948
+
949
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
950
+ extra_step_kwargs = self.prepare_extra_func_kwargs(
951
+ self.scheduler.step,
952
+ {"generator": generator, "eta": eta},
953
+ )
954
+
955
+ target_dtype = PRECISION_TO_TYPE[self.args.precision]
956
+ autocast_enabled = (
957
+ target_dtype != torch.float32
958
+ ) and not self.args.disable_autocast
959
+ vae_dtype = PRECISION_TO_TYPE[self.args.vae_precision]
960
+ vae_autocast_enabled = (
961
+ vae_dtype != torch.float32
962
+ ) and not self.args.disable_autocast
963
+
964
+ # 7. Denoising loop
965
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
966
+ self._num_timesteps = len(timesteps)
967
+
968
+ if callback != None:
969
+ callback(-1, None, None)
970
+ load_latent = True
971
+ load_latent = False
972
+
973
+ if load_latent:
974
+ timesteps = []
975
+ # if is_progress_bar:
976
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
977
+ for i, t in enumerate(timesteps):
978
+ offload.set_step_no_for_lora(i)
979
+ if self.interrupt:
980
+ continue
981
+ import os
982
+ if os.path.isfile("abort"):
983
+ continue
984
+
985
+ # expand the latents if we are doing classifier free guidance
986
+ latent_model_input = (
987
+ torch.cat([latents] * 2)
988
+ if self.do_classifier_free_guidance
989
+ else latents
990
+ )
991
+ latent_model_input = self.scheduler.scale_model_input(
992
+ latent_model_input, t
993
+ )
994
+
995
+ t_expand = t.repeat(latent_model_input.shape[0])
996
+ guidance_expand = (
997
+ torch.tensor(
998
+ [embedded_guidance_scale] * latent_model_input.shape[0],
999
+ dtype=torch.float32,
1000
+ device=device,
1001
+ ).to(target_dtype)
1002
+ * 1000.0
1003
+ if embedded_guidance_scale is not None
1004
+ else None
1005
+ )
1006
+
1007
+ # predict the noise residual
1008
+ with torch.autocast(
1009
+ device_type="cuda", dtype=target_dtype, enabled=autocast_enabled
1010
+ ):
1011
+ ret = self.transformer( # For an input image (129, 192, 336) (1, 256, 256)
1012
+ latent_model_input, # [2, 16, 33, 24, 42]
1013
+ t_expand, # [2]
1014
+ text_states=prompt_embeds, # [2, 256, 4096]
1015
+ text_mask=prompt_mask, # [2, 256]
1016
+ text_states_2=prompt_embeds_2, # [2, 768]
1017
+ freqs_cos=freqs_cis[0], # [seqlen, head_dim]
1018
+ freqs_sin=freqs_cis[1], # [seqlen, head_dim]
1019
+ guidance=guidance_expand,
1020
+ pipeline=self,
1021
+ return_dict=True,
1022
+ )
1023
+
1024
+ if self._interrupt:
1025
+ return [None]
1026
+ noise_pred= ret["x"]
1027
+
1028
+ # perform guidance
1029
+ if self.do_classifier_free_guidance:
1030
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1031
+ noise_pred = noise_pred_uncond + self.guidance_scale * (
1032
+ noise_pred_text - noise_pred_uncond
1033
+ )
1034
+
1035
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1036
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1037
+ noise_pred = rescale_noise_cfg(
1038
+ noise_pred,
1039
+ noise_pred_text,
1040
+ guidance_rescale=self.guidance_rescale,
1041
+ )
1042
+
1043
+ # compute the previous noisy sample x_t -> x_t-1
1044
+ latents = self.scheduler.step(
1045
+ noise_pred, t, latents, **extra_step_kwargs, return_dict=False
1046
+ )[0]
1047
+
1048
+ if callback_on_step_end is not None:
1049
+ callback_kwargs = {}
1050
+ for k in callback_on_step_end_tensor_inputs:
1051
+ callback_kwargs[k] = locals()[k]
1052
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1053
+
1054
+ latents = callback_outputs.pop("latents", latents)
1055
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1056
+ negative_prompt_embeds = callback_outputs.pop(
1057
+ "negative_prompt_embeds", negative_prompt_embeds
1058
+ )
1059
+
1060
+ # call the callback, if provided
1061
+ if i == len(timesteps) - 1 or (
1062
+ (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
1063
+ ):
1064
+ if progress_bar is not None:
1065
+ progress_bar.update()
1066
+ if callback is not None and i % callback_steps == 0:
1067
+ step_idx = i // getattr(self.scheduler, "order", 1)
1068
+ callback(step_idx, t, latents)
1069
+
1070
+ if self.interrupt:
1071
+ return [None]
1072
+
1073
+ if load_latent:
1074
+ latents = torch.load("latent.pt")
1075
+ else:
1076
+ torch.save(latents, "latent.pt")
1077
+
1078
+ if not output_type == "latent":
1079
+ expand_temporal_dim = False
1080
+ if len(latents.shape) == 4:
1081
+ if isinstance(self.vae, AutoencoderKLCausal3D):
1082
+ latents = latents.unsqueeze(2)
1083
+ expand_temporal_dim = True
1084
+ elif len(latents.shape) == 5:
1085
+ pass
1086
+ else:
1087
+ raise ValueError(
1088
+ f"Only support latents with shape (b, c, h, w) or (b, c, f, h, w), but got {latents.shape}."
1089
+ )
1090
+
1091
+ if (
1092
+ hasattr(self.vae.config, "shift_factor")
1093
+ and self.vae.config.shift_factor
1094
+ ):
1095
+ latents = (
1096
+ latents / self.vae.config.scaling_factor
1097
+ + self.vae.config.shift_factor
1098
+ )
1099
+ else:
1100
+ latents = latents / self.vae.config.scaling_factor
1101
+
1102
+ with torch.autocast(
1103
+ device_type="cuda", dtype=vae_dtype, enabled=vae_autocast_enabled
1104
+ ):
1105
+ if enable_tiling:
1106
+ self.vae.enable_tiling()
1107
+ image = self.vae.decode(
1108
+ latents, return_dict=False, generator=generator
1109
+ )[0]
1110
+ else:
1111
+ image = self.vae.decode(
1112
+ latents, return_dict=False, generator=generator
1113
+ )[0]
1114
+
1115
+ if expand_temporal_dim or image.shape[2] == 1:
1116
+ image = image.squeeze(2)
1117
+
1118
+ else:
1119
+ image = latents
1120
+
1121
+ image = (image / 2 + 0.5).clamp(0, 1)
1122
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
1123
+ image = image.cpu().float()
1124
+
1125
+ # Offload all models
1126
+ self.maybe_free_model_hooks()
1127
+
1128
+ if not return_dict:
1129
+ return image
1130
+
1131
+ return HunyuanVideoPipelineOutput(videos=image)
hyvideo/diffusion/schedulers/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .scheduling_flow_match_discrete import FlowMatchDiscreteScheduler
hyvideo/diffusion/schedulers/scheduling_flow_match_discrete.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Stability AI, Katherine Crowson and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ #
16
+ # Modified from diffusers==0.29.2
17
+ #
18
+ # ==============================================================================
19
+
20
+ from dataclasses import dataclass
21
+ from typing import Optional, Tuple, Union
22
+
23
+ import numpy as np
24
+ import torch
25
+
26
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
27
+ from diffusers.utils import BaseOutput, logging
28
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
29
+
30
+
31
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
32
+
33
+
34
+ @dataclass
35
+ class FlowMatchDiscreteSchedulerOutput(BaseOutput):
36
+ """
37
+ Output class for the scheduler's `step` function output.
38
+
39
+ Args:
40
+ prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
41
+ Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
42
+ denoising loop.
43
+ """
44
+
45
+ prev_sample: torch.FloatTensor
46
+
47
+
48
+ class FlowMatchDiscreteScheduler(SchedulerMixin, ConfigMixin):
49
+ """
50
+ Euler scheduler.
51
+
52
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
53
+ methods the library implements for all schedulers such as loading and saving.
54
+
55
+ Args:
56
+ num_train_timesteps (`int`, defaults to 1000):
57
+ The number of diffusion steps to train the model.
58
+ timestep_spacing (`str`, defaults to `"linspace"`):
59
+ The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
60
+ Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
61
+ shift (`float`, defaults to 1.0):
62
+ The shift value for the timestep schedule.
63
+ reverse (`bool`, defaults to `True`):
64
+ Whether to reverse the timestep schedule.
65
+ """
66
+
67
+ _compatibles = []
68
+ order = 1
69
+
70
+ @register_to_config
71
+ def __init__(
72
+ self,
73
+ num_train_timesteps: int = 1000,
74
+ shift: float = 1.0,
75
+ reverse: bool = True,
76
+ solver: str = "euler",
77
+ n_tokens: Optional[int] = None,
78
+ ):
79
+ sigmas = torch.linspace(1, 0, num_train_timesteps + 1)
80
+
81
+ if not reverse:
82
+ sigmas = sigmas.flip(0)
83
+
84
+ self.sigmas = sigmas
85
+ # the value fed to model
86
+ self.timesteps = (sigmas[:-1] * num_train_timesteps).to(dtype=torch.float32)
87
+
88
+ self._step_index = None
89
+ self._begin_index = None
90
+
91
+ self.supported_solver = ["euler"]
92
+ if solver not in self.supported_solver:
93
+ raise ValueError(
94
+ f"Solver {solver} not supported. Supported solvers: {self.supported_solver}"
95
+ )
96
+
97
+ @property
98
+ def step_index(self):
99
+ """
100
+ The index counter for current timestep. It will increase 1 after each scheduler step.
101
+ """
102
+ return self._step_index
103
+
104
+ @property
105
+ def begin_index(self):
106
+ """
107
+ The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
108
+ """
109
+ return self._begin_index
110
+
111
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
112
+ def set_begin_index(self, begin_index: int = 0):
113
+ """
114
+ Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
115
+
116
+ Args:
117
+ begin_index (`int`):
118
+ The begin index for the scheduler.
119
+ """
120
+ self._begin_index = begin_index
121
+
122
+ def _sigma_to_t(self, sigma):
123
+ return sigma * self.config.num_train_timesteps
124
+
125
+ def set_timesteps(
126
+ self,
127
+ num_inference_steps: int,
128
+ device: Union[str, torch.device] = None,
129
+ n_tokens: int = None,
130
+ ):
131
+ """
132
+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
133
+
134
+ Args:
135
+ num_inference_steps (`int`):
136
+ The number of diffusion steps used when generating samples with a pre-trained model.
137
+ device (`str` or `torch.device`, *optional*):
138
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
139
+ n_tokens (`int`, *optional*):
140
+ Number of tokens in the input sequence.
141
+ """
142
+ self.num_inference_steps = num_inference_steps
143
+
144
+ sigmas = torch.linspace(1, 0, num_inference_steps + 1)
145
+ sigmas = self.sd3_time_shift(sigmas)
146
+
147
+ if not self.config.reverse:
148
+ sigmas = 1 - sigmas
149
+
150
+ self.sigmas = sigmas
151
+ self.timesteps = (sigmas[:-1] * self.config.num_train_timesteps).to(
152
+ dtype=torch.float32, device=device
153
+ )
154
+
155
+ # Reset step index
156
+ self._step_index = None
157
+
158
+ def index_for_timestep(self, timestep, schedule_timesteps=None):
159
+ if schedule_timesteps is None:
160
+ schedule_timesteps = self.timesteps
161
+
162
+ indices = (schedule_timesteps == timestep).nonzero()
163
+
164
+ # The sigma index that is taken for the **very** first `step`
165
+ # is always the second index (or the last index if there is only 1)
166
+ # This way we can ensure we don't accidentally skip a sigma in
167
+ # case we start in the middle of the denoising schedule (e.g. for image-to-image)
168
+ pos = 1 if len(indices) > 1 else 0
169
+
170
+ return indices[pos].item()
171
+
172
+ def _init_step_index(self, timestep):
173
+ if self.begin_index is None:
174
+ if isinstance(timestep, torch.Tensor):
175
+ timestep = timestep.to(self.timesteps.device)
176
+ self._step_index = self.index_for_timestep(timestep)
177
+ else:
178
+ self._step_index = self._begin_index
179
+
180
+ def scale_model_input(
181
+ self, sample: torch.Tensor, timestep: Optional[int] = None
182
+ ) -> torch.Tensor:
183
+ return sample
184
+
185
+ def sd3_time_shift(self, t: torch.Tensor):
186
+ return (self.config.shift * t) / (1 + (self.config.shift - 1) * t)
187
+
188
+ def step(
189
+ self,
190
+ model_output: torch.FloatTensor,
191
+ timestep: Union[float, torch.FloatTensor],
192
+ sample: torch.FloatTensor,
193
+ return_dict: bool = True,
194
+ ) -> Union[FlowMatchDiscreteSchedulerOutput, Tuple]:
195
+ """
196
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
197
+ process from the learned model outputs (most often the predicted noise).
198
+
199
+ Args:
200
+ model_output (`torch.FloatTensor`):
201
+ The direct output from learned diffusion model.
202
+ timestep (`float`):
203
+ The current discrete timestep in the diffusion chain.
204
+ sample (`torch.FloatTensor`):
205
+ A current instance of a sample created by the diffusion process.
206
+ generator (`torch.Generator`, *optional*):
207
+ A random number generator.
208
+ n_tokens (`int`, *optional*):
209
+ Number of tokens in the input sequence.
210
+ return_dict (`bool`):
211
+ Whether or not to return a [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or
212
+ tuple.
213
+
214
+ Returns:
215
+ [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or `tuple`:
216
+ If return_dict is `True`, [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] is
217
+ returned, otherwise a tuple is returned where the first element is the sample tensor.
218
+ """
219
+
220
+ if (
221
+ isinstance(timestep, int)
222
+ or isinstance(timestep, torch.IntTensor)
223
+ or isinstance(timestep, torch.LongTensor)
224
+ ):
225
+ raise ValueError(
226
+ (
227
+ "Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
228
+ " `EulerDiscreteScheduler.step()` is not supported. Make sure to pass"
229
+ " one of the `scheduler.timesteps` as a timestep."
230
+ ),
231
+ )
232
+
233
+ if self.step_index is None:
234
+ self._init_step_index(timestep)
235
+
236
+ # Upcast to avoid precision issues when computing prev_sample
237
+ sample = sample.to(torch.float32)
238
+
239
+ dt = self.sigmas[self.step_index + 1] - self.sigmas[self.step_index]
240
+
241
+ if self.config.solver == "euler":
242
+ prev_sample = sample + model_output.to(torch.float32) * dt
243
+ else:
244
+ raise ValueError(
245
+ f"Solver {self.config.solver} not supported. Supported solvers: {self.supported_solver}"
246
+ )
247
+
248
+ # upon completion increase step index by one
249
+ self._step_index += 1
250
+
251
+ if not return_dict:
252
+ return (prev_sample,)
253
+
254
+ return FlowMatchDiscreteSchedulerOutput(prev_sample=prev_sample)
255
+
256
+ def __len__(self):
257
+ return self.config.num_train_timesteps
hyvideo/inference.py ADDED
@@ -0,0 +1,686 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import random
4
+ import functools
5
+ from typing import List, Optional, Tuple, Union
6
+
7
+ from pathlib import Path
8
+ from loguru import logger
9
+
10
+ import torch
11
+ import torch.distributed as dist
12
+ from hyvideo.constants import PROMPT_TEMPLATE, NEGATIVE_PROMPT, PRECISION_TO_TYPE
13
+ from hyvideo.vae import load_vae
14
+ from hyvideo.modules import load_model
15
+ from hyvideo.text_encoder import TextEncoder
16
+ from hyvideo.utils.data_utils import align_to
17
+ from hyvideo.modules.posemb_layers import get_nd_rotary_pos_embed
18
+ from hyvideo.diffusion.schedulers import FlowMatchDiscreteScheduler
19
+ from hyvideo.diffusion.pipelines import HunyuanVideoPipeline
20
+
21
+ try:
22
+ import xfuser
23
+ from xfuser.core.distributed import (
24
+ get_sequence_parallel_world_size,
25
+ get_sequence_parallel_rank,
26
+ get_sp_group,
27
+ initialize_model_parallel,
28
+ init_distributed_environment
29
+ )
30
+ except:
31
+ xfuser = None
32
+ get_sequence_parallel_world_size = None
33
+ get_sequence_parallel_rank = None
34
+ get_sp_group = None
35
+ initialize_model_parallel = None
36
+ init_distributed_environment = None
37
+
38
+
39
+ def parallelize_transformer(pipe):
40
+ transformer = pipe.transformer
41
+ original_forward = transformer.forward
42
+
43
+ @functools.wraps(transformer.__class__.forward)
44
+ def new_forward(
45
+ self,
46
+ x: torch.Tensor,
47
+ t: torch.Tensor, # Should be in range(0, 1000).
48
+ text_states: torch.Tensor = None,
49
+ text_mask: torch.Tensor = None, # Now we don't use it.
50
+ text_states_2: Optional[torch.Tensor] = None, # Text embedding for modulation.
51
+ freqs_cos: Optional[torch.Tensor] = None,
52
+ freqs_sin: Optional[torch.Tensor] = None,
53
+ guidance: torch.Tensor = None, # Guidance for modulation, should be cfg_scale x 1000.
54
+ return_dict: bool = True,
55
+ ):
56
+ if x.shape[-2] // 2 % get_sequence_parallel_world_size() == 0:
57
+ # try to split x by height
58
+ split_dim = -2
59
+ elif x.shape[-1] // 2 % get_sequence_parallel_world_size() == 0:
60
+ # try to split x by width
61
+ split_dim = -1
62
+ else:
63
+ raise ValueError(f"Cannot split video sequence into ulysses_degree x ring_degree ({get_sequence_parallel_world_size()}) parts evenly")
64
+
65
+ # patch sizes for the temporal, height, and width dimensions are 1, 2, and 2.
66
+ temporal_size, h, w = x.shape[2], x.shape[3] // 2, x.shape[4] // 2
67
+
68
+ x = torch.chunk(x, get_sequence_parallel_world_size(),dim=split_dim)[get_sequence_parallel_rank()]
69
+
70
+ dim_thw = freqs_cos.shape[-1]
71
+ freqs_cos = freqs_cos.reshape(temporal_size, h, w, dim_thw)
72
+ freqs_cos = torch.chunk(freqs_cos, get_sequence_parallel_world_size(),dim=split_dim - 1)[get_sequence_parallel_rank()]
73
+ freqs_cos = freqs_cos.reshape(-1, dim_thw)
74
+ dim_thw = freqs_sin.shape[-1]
75
+ freqs_sin = freqs_sin.reshape(temporal_size, h, w, dim_thw)
76
+ freqs_sin = torch.chunk(freqs_sin, get_sequence_parallel_world_size(),dim=split_dim - 1)[get_sequence_parallel_rank()]
77
+ freqs_sin = freqs_sin.reshape(-1, dim_thw)
78
+
79
+ from xfuser.core.long_ctx_attention import xFuserLongContextAttention
80
+
81
+ for block in transformer.double_blocks + transformer.single_blocks:
82
+ block.hybrid_seq_parallel_attn = xFuserLongContextAttention()
83
+
84
+ output = original_forward(
85
+ x,
86
+ t,
87
+ text_states,
88
+ text_mask,
89
+ text_states_2,
90
+ freqs_cos,
91
+ freqs_sin,
92
+ guidance,
93
+ return_dict,
94
+ )
95
+
96
+ return_dict = not isinstance(output, tuple)
97
+ sample = output["x"]
98
+ sample = get_sp_group().all_gather(sample, dim=split_dim)
99
+ output["x"] = sample
100
+ return output
101
+
102
+ new_forward = new_forward.__get__(transformer)
103
+ transformer.forward = new_forward
104
+
105
+
106
+ class Inference(object):
107
+ def __init__(
108
+ self,
109
+ args,
110
+ vae,
111
+ vae_kwargs,
112
+ text_encoder,
113
+ model,
114
+ text_encoder_2=None,
115
+ pipeline=None,
116
+ use_cpu_offload=False,
117
+ device=None,
118
+ logger=None,
119
+ parallel_args=None,
120
+ ):
121
+ self.vae = vae
122
+ self.vae_kwargs = vae_kwargs
123
+
124
+ self.text_encoder = text_encoder
125
+ self.text_encoder_2 = text_encoder_2
126
+
127
+ self.model = model
128
+ self.pipeline = pipeline
129
+ self.use_cpu_offload = use_cpu_offload
130
+
131
+ self.args = args
132
+ self.device = (
133
+ device
134
+ if device is not None
135
+ else "cuda"
136
+ if torch.cuda.is_available()
137
+ else "cpu"
138
+ )
139
+ self.logger = logger
140
+ self.parallel_args = parallel_args
141
+
142
+ @classmethod
143
+ def from_pretrained(cls, pretrained_model_path, text_encoder_path, args, device=None, **kwargs):
144
+ """
145
+ Initialize the Inference pipeline.
146
+
147
+ Args:
148
+ pretrained_model_path (str or pathlib.Path): The model path, including t2v, text encoder and vae checkpoints.
149
+ args (argparse.Namespace): The arguments for the pipeline.
150
+ device (int): The device for inference. Default is 0.
151
+ """
152
+ # ========================================================================
153
+ logger.info(f"Got text-to-video model root path: {pretrained_model_path}")
154
+
155
+ # ==================== Initialize Distributed Environment ================
156
+ if args.ulysses_degree > 1 or args.ring_degree > 1:
157
+ assert xfuser is not None, \
158
+ "Ulysses Attention and Ring Attention requires xfuser package."
159
+
160
+ assert args.use_cpu_offload is False, \
161
+ "Cannot enable use_cpu_offload in the distributed environment."
162
+
163
+ dist.init_process_group("nccl")
164
+
165
+ assert dist.get_world_size() == args.ring_degree * args.ulysses_degree, \
166
+ "number of GPUs should be equal to ring_degree * ulysses_degree."
167
+
168
+ init_distributed_environment(rank=dist.get_rank(), world_size=dist.get_world_size())
169
+
170
+ initialize_model_parallel(
171
+ sequence_parallel_degree=dist.get_world_size(),
172
+ ring_degree=args.ring_degree,
173
+ ulysses_degree=args.ulysses_degree,
174
+ )
175
+ device = torch.device(f"cuda:{os.environ['LOCAL_RANK']}")
176
+ else:
177
+ if device is None:
178
+ device = "cuda" if torch.cuda.is_available() else "cpu"
179
+
180
+ parallel_args = {"ulysses_degree": args.ulysses_degree, "ring_degree": args.ring_degree}
181
+
182
+ # ======================== Get the args path =============================
183
+
184
+ # Disable gradient
185
+ torch.set_grad_enabled(False)
186
+ # =========================== Build main model ===========================
187
+ logger.info("Building model...")
188
+ pinToMemory = kwargs.pop("pinToMemory", False)
189
+ partialPinning = kwargs.pop("partialPinning", False)
190
+ # factor_kwargs = {"device": device, "dtype": PRECISION_TO_TYPE[args.precision]}
191
+ factor_kwargs = kwargs | {"device": "meta", "dtype": PRECISION_TO_TYPE[args.precision]}
192
+ in_channels = args.latent_channels
193
+ out_channels = args.latent_channels
194
+
195
+ model = load_model(
196
+ args,
197
+ in_channels=in_channels,
198
+ out_channels=out_channels,
199
+ factor_kwargs=factor_kwargs,
200
+ )
201
+ logger.info(f"Loading torch model {pretrained_model_path}...")
202
+
203
+ from mmgp import offload
204
+ offload.load_model_data(model, pretrained_model_path, pinToMemory = pinToMemory, partialPinning = partialPinning)
205
+
206
+ model.eval()
207
+
208
+ # ============================= Build extra models ========================
209
+ # VAE
210
+ vae, _, s_ratio, t_ratio = load_vae(
211
+ args.vae,
212
+ args.vae_precision,
213
+ logger=logger,
214
+ device=device if not args.use_cpu_offload else "cpu",
215
+ )
216
+ vae_kwargs = {"s_ratio": s_ratio, "t_ratio": t_ratio}
217
+
218
+ # Text encoder
219
+ if args.prompt_template_video is not None:
220
+ crop_start = PROMPT_TEMPLATE[args.prompt_template_video].get(
221
+ "crop_start", 0
222
+ )
223
+ elif args.prompt_template is not None:
224
+ crop_start = PROMPT_TEMPLATE[args.prompt_template].get("crop_start", 0)
225
+ else:
226
+ crop_start = 0
227
+ max_length = args.text_len + crop_start
228
+
229
+ # prompt_template
230
+ prompt_template = (
231
+ PROMPT_TEMPLATE[args.prompt_template]
232
+ if args.prompt_template is not None
233
+ else None
234
+ )
235
+
236
+ # prompt_template_video
237
+ prompt_template_video = (
238
+ PROMPT_TEMPLATE[args.prompt_template_video]
239
+ if args.prompt_template_video is not None
240
+ else None
241
+ )
242
+
243
+ text_encoder = TextEncoder(
244
+ text_encoder_type=args.text_encoder,
245
+ max_length=max_length,
246
+ text_encoder_precision=args.text_encoder_precision,
247
+ tokenizer_type=args.tokenizer,
248
+ prompt_template=prompt_template,
249
+ prompt_template_video=prompt_template_video,
250
+ hidden_state_skip_layer=args.hidden_state_skip_layer,
251
+ apply_final_norm=args.apply_final_norm,
252
+ reproduce=args.reproduce,
253
+ logger=logger,
254
+ device=device if not args.use_cpu_offload else "cpu",
255
+ text_encoder_path = text_encoder_path
256
+ )
257
+ text_encoder_2 = None
258
+ if args.text_encoder_2 is not None:
259
+ text_encoder_2 = TextEncoder(
260
+ text_encoder_type=args.text_encoder_2,
261
+ max_length=args.text_len_2,
262
+ text_encoder_precision=args.text_encoder_precision_2,
263
+ tokenizer_type=args.tokenizer_2,
264
+ reproduce=args.reproduce,
265
+ logger=logger,
266
+ device=device if not args.use_cpu_offload else "cpu",
267
+ )
268
+
269
+ return cls(
270
+ args=args,
271
+ vae=vae,
272
+ vae_kwargs=vae_kwargs,
273
+ text_encoder=text_encoder,
274
+ text_encoder_2=text_encoder_2,
275
+ model=model,
276
+ use_cpu_offload=args.use_cpu_offload,
277
+ device=device,
278
+ logger=logger,
279
+ parallel_args=parallel_args
280
+ )
281
+
282
+ @staticmethod
283
+ def load_state_dict(args, model, pretrained_model_path):
284
+ load_key = args.load_key
285
+ dit_weight = Path(args.dit_weight)
286
+
287
+ if dit_weight is None:
288
+ model_dir = pretrained_model_path / f"t2v_{args.model_resolution}"
289
+ files = list(model_dir.glob("*.pt"))
290
+ if len(files) == 0:
291
+ raise ValueError(f"No model weights found in {model_dir}")
292
+ if str(files[0]).startswith("pytorch_model_"):
293
+ model_path = dit_weight / f"pytorch_model_{load_key}.pt"
294
+ bare_model = True
295
+ elif any(str(f).endswith("_model_states.pt") for f in files):
296
+ files = [f for f in files if str(f).endswith("_model_states.pt")]
297
+ model_path = files[0]
298
+ if len(files) > 1:
299
+ logger.warning(
300
+ f"Multiple model weights found in {dit_weight}, using {model_path}"
301
+ )
302
+ bare_model = False
303
+ else:
304
+ raise ValueError(
305
+ f"Invalid model path: {dit_weight} with unrecognized weight format: "
306
+ f"{list(map(str, files))}. When given a directory as --dit-weight, only "
307
+ f"`pytorch_model_*.pt`(provided by HunyuanDiT official) and "
308
+ f"`*_model_states.pt`(saved by deepspeed) can be parsed. If you want to load a "
309
+ f"specific weight file, please provide the full path to the file."
310
+ )
311
+ else:
312
+ if dit_weight.is_dir():
313
+ files = list(dit_weight.glob("*.pt"))
314
+ if len(files) == 0:
315
+ raise ValueError(f"No model weights found in {dit_weight}")
316
+ if str(files[0]).startswith("pytorch_model_"):
317
+ model_path = dit_weight / f"pytorch_model_{load_key}.pt"
318
+ bare_model = True
319
+ elif any(str(f).endswith("_model_states.pt") for f in files):
320
+ files = [f for f in files if str(f).endswith("_model_states.pt")]
321
+ model_path = files[0]
322
+ if len(files) > 1:
323
+ logger.warning(
324
+ f"Multiple model weights found in {dit_weight}, using {model_path}"
325
+ )
326
+ bare_model = False
327
+ else:
328
+ raise ValueError(
329
+ f"Invalid model path: {dit_weight} with unrecognized weight format: "
330
+ f"{list(map(str, files))}. When given a directory as --dit-weight, only "
331
+ f"`pytorch_model_*.pt`(provided by HunyuanDiT official) and "
332
+ f"`*_model_states.pt`(saved by deepspeed) can be parsed. If you want to load a "
333
+ f"specific weight file, please provide the full path to the file."
334
+ )
335
+ elif dit_weight.is_file():
336
+ model_path = dit_weight
337
+ bare_model = "unknown"
338
+ else:
339
+ raise ValueError(f"Invalid model path: {dit_weight}")
340
+
341
+ if not model_path.exists():
342
+ raise ValueError(f"model_path not exists: {model_path}")
343
+ logger.info(f"Loading torch model {model_path}...")
344
+ state_dict = torch.load(model_path, map_location=lambda storage, loc: storage)
345
+
346
+ if bare_model == "unknown" and ("ema" in state_dict or "module" in state_dict):
347
+ bare_model = False
348
+ if bare_model is False:
349
+ if load_key in state_dict:
350
+ state_dict = state_dict[load_key]
351
+ else:
352
+ raise KeyError(
353
+ f"Missing key: `{load_key}` in the checkpoint: {model_path}. The keys in the checkpoint "
354
+ f"are: {list(state_dict.keys())}."
355
+ )
356
+ model.load_state_dict(state_dict, strict=True, assign = True )
357
+ return model
358
+
359
+ @staticmethod
360
+ def parse_size(size):
361
+ if isinstance(size, int):
362
+ size = [size]
363
+ if not isinstance(size, (list, tuple)):
364
+ raise ValueError(f"Size must be an integer or (height, width), got {size}.")
365
+ if len(size) == 1:
366
+ size = [size[0], size[0]]
367
+ if len(size) != 2:
368
+ raise ValueError(f"Size must be an integer or (height, width), got {size}.")
369
+ return size
370
+
371
+
372
+ class HunyuanVideoSampler(Inference):
373
+ def __init__(
374
+ self,
375
+ args,
376
+ vae,
377
+ vae_kwargs,
378
+ text_encoder,
379
+ model,
380
+ text_encoder_2=None,
381
+ pipeline=None,
382
+ use_cpu_offload=False,
383
+ device=0,
384
+ logger=None,
385
+ parallel_args=None
386
+ ):
387
+ super().__init__(
388
+ args,
389
+ vae,
390
+ vae_kwargs,
391
+ text_encoder,
392
+ model,
393
+ text_encoder_2=text_encoder_2,
394
+ pipeline=pipeline,
395
+ use_cpu_offload=use_cpu_offload,
396
+ device=device,
397
+ logger=logger,
398
+ parallel_args=parallel_args
399
+ )
400
+
401
+ self.pipeline = self.load_diffusion_pipeline(
402
+ args=args,
403
+ vae=self.vae,
404
+ text_encoder=self.text_encoder,
405
+ text_encoder_2=self.text_encoder_2,
406
+ model=self.model,
407
+ device=self.device,
408
+ )
409
+
410
+ self.default_negative_prompt = NEGATIVE_PROMPT
411
+
412
+ def load_diffusion_pipeline(
413
+ self,
414
+ args,
415
+ vae,
416
+ text_encoder,
417
+ text_encoder_2,
418
+ model,
419
+ scheduler=None,
420
+ device=None,
421
+ progress_bar_config=None,
422
+ data_type="video",
423
+ ):
424
+ """Load the denoising scheduler for inference."""
425
+ if scheduler is None:
426
+ if args.denoise_type == "flow":
427
+ scheduler = FlowMatchDiscreteScheduler(
428
+ shift=args.flow_shift,
429
+ reverse=args.flow_reverse,
430
+ solver=args.flow_solver,
431
+ )
432
+ else:
433
+ raise ValueError(f"Invalid denoise type {args.denoise_type}")
434
+
435
+ pipeline = HunyuanVideoPipeline(
436
+ vae=vae,
437
+ text_encoder=text_encoder,
438
+ text_encoder_2=text_encoder_2,
439
+ transformer=model,
440
+ scheduler=scheduler,
441
+ progress_bar_config=progress_bar_config,
442
+ args=args,
443
+ )
444
+ # if self.use_cpu_offload:
445
+ # pipeline.enable_sequential_cpu_offload()
446
+ # else:
447
+ # pipeline = pipeline.to(device)
448
+
449
+ return pipeline
450
+
451
+ def get_rotary_pos_embed(self, video_length, height, width, enable_riflex = False):
452
+ target_ndim = 3
453
+ ndim = 5 - 2
454
+ # 884
455
+ if "884" in self.args.vae:
456
+ latents_size = [(video_length - 1) // 4 + 1, height // 8, width // 8]
457
+ elif "888" in self.args.vae:
458
+ latents_size = [(video_length - 1) // 8 + 1, height // 8, width // 8]
459
+ else:
460
+ latents_size = [video_length, height // 8, width // 8]
461
+
462
+ if isinstance(self.model.patch_size, int):
463
+ assert all(s % self.model.patch_size == 0 for s in latents_size), (
464
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.model.patch_size}), "
465
+ f"but got {latents_size}."
466
+ )
467
+ rope_sizes = [s // self.model.patch_size for s in latents_size]
468
+ elif isinstance(self.model.patch_size, list):
469
+ assert all(
470
+ s % self.model.patch_size[idx] == 0
471
+ for idx, s in enumerate(latents_size)
472
+ ), (
473
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.model.patch_size}), "
474
+ f"but got {latents_size}."
475
+ )
476
+ rope_sizes = [
477
+ s // self.model.patch_size[idx] for idx, s in enumerate(latents_size)
478
+ ]
479
+
480
+ if len(rope_sizes) != target_ndim:
481
+ rope_sizes = [1] * (target_ndim - len(rope_sizes)) + rope_sizes # time axis
482
+ head_dim = self.model.hidden_size // self.model.heads_num
483
+ rope_dim_list = self.model.rope_dim_list
484
+ if rope_dim_list is None:
485
+ rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)]
486
+ assert (
487
+ sum(rope_dim_list) == head_dim
488
+ ), "sum(rope_dim_list) should equal to head_dim of attention layer"
489
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
490
+ rope_dim_list,
491
+ rope_sizes,
492
+ theta=self.args.rope_theta,
493
+ use_real=True,
494
+ theta_rescale_factor=1,
495
+ L_test = (video_length - 1) // 4 + 1,
496
+ enable_riflex = enable_riflex
497
+ )
498
+ return freqs_cos, freqs_sin
499
+
500
+ @torch.no_grad()
501
+ def predict(
502
+ self,
503
+ prompt,
504
+ height=192,
505
+ width=336,
506
+ video_length=129,
507
+ seed=None,
508
+ negative_prompt=None,
509
+ infer_steps=50,
510
+ guidance_scale=6,
511
+ flow_shift=5.0,
512
+ embedded_guidance_scale=None,
513
+ batch_size=1,
514
+ num_videos_per_prompt=1,
515
+ enable_riflex = False,
516
+ **kwargs,
517
+ ):
518
+ """
519
+ Predict the image/video from the given text.
520
+
521
+ Args:
522
+ prompt (str or List[str]): The input text.
523
+ kwargs:
524
+ height (int): The height of the output video. Default is 192.
525
+ width (int): The width of the output video. Default is 336.
526
+ video_length (int): The frame number of the output video. Default is 129.
527
+ seed (int or List[str]): The random seed for the generation. Default is a random integer.
528
+ negative_prompt (str or List[str]): The negative text prompt. Default is an empty string.
529
+ guidance_scale (float): The guidance scale for the generation. Default is 6.0.
530
+ num_images_per_prompt (int): The number of images per prompt. Default is 1.
531
+ infer_steps (int): The number of inference steps. Default is 100.
532
+ """
533
+ if self.parallel_args['ulysses_degree'] > 1 or self.parallel_args['ring_degree'] > 1:
534
+ assert seed is not None, \
535
+ "You have to set a seed in the distributed environment, please rerun with --seed <your-seed>."
536
+
537
+ parallelize_transformer(self.pipeline)
538
+
539
+ out_dict = dict()
540
+
541
+ # ========================================================================
542
+ # Arguments: seed
543
+ # ========================================================================
544
+ if isinstance(seed, torch.Tensor):
545
+ seed = seed.tolist()
546
+ if seed is None:
547
+ seeds = [
548
+ random.randint(0, 1_000_000)
549
+ for _ in range(batch_size * num_videos_per_prompt)
550
+ ]
551
+ elif isinstance(seed, int):
552
+ seeds = [
553
+ seed + i
554
+ for _ in range(batch_size)
555
+ for i in range(num_videos_per_prompt)
556
+ ]
557
+ elif isinstance(seed, (list, tuple)):
558
+ if len(seed) == batch_size:
559
+ seeds = [
560
+ int(seed[i]) + j
561
+ for i in range(batch_size)
562
+ for j in range(num_videos_per_prompt)
563
+ ]
564
+ elif len(seed) == batch_size * num_videos_per_prompt:
565
+ seeds = [int(s) for s in seed]
566
+ else:
567
+ raise ValueError(
568
+ f"Length of seed must be equal to number of prompt(batch_size) or "
569
+ f"batch_size * num_videos_per_prompt ({batch_size} * {num_videos_per_prompt}), got {seed}."
570
+ )
571
+ else:
572
+ raise ValueError(
573
+ f"Seed must be an integer, a list of integers, or None, got {seed}."
574
+ )
575
+ generator = [torch.Generator(self.device).manual_seed(seed) for seed in seeds]
576
+ out_dict["seeds"] = seeds
577
+
578
+ # ========================================================================
579
+ # Arguments: target_width, target_height, target_video_length
580
+ # ========================================================================
581
+ if width <= 0 or height <= 0 or video_length <= 0:
582
+ raise ValueError(
583
+ f"`height` and `width` and `video_length` must be positive integers, got height={height}, width={width}, video_length={video_length}"
584
+ )
585
+ if (video_length - 1) % 4 != 0:
586
+ raise ValueError(
587
+ f"`video_length-1` must be a multiple of 4, got {video_length}"
588
+ )
589
+
590
+ logger.info(
591
+ f"Input (height, width, video_length) = ({height}, {width}, {video_length})"
592
+ )
593
+
594
+ target_height = align_to(height, 16)
595
+ target_width = align_to(width, 16)
596
+ target_video_length = video_length
597
+
598
+ out_dict["size"] = (target_height, target_width, target_video_length)
599
+
600
+ # ========================================================================
601
+ # Arguments: prompt, new_prompt, negative_prompt
602
+ # ========================================================================
603
+ if not isinstance(prompt, str):
604
+ raise TypeError(f"`prompt` must be a string, but got {type(prompt)}")
605
+ prompt = [prompt.strip()]
606
+
607
+ # negative prompt
608
+ if negative_prompt is None or negative_prompt == "":
609
+ negative_prompt = self.default_negative_prompt
610
+ if not isinstance(negative_prompt, str):
611
+ raise TypeError(
612
+ f"`negative_prompt` must be a string, but got {type(negative_prompt)}"
613
+ )
614
+ negative_prompt = [negative_prompt.strip()]
615
+
616
+ # ========================================================================
617
+ # Scheduler
618
+ # ========================================================================
619
+ scheduler = FlowMatchDiscreteScheduler(
620
+ shift=flow_shift,
621
+ reverse=self.args.flow_reverse,
622
+ solver=self.args.flow_solver
623
+ )
624
+ self.pipeline.scheduler = scheduler
625
+
626
+ # ========================================================================
627
+ # Build Rope freqs
628
+ # ========================================================================
629
+ freqs_cos, freqs_sin = self.get_rotary_pos_embed(
630
+ target_video_length, target_height, target_width, enable_riflex
631
+ )
632
+ n_tokens = freqs_cos.shape[0]
633
+
634
+ # ========================================================================
635
+ # Print infer args
636
+ # ========================================================================
637
+ debug_str = f"""
638
+ height: {target_height}
639
+ width: {target_width}
640
+ video_length: {target_video_length}
641
+ prompt: {prompt}
642
+ neg_prompt: {negative_prompt}
643
+ seed: {seed}
644
+ infer_steps: {infer_steps}
645
+ num_videos_per_prompt: {num_videos_per_prompt}
646
+ guidance_scale: {guidance_scale}
647
+ n_tokens: {n_tokens}
648
+ flow_shift: {flow_shift}
649
+ embedded_guidance_scale: {embedded_guidance_scale}"""
650
+ logger.debug(debug_str)
651
+
652
+ callback = kwargs.pop("callback", None)
653
+ callback_steps = kwargs.pop("callback_steps", None)
654
+
655
+ # ========================================================================
656
+ # Pipeline inference
657
+ # ========================================================================
658
+ start_time = time.time()
659
+ samples = self.pipeline(
660
+ prompt=prompt,
661
+ height=target_height,
662
+ width=target_width,
663
+ video_length=target_video_length,
664
+ num_inference_steps=infer_steps,
665
+ guidance_scale=guidance_scale,
666
+ negative_prompt=negative_prompt,
667
+ num_videos_per_prompt=num_videos_per_prompt,
668
+ generator=generator,
669
+ output_type="pil",
670
+ freqs_cis=(freqs_cos, freqs_sin),
671
+ n_tokens=n_tokens,
672
+ embedded_guidance_scale=embedded_guidance_scale,
673
+ data_type="video" if target_video_length > 1 else "image",
674
+ is_progress_bar=True,
675
+ vae_ver=self.args.vae,
676
+ enable_tiling=self.args.vae_tiling,
677
+ callback = callback,
678
+ callback_steps = callback_steps,
679
+ )[0]
680
+ out_dict["samples"] = samples
681
+ out_dict["prompts"] = prompt
682
+
683
+ gen_time = time.time() - start_time
684
+ logger.info(f"Success, time: {gen_time}")
685
+
686
+ return out_dict
hyvideo/modules/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .models import HYVideoDiffusionTransformer, HUNYUAN_VIDEO_CONFIG
2
+
3
+
4
+ def load_model(args, in_channels, out_channels, factor_kwargs):
5
+ """load hunyuan video model
6
+
7
+ Args:
8
+ args (dict): model args
9
+ in_channels (int): input channels number
10
+ out_channels (int): output channels number
11
+ factor_kwargs (dict): factor kwargs
12
+
13
+ Returns:
14
+ model (nn.Module): The hunyuan video model
15
+ """
16
+ if args.model in HUNYUAN_VIDEO_CONFIG.keys():
17
+ model = HYVideoDiffusionTransformer(
18
+ args,
19
+ in_channels=in_channels,
20
+ out_channels=out_channels,
21
+ **HUNYUAN_VIDEO_CONFIG[args.model],
22
+ **factor_kwargs,
23
+ )
24
+ return model
25
+ else:
26
+ raise NotImplementedError()
hyvideo/modules/activation_layers.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+
3
+
4
+ def get_activation_layer(act_type):
5
+ """get activation layer
6
+
7
+ Args:
8
+ act_type (str): the activation type
9
+
10
+ Returns:
11
+ torch.nn.functional: the activation layer
12
+ """
13
+ if act_type == "gelu":
14
+ return lambda: nn.GELU()
15
+ elif act_type == "gelu_tanh":
16
+ # Approximate `tanh` requires torch >= 1.13
17
+ return lambda: nn.GELU(approximate="tanh")
18
+ elif act_type == "relu":
19
+ return nn.ReLU
20
+ elif act_type == "silu":
21
+ return nn.SiLU
22
+ else:
23
+ raise ValueError(f"Unknown activation type: {act_type}")
hyvideo/modules/attenion.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.metadata
2
+ import math
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from importlib.metadata import version
8
+
9
+ def clear_list(l):
10
+ for i in range(len(l)):
11
+ l[i] = None
12
+
13
+ try:
14
+ import flash_attn
15
+ from flash_attn.flash_attn_interface import _flash_attn_forward
16
+ from flash_attn.flash_attn_interface import flash_attn_varlen_func
17
+ except ImportError:
18
+ flash_attn = None
19
+ flash_attn_varlen_func = None
20
+ _flash_attn_forward = None
21
+
22
+ try:
23
+ from xformers.ops import memory_efficient_attention
24
+ except ImportError:
25
+ memory_efficient_attention = None
26
+
27
+ try:
28
+ from sageattention import sageattn_varlen
29
+ def sageattn_varlen_wrapper(
30
+ q,
31
+ k,
32
+ v,
33
+ cu_seqlens_q,
34
+ cu_seqlens_kv,
35
+ max_seqlen_q,
36
+ max_seqlen_kv,
37
+ ):
38
+ return sageattn_varlen(q, k, v, cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv)
39
+ except ImportError:
40
+ sageattn_varlen_wrapper = None
41
+
42
+ try:
43
+ from sageattention import sageattn
44
+ @torch.compiler.disable()
45
+ def sageattn_wrapper(
46
+ qkv_list,
47
+ attention_length
48
+ ):
49
+ q,k, v = qkv_list
50
+ padding_length = q.shape[1] -attention_length
51
+ q = q[:, :attention_length, :, : ]
52
+ k = k[:, :attention_length, :, : ]
53
+ v = v[:, :attention_length, :, : ]
54
+
55
+ o = sageattn(q, k, v, tensor_layout="NHD")
56
+ del q, k ,v
57
+ clear_list(qkv_list)
58
+
59
+ if padding_length > 0:
60
+ o = torch.cat([o, torch.empty( (o.shape[0], padding_length, *o.shape[-2:]), dtype= o.dtype, device=o.device ) ], 1)
61
+
62
+ return o
63
+
64
+ except ImportError:
65
+ sageattn = None
66
+
67
+
68
+ def get_attention_modes():
69
+ ret = ["sdpa", "auto"]
70
+ if flash_attn != None:
71
+ ret.append("flash")
72
+ if memory_efficient_attention != None:
73
+ ret.append("xformers")
74
+ if sageattn_varlen_wrapper != None:
75
+ ret.append("sage")
76
+ if sageattn != None and version("sageattention").startswith("2") :
77
+ ret.append("sage2")
78
+
79
+ return ret
80
+
81
+
82
+
83
+ MEMORY_LAYOUT = {
84
+ "sdpa": (
85
+ lambda x: x.transpose(1, 2),
86
+ lambda x: x.transpose(1, 2),
87
+ ),
88
+ "xformers": (
89
+ lambda x: x,
90
+ lambda x: x,
91
+ ),
92
+ "sage2": (
93
+ lambda x: x,
94
+ lambda x: x,
95
+ ),
96
+ "sage": (
97
+ lambda x: x.view(x.shape[0] * x.shape[1], *x.shape[2:]),
98
+ lambda x: x,
99
+ ),
100
+ "flash": (
101
+ lambda x: x.view(x.shape[0] * x.shape[1], *x.shape[2:]),
102
+ lambda x: x,
103
+ ),
104
+ "torch": (
105
+ lambda x: x.transpose(1, 2),
106
+ lambda x: x.transpose(1, 2),
107
+ ),
108
+ "vanilla": (
109
+ lambda x: x.transpose(1, 2),
110
+ lambda x: x.transpose(1, 2),
111
+ ),
112
+ }
113
+
114
+ @torch.compiler.disable()
115
+ def sdpa_wrapper(
116
+ qkv_list,
117
+ attention_length
118
+ ):
119
+ q,k, v = qkv_list
120
+ padding_length = q.shape[2] -attention_length
121
+ q = q[:, :, :attention_length, :]
122
+ k = k[:, :, :attention_length, :]
123
+ v = v[:, :, :attention_length, :]
124
+
125
+ o = F.scaled_dot_product_attention(
126
+ q, k, v, attn_mask=None, is_causal=False
127
+ )
128
+ del q, k ,v
129
+ clear_list(qkv_list)
130
+
131
+ if padding_length > 0:
132
+ o = torch.cat([o, torch.empty( (*o.shape[:2], padding_length, o.shape[-1]), dtype= o.dtype, device=o.device ) ], 2)
133
+
134
+ return o
135
+
136
+ def get_cu_seqlens(text_mask, img_len):
137
+ """Calculate cu_seqlens_q, cu_seqlens_kv using text_mask and img_len
138
+
139
+ Args:
140
+ text_mask (torch.Tensor): the mask of text
141
+ img_len (int): the length of image
142
+
143
+ Returns:
144
+ torch.Tensor: the calculated cu_seqlens for flash attention
145
+ """
146
+ batch_size = text_mask.shape[0]
147
+ text_len = text_mask.sum(dim=1)
148
+ max_len = text_mask.shape[1] + img_len
149
+
150
+ cu_seqlens = torch.zeros([2 * batch_size + 1], dtype=torch.int32, device="cuda")
151
+
152
+ for i in range(batch_size):
153
+ s = text_len[i] + img_len
154
+ s1 = i * max_len + s
155
+ s2 = (i + 1) * max_len
156
+ cu_seqlens[2 * i + 1] = s1
157
+ cu_seqlens[2 * i + 2] = s2
158
+
159
+ return cu_seqlens
160
+
161
+
162
+ def attention(
163
+ qkv_list,
164
+ mode="flash",
165
+ drop_rate=0,
166
+ attn_mask=None,
167
+ causal=False,
168
+ cu_seqlens_q=None,
169
+ cu_seqlens_kv=None,
170
+ max_seqlen_q=None,
171
+ max_seqlen_kv=None,
172
+ batch_size=1,
173
+ ):
174
+ """
175
+ Perform QKV self attention.
176
+
177
+ Args:
178
+ q (torch.Tensor): Query tensor with shape [b, s, a, d], where a is the number of heads.
179
+ k (torch.Tensor): Key tensor with shape [b, s1, a, d]
180
+ v (torch.Tensor): Value tensor with shape [b, s1, a, d]
181
+ mode (str): Attention mode. Choose from 'self_flash', 'cross_flash', 'torch', and 'vanilla'.
182
+ drop_rate (float): Dropout rate in attention map. (default: 0)
183
+ attn_mask (torch.Tensor): Attention mask with shape [b, s1] (cross_attn), or [b, a, s, s1] (torch or vanilla).
184
+ (default: None)
185
+ causal (bool): Whether to use causal attention. (default: False)
186
+ cu_seqlens_q (torch.Tensor): dtype torch.int32. The cumulative sequence lengths of the sequences in the batch,
187
+ used to index into q.
188
+ cu_seqlens_kv (torch.Tensor): dtype torch.int32. The cumulative sequence lengths of the sequences in the batch,
189
+ used to index into kv.
190
+ max_seqlen_q (int): The maximum sequence length in the batch of q.
191
+ max_seqlen_kv (int): The maximum sequence length in the batch of k and v.
192
+
193
+ Returns:
194
+ torch.Tensor: Output tensor after self attention with shape [b, s, ad]
195
+ """
196
+ pre_attn_layout, post_attn_layout = MEMORY_LAYOUT[mode]
197
+ q , k , v = qkv_list
198
+ clear_list(qkv_list)
199
+ del qkv_list
200
+ padding_length = 0
201
+ # if attn_mask == None and mode == "sdpa":
202
+ # padding_length = q.shape[1] - cu_seqlens_q
203
+ # q = q[:, :cu_seqlens_q, ... ]
204
+ # k = k[:, :cu_seqlens_kv, ... ]
205
+ # v = v[:, :cu_seqlens_kv, ... ]
206
+
207
+ q = pre_attn_layout(q)
208
+ k = pre_attn_layout(k)
209
+ v = pre_attn_layout(v)
210
+
211
+ if mode == "torch":
212
+ if attn_mask is not None and attn_mask.dtype != torch.bool:
213
+ attn_mask = attn_mask.to(q.dtype)
214
+ x = F.scaled_dot_product_attention(
215
+ q, k, v, attn_mask=attn_mask, dropout_p=drop_rate, is_causal=causal
216
+ )
217
+
218
+ elif mode == "sdpa":
219
+ # if attn_mask is not None and attn_mask.dtype != torch.bool:
220
+ # attn_mask = attn_mask.to(q.dtype)
221
+ # x = F.scaled_dot_product_attention(
222
+ # q, k, v, attn_mask=attn_mask, dropout_p=drop_rate, is_causal=causal
223
+ # )
224
+ assert attn_mask==None
225
+ qkv_list = [q, k, v]
226
+ del q, k , v
227
+ x = sdpa_wrapper( qkv_list, cu_seqlens_q )
228
+
229
+ elif mode == "xformers":
230
+ x = memory_efficient_attention(
231
+ q, k, v , attn_bias= attn_mask
232
+ )
233
+
234
+ elif mode == "sage2":
235
+ qkv_list = [q, k, v]
236
+ del q, k , v
237
+ x = sageattn_wrapper(qkv_list, cu_seqlens_q)
238
+
239
+ elif mode == "sage":
240
+ x = sageattn_varlen_wrapper(
241
+ q,
242
+ k,
243
+ v,
244
+ cu_seqlens_q,
245
+ cu_seqlens_kv,
246
+ max_seqlen_q,
247
+ max_seqlen_kv,
248
+ )
249
+ # x with shape [(bxs), a, d]
250
+ x = x.view(
251
+ batch_size, max_seqlen_q, x.shape[-2], x.shape[-1]
252
+ ) # reshape x to [b, s, a, d]
253
+
254
+ elif mode == "flash":
255
+ x = flash_attn_varlen_func(
256
+ q,
257
+ k,
258
+ v,
259
+ cu_seqlens_q,
260
+ cu_seqlens_kv,
261
+ max_seqlen_q,
262
+ max_seqlen_kv,
263
+ )
264
+ # x with shape [(bxs), a, d]
265
+ x = x.view(
266
+ batch_size, max_seqlen_q, x.shape[-2], x.shape[-1]
267
+ ) # reshape x to [b, s, a, d]
268
+ elif mode == "vanilla":
269
+ scale_factor = 1 / math.sqrt(q.size(-1))
270
+
271
+ b, a, s, _ = q.shape
272
+ s1 = k.size(2)
273
+ attn_bias = torch.zeros(b, a, s, s1, dtype=q.dtype, device=q.device)
274
+ if causal:
275
+ # Only applied to self attention
276
+ assert (
277
+ attn_mask is None
278
+ ), "Causal mask and attn_mask cannot be used together"
279
+ temp_mask = torch.ones(b, a, s, s, dtype=torch.bool, device=q.device).tril(
280
+ diagonal=0
281
+ )
282
+ attn_bias.masked_fill_(temp_mask.logical_not(), float("-inf"))
283
+ attn_bias.to(q.dtype)
284
+
285
+ if attn_mask is not None:
286
+ if attn_mask.dtype == torch.bool:
287
+ attn_bias.masked_fill_(attn_mask.logical_not(), float("-inf"))
288
+ else:
289
+ attn_bias += attn_mask
290
+
291
+ # TODO: Maybe force q and k to be float32 to avoid numerical overflow
292
+ attn = (q @ k.transpose(-2, -1)) * scale_factor
293
+ attn += attn_bias
294
+ attn = attn.softmax(dim=-1)
295
+ attn = torch.dropout(attn, p=drop_rate, train=True)
296
+ x = attn @ v
297
+ else:
298
+ raise NotImplementedError(f"Unsupported attention mode: {mode}")
299
+
300
+ x = post_attn_layout(x)
301
+ b, s, a, d = x.shape
302
+ out = x.reshape(b, s, -1)
303
+ if padding_length > 0 :
304
+ out = torch.cat([out, torch.empty( (out.shape[0], padding_length, out.shape[2]), dtype= out.dtype, device=out.device ) ], 1)
305
+
306
+ return out
307
+
308
+
309
+ def parallel_attention(
310
+ hybrid_seq_parallel_attn,
311
+ q,
312
+ k,
313
+ v,
314
+ img_q_len,
315
+ img_kv_len,
316
+ cu_seqlens_q,
317
+ cu_seqlens_kv
318
+ ):
319
+ attn1 = hybrid_seq_parallel_attn(
320
+ None,
321
+ q[:, :img_q_len, :, :],
322
+ k[:, :img_kv_len, :, :],
323
+ v[:, :img_kv_len, :, :],
324
+ dropout_p=0.0,
325
+ causal=False,
326
+ joint_tensor_query=q[:,img_q_len:cu_seqlens_q[1]],
327
+ joint_tensor_key=k[:,img_kv_len:cu_seqlens_kv[1]],
328
+ joint_tensor_value=v[:,img_kv_len:cu_seqlens_kv[1]],
329
+ joint_strategy="rear",
330
+ )
331
+ if flash_attn.__version__ >= '2.7.0':
332
+ attn2, *_ = _flash_attn_forward(
333
+ q[:,cu_seqlens_q[1]:],
334
+ k[:,cu_seqlens_kv[1]:],
335
+ v[:,cu_seqlens_kv[1]:],
336
+ dropout_p=0.0,
337
+ softmax_scale=q.shape[-1] ** (-0.5),
338
+ causal=False,
339
+ window_size_left=-1,
340
+ window_size_right=-1,
341
+ softcap=0.0,
342
+ alibi_slopes=None,
343
+ return_softmax=False,
344
+ )
345
+ else:
346
+ attn2, *_ = _flash_attn_forward(
347
+ q[:,cu_seqlens_q[1]:],
348
+ k[:,cu_seqlens_kv[1]:],
349
+ v[:,cu_seqlens_kv[1]:],
350
+ dropout_p=0.0,
351
+ softmax_scale=q.shape[-1] ** (-0.5),
352
+ causal=False,
353
+ window_size=(-1, -1),
354
+ softcap=0.0,
355
+ alibi_slopes=None,
356
+ return_softmax=False,
357
+ )
358
+ attn = torch.cat([attn1, attn2], dim=1)
359
+ b, s, a, d = attn.shape
360
+ attn = attn.reshape(b, s, -1)
361
+
362
+ return attn
hyvideo/modules/embed_layers.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+ from einops import rearrange, repeat
5
+
6
+ from ..utils.helpers import to_2tuple
7
+
8
+
9
+ class PatchEmbed(nn.Module):
10
+ """2D Image to Patch Embedding
11
+
12
+ Image to Patch Embedding using Conv2d
13
+
14
+ A convolution based approach to patchifying a 2D image w/ embedding projection.
15
+
16
+ Based on the impl in https://github.com/google-research/vision_transformer
17
+
18
+ Hacked together by / Copyright 2020 Ross Wightman
19
+
20
+ Remove the _assert function in forward function to be compatible with multi-resolution images.
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ patch_size=16,
26
+ in_chans=3,
27
+ embed_dim=768,
28
+ norm_layer=None,
29
+ flatten=True,
30
+ bias=True,
31
+ dtype=None,
32
+ device=None,
33
+ ):
34
+ factory_kwargs = {"dtype": dtype, "device": device}
35
+ super().__init__()
36
+ patch_size = to_2tuple(patch_size)
37
+ self.patch_size = patch_size
38
+ self.flatten = flatten
39
+
40
+ self.proj = nn.Conv3d(
41
+ in_chans,
42
+ embed_dim,
43
+ kernel_size=patch_size,
44
+ stride=patch_size,
45
+ bias=bias,
46
+ **factory_kwargs
47
+ )
48
+ nn.init.xavier_uniform_(self.proj.weight.view(self.proj.weight.size(0), -1))
49
+ if bias:
50
+ nn.init.zeros_(self.proj.bias)
51
+
52
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
53
+
54
+ def forward(self, x):
55
+ x = self.proj(x)
56
+ if self.flatten:
57
+ x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
58
+ x = self.norm(x)
59
+ return x
60
+
61
+
62
+ class TextProjection(nn.Module):
63
+ """
64
+ Projects text embeddings. Also handles dropout for classifier-free guidance.
65
+
66
+ Adapted from https://github.com/PixArt-alpha/PixArt-alpha/blob/master/diffusion/model/nets/PixArt_blocks.py
67
+ """
68
+
69
+ def __init__(self, in_channels, hidden_size, act_layer, dtype=None, device=None):
70
+ factory_kwargs = {"dtype": dtype, "device": device}
71
+ super().__init__()
72
+ self.linear_1 = nn.Linear(
73
+ in_features=in_channels,
74
+ out_features=hidden_size,
75
+ bias=True,
76
+ **factory_kwargs
77
+ )
78
+ self.act_1 = act_layer()
79
+ self.linear_2 = nn.Linear(
80
+ in_features=hidden_size,
81
+ out_features=hidden_size,
82
+ bias=True,
83
+ **factory_kwargs
84
+ )
85
+
86
+ def forward(self, caption):
87
+ hidden_states = self.linear_1(caption)
88
+ hidden_states = self.act_1(hidden_states)
89
+ hidden_states = self.linear_2(hidden_states)
90
+ return hidden_states
91
+
92
+
93
+ def timestep_embedding(t, dim, max_period=10000):
94
+ """
95
+ Create sinusoidal timestep embeddings.
96
+
97
+ Args:
98
+ t (torch.Tensor): a 1-D Tensor of N indices, one per batch element. These may be fractional.
99
+ dim (int): the dimension of the output.
100
+ max_period (int): controls the minimum frequency of the embeddings.
101
+
102
+ Returns:
103
+ embedding (torch.Tensor): An (N, D) Tensor of positional embeddings.
104
+
105
+ .. ref_link: https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
106
+ """
107
+ half = dim // 2
108
+ freqs = torch.exp(
109
+ -math.log(max_period)
110
+ * torch.arange(start=0, end=half, dtype=torch.float32)
111
+ / half
112
+ ).to(device=t.device)
113
+ args = t[:, None].float() * freqs[None]
114
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
115
+ if dim % 2:
116
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
117
+ return embedding
118
+
119
+
120
+ class TimestepEmbedder(nn.Module):
121
+ """
122
+ Embeds scalar timesteps into vector representations.
123
+ """
124
+
125
+ def __init__(
126
+ self,
127
+ hidden_size,
128
+ act_layer,
129
+ frequency_embedding_size=256,
130
+ max_period=10000,
131
+ out_size=None,
132
+ dtype=None,
133
+ device=None,
134
+ ):
135
+ factory_kwargs = {"dtype": dtype, "device": device}
136
+ super().__init__()
137
+ self.frequency_embedding_size = frequency_embedding_size
138
+ self.max_period = max_period
139
+ if out_size is None:
140
+ out_size = hidden_size
141
+
142
+ self.mlp = nn.Sequential(
143
+ nn.Linear(
144
+ frequency_embedding_size, hidden_size, bias=True, **factory_kwargs
145
+ ),
146
+ act_layer(),
147
+ nn.Linear(hidden_size, out_size, bias=True, **factory_kwargs),
148
+ )
149
+ nn.init.normal_(self.mlp[0].weight, std=0.02)
150
+ nn.init.normal_(self.mlp[2].weight, std=0.02)
151
+
152
+ def forward(self, t):
153
+ t_freq = timestep_embedding(
154
+ t, self.frequency_embedding_size, self.max_period
155
+ ).type(self.mlp[0].weight.dtype)
156
+ t_emb = self.mlp(t_freq)
157
+ return t_emb
hyvideo/modules/mlp_layers.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modified from timm library:
2
+ # https://github.com/huggingface/pytorch-image-models/blob/648aaa41233ba83eb38faf5ba9d415d574823241/timm/layers/mlp.py#L13
3
+
4
+ from functools import partial
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+
9
+ from .modulate_layers import modulate
10
+ from ..utils.helpers import to_2tuple
11
+
12
+
13
+ class MLP(nn.Module):
14
+ """MLP as used in Vision Transformer, MLP-Mixer and related networks"""
15
+
16
+ def __init__(
17
+ self,
18
+ in_channels,
19
+ hidden_channels=None,
20
+ out_features=None,
21
+ act_layer=nn.GELU,
22
+ norm_layer=None,
23
+ bias=True,
24
+ drop=0.0,
25
+ use_conv=False,
26
+ device=None,
27
+ dtype=None,
28
+ ):
29
+ factory_kwargs = {"device": device, "dtype": dtype}
30
+ super().__init__()
31
+ out_features = out_features or in_channels
32
+ hidden_channels = hidden_channels or in_channels
33
+ bias = to_2tuple(bias)
34
+ drop_probs = to_2tuple(drop)
35
+ linear_layer = partial(nn.Conv2d, kernel_size=1) if use_conv else nn.Linear
36
+
37
+ self.fc1 = linear_layer(
38
+ in_channels, hidden_channels, bias=bias[0], **factory_kwargs
39
+ )
40
+ self.act = act_layer()
41
+ self.drop1 = nn.Dropout(drop_probs[0])
42
+ self.norm = (
43
+ norm_layer(hidden_channels, **factory_kwargs)
44
+ if norm_layer is not None
45
+ else nn.Identity()
46
+ )
47
+ self.fc2 = linear_layer(
48
+ hidden_channels, out_features, bias=bias[1], **factory_kwargs
49
+ )
50
+ self.drop2 = nn.Dropout(drop_probs[1])
51
+
52
+ def forward(self, x):
53
+ x = self.fc1(x)
54
+ x = self.act(x)
55
+ x = self.drop1(x)
56
+ x = self.norm(x)
57
+ x = self.fc2(x)
58
+ x = self.drop2(x)
59
+ return x
60
+
61
+ def apply_(self, x, divide = 4):
62
+ x_shape = x.shape
63
+ x = x.view(-1, x.shape[-1])
64
+ chunk_size = int(x_shape[1]/divide)
65
+ x_chunks = torch.split(x, chunk_size)
66
+ for i, x_chunk in enumerate(x_chunks):
67
+ mlp_chunk = self.fc1(x_chunk)
68
+ mlp_chunk = self.act(mlp_chunk)
69
+ mlp_chunk = self.drop1(mlp_chunk)
70
+ mlp_chunk = self.norm(mlp_chunk)
71
+ mlp_chunk = self.fc2(mlp_chunk)
72
+ x_chunk[...] = self.drop2(mlp_chunk)
73
+ return x
74
+
75
+ #
76
+ class MLPEmbedder(nn.Module):
77
+ """copied from https://github.com/black-forest-labs/flux/blob/main/src/flux/modules/layers.py"""
78
+ def __init__(self, in_dim: int, hidden_dim: int, device=None, dtype=None):
79
+ factory_kwargs = {"device": device, "dtype": dtype}
80
+ super().__init__()
81
+ self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True, **factory_kwargs)
82
+ self.silu = nn.SiLU()
83
+ self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True, **factory_kwargs)
84
+
85
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
86
+ return self.out_layer(self.silu(self.in_layer(x)))
87
+
88
+
89
+ class FinalLayer(nn.Module):
90
+ """The final layer of DiT."""
91
+
92
+ def __init__(
93
+ self, hidden_size, patch_size, out_channels, act_layer, device=None, dtype=None
94
+ ):
95
+ factory_kwargs = {"device": device, "dtype": dtype}
96
+ super().__init__()
97
+
98
+ # Just use LayerNorm for the final layer
99
+ self.norm_final = nn.LayerNorm(
100
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
101
+ )
102
+ if isinstance(patch_size, int):
103
+ self.linear = nn.Linear(
104
+ hidden_size,
105
+ patch_size * patch_size * out_channels,
106
+ bias=True,
107
+ **factory_kwargs
108
+ )
109
+ else:
110
+ self.linear = nn.Linear(
111
+ hidden_size,
112
+ patch_size[0] * patch_size[1] * patch_size[2] * out_channels,
113
+ bias=True,
114
+ )
115
+ nn.init.zeros_(self.linear.weight)
116
+ nn.init.zeros_(self.linear.bias)
117
+
118
+ # Here we don't distinguish between the modulate types. Just use the simple one.
119
+ self.adaLN_modulation = nn.Sequential(
120
+ act_layer(),
121
+ nn.Linear(hidden_size, 2 * hidden_size, bias=True, **factory_kwargs),
122
+ )
123
+ # Zero-initialize the modulation
124
+ nn.init.zeros_(self.adaLN_modulation[1].weight)
125
+ nn.init.zeros_(self.adaLN_modulation[1].bias)
126
+
127
+ def forward(self, x, c):
128
+ shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
129
+ x = modulate(self.norm_final(x), shift=shift, scale=scale)
130
+ x = self.linear(x)
131
+ return x
hyvideo/modules/models.py ADDED
@@ -0,0 +1,980 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Tuple, Optional, Union, Dict
2
+ from einops import rearrange
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+
8
+ from diffusers.models import ModelMixin
9
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
10
+
11
+ from .activation_layers import get_activation_layer
12
+ from .norm_layers import get_norm_layer
13
+ from .embed_layers import TimestepEmbedder, PatchEmbed, TextProjection
14
+ from .attenion import attention, parallel_attention, get_cu_seqlens
15
+ from .posemb_layers import apply_rotary_emb
16
+ from .mlp_layers import MLP, MLPEmbedder, FinalLayer
17
+ from .modulate_layers import ModulateDiT, modulate, modulate_, apply_gate_and_accumulate_
18
+ from .token_refiner import SingleTokenRefiner
19
+ import numpy as np
20
+
21
+
22
+ def get_linear_split_map():
23
+ hidden_size = 3072
24
+ split_linear_modules_map = {
25
+ "img_attn_qkv" : {"mapped_modules" : ["img_attn_q", "img_attn_k", "img_attn_v"] , "split_sizes": [hidden_size, hidden_size, hidden_size]},
26
+ "linear1" : {"mapped_modules" : ["linear1_attn_q", "linear1_attn_k", "linear1_attn_v", "linear1_mlp"] , "split_sizes": [hidden_size, hidden_size, hidden_size, 7*hidden_size- 3*hidden_size]}
27
+ }
28
+ return split_linear_modules_map
29
+ try:
30
+ from xformers.ops.fmha.attn_bias import BlockDiagonalPaddedKeysMask
31
+ except ImportError:
32
+ BlockDiagonalPaddedKeysMask = None
33
+
34
+ class MMDoubleStreamBlock(nn.Module):
35
+ """
36
+ A multimodal dit block with seperate modulation for
37
+ text and image/video, see more details (SD3): https://arxiv.org/abs/2403.03206
38
+ (Flux.1): https://github.com/black-forest-labs/flux
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ hidden_size: int,
44
+ heads_num: int,
45
+ mlp_width_ratio: float,
46
+ mlp_act_type: str = "gelu_tanh",
47
+ qk_norm: bool = True,
48
+ qk_norm_type: str = "rms",
49
+ qkv_bias: bool = False,
50
+ dtype: Optional[torch.dtype] = None,
51
+ device: Optional[torch.device] = None,
52
+ attention_mode: str = "sdpa",
53
+ ):
54
+ factory_kwargs = {"device": device, "dtype": dtype}
55
+ super().__init__()
56
+
57
+ self.attention_mode = attention_mode
58
+ self.deterministic = False
59
+ self.heads_num = heads_num
60
+ head_dim = hidden_size // heads_num
61
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
62
+
63
+ self.img_mod = ModulateDiT(
64
+ hidden_size,
65
+ factor=6,
66
+ act_layer=get_activation_layer("silu"),
67
+ **factory_kwargs,
68
+ )
69
+ self.img_norm1 = nn.LayerNorm(
70
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
71
+ )
72
+
73
+ self.img_attn_qkv = nn.Linear(
74
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
75
+ )
76
+ qk_norm_layer = get_norm_layer(qk_norm_type)
77
+ self.img_attn_q_norm = (
78
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
79
+ if qk_norm
80
+ else nn.Identity()
81
+ )
82
+ self.img_attn_k_norm = (
83
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
84
+ if qk_norm
85
+ else nn.Identity()
86
+ )
87
+ self.img_attn_proj = nn.Linear(
88
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
89
+ )
90
+
91
+ self.img_norm2 = nn.LayerNorm(
92
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
93
+ )
94
+ self.img_mlp = MLP(
95
+ hidden_size,
96
+ mlp_hidden_dim,
97
+ act_layer=get_activation_layer(mlp_act_type),
98
+ bias=True,
99
+ **factory_kwargs,
100
+ )
101
+
102
+ self.txt_mod = ModulateDiT(
103
+ hidden_size,
104
+ factor=6,
105
+ act_layer=get_activation_layer("silu"),
106
+ **factory_kwargs,
107
+ )
108
+ self.txt_norm1 = nn.LayerNorm(
109
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
110
+ )
111
+
112
+ self.txt_attn_qkv = nn.Linear(
113
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
114
+ )
115
+ self.txt_attn_q_norm = (
116
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
117
+ if qk_norm
118
+ else nn.Identity()
119
+ )
120
+ self.txt_attn_k_norm = (
121
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
122
+ if qk_norm
123
+ else nn.Identity()
124
+ )
125
+ self.txt_attn_proj = nn.Linear(
126
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
127
+ )
128
+
129
+ self.txt_norm2 = nn.LayerNorm(
130
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
131
+ )
132
+ self.txt_mlp = MLP(
133
+ hidden_size,
134
+ mlp_hidden_dim,
135
+ act_layer=get_activation_layer(mlp_act_type),
136
+ bias=True,
137
+ **factory_kwargs,
138
+ )
139
+ self.hybrid_seq_parallel_attn = None
140
+
141
+ def enable_deterministic(self):
142
+ self.deterministic = True
143
+
144
+ def disable_deterministic(self):
145
+ self.deterministic = False
146
+
147
+ def forward(
148
+ self,
149
+ img: torch.Tensor,
150
+ txt: torch.Tensor,
151
+ vec: torch.Tensor,
152
+ attn_mask = None,
153
+ cu_seqlens_q: Optional[torch.Tensor] = None,
154
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
155
+ max_seqlen_q: Optional[int] = None,
156
+ max_seqlen_kv: Optional[int] = None,
157
+ freqs_cis: tuple = None,
158
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
159
+ (
160
+ img_mod1_shift,
161
+ img_mod1_scale,
162
+ img_mod1_gate,
163
+ img_mod2_shift,
164
+ img_mod2_scale,
165
+ img_mod2_gate,
166
+ ) = self.img_mod(vec).chunk(6, dim=-1)
167
+ (
168
+ txt_mod1_shift,
169
+ txt_mod1_scale,
170
+ txt_mod1_gate,
171
+ txt_mod2_shift,
172
+ txt_mod2_scale,
173
+ txt_mod2_gate,
174
+ ) = self.txt_mod(vec).chunk(6, dim=-1)
175
+
176
+ ##### Enjoy this spagheti VRAM optimizations done by DeepBeepMeep !
177
+ # I am sure you are a nice person and as you copy this code, you will give me proper credits:
178
+ # Please link to https://github.com/deepbeepmeep/HunyuanVideoGP and @deepbeepmeep on twitter
179
+
180
+ # Prepare image for attention.
181
+ img_modulated = self.img_norm1(img)
182
+ img_modulated = img_modulated.to(torch.bfloat16)
183
+ modulate_( img_modulated, shift=img_mod1_shift, scale=img_mod1_scale )
184
+
185
+ shape = (*img_modulated.shape[:2], self.heads_num, int(img_modulated.shape[-1] / self.heads_num) )
186
+ img_q = self.img_attn_q(img_modulated).view(*shape)
187
+ img_k = self.img_attn_k(img_modulated).view(*shape)
188
+ img_v = self.img_attn_v(img_modulated).view(*shape)
189
+ del img_modulated
190
+
191
+ # Apply QK-Norm if needed
192
+ self.img_attn_q_norm.apply_(img_q).to(img_v)
193
+ img_q_len = img_q.shape[1]
194
+ self.img_attn_k_norm.apply_(img_k).to(img_v)
195
+ img_kv_len= img_k.shape[1]
196
+ batch_size = img_k.shape[0]
197
+ # Apply RoPE if needed.
198
+ if freqs_cis is not None:
199
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
200
+ assert (
201
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
202
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
203
+ img_q, img_k = img_qq, img_kk
204
+ del img_qq, img_kk
205
+ # Prepare txt for attention.
206
+ txt_modulated = self.txt_norm1(txt)
207
+ modulate_(txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale )
208
+
209
+ txt_qkv = self.txt_attn_qkv(txt_modulated)
210
+ del txt_modulated
211
+ txt_q, txt_k, txt_v = rearrange(
212
+ txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
213
+ )
214
+ del txt_qkv
215
+ # Apply QK-Norm if needed.
216
+ self.txt_attn_q_norm.apply_(txt_q).to(txt_v)
217
+ self.txt_attn_k_norm.apply_(txt_k).to(txt_v)
218
+
219
+ # Run actual attention.
220
+ q = torch.cat((img_q, txt_q), dim=1)
221
+ del img_q, txt_q
222
+ k = torch.cat((img_k, txt_k), dim=1)
223
+ del img_k, txt_k
224
+ v = torch.cat((img_v, txt_v), dim=1)
225
+ del img_v, txt_v
226
+
227
+ # attention computation start
228
+ if not self.hybrid_seq_parallel_attn:
229
+ qkv_list = [q,k,v]
230
+ del q, k, v
231
+
232
+ attn = attention(
233
+ qkv_list,
234
+ mode=self.attention_mode,
235
+ attn_mask=attn_mask,
236
+ cu_seqlens_q=cu_seqlens_q,
237
+ cu_seqlens_kv=cu_seqlens_kv,
238
+ max_seqlen_q=max_seqlen_q,
239
+ max_seqlen_kv=max_seqlen_kv,
240
+ batch_size=batch_size,
241
+ )
242
+ del qkv_list
243
+ else:
244
+ attn = parallel_attention(
245
+ self.hybrid_seq_parallel_attn,
246
+ q,
247
+ k,
248
+ v,
249
+ img_q_len= img_q_len,
250
+ img_kv_len= img_kv_len,
251
+ cu_seqlens_q=cu_seqlens_q,
252
+ cu_seqlens_kv=cu_seqlens_kv
253
+ )
254
+ del q, k, v
255
+
256
+ # attention computation end
257
+
258
+ img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
259
+ del attn
260
+ # Calculate the img bloks.
261
+ img_attn = self.img_attn_proj(img_attn)
262
+ apply_gate_and_accumulate_(img, img_attn, gate=img_mod1_gate)
263
+
264
+ del img_attn
265
+ img_modulated = self.img_norm2(img)
266
+ img_modulated = img_modulated.to(torch.bfloat16)
267
+ modulate_( img_modulated , shift=img_mod2_shift, scale=img_mod2_scale)
268
+
269
+ self.img_mlp.apply_(img_modulated)
270
+ apply_gate_and_accumulate_(img, img_modulated, gate=img_mod2_gate)
271
+
272
+ del img_modulated
273
+
274
+ # Calculate the txt bloks.
275
+ txt_attn = self.txt_attn_proj(txt_attn)
276
+ apply_gate_and_accumulate_(txt, txt_attn, gate=txt_mod1_gate)
277
+ del txt_attn
278
+ txt_modulated = self.txt_norm2(txt)
279
+ txt_modulated = txt_modulated.to(torch.bfloat16)
280
+ modulate_(txt_modulated, shift=txt_mod2_shift, scale=txt_mod2_scale)
281
+ txt_mlp = self.txt_mlp(txt_modulated) # should delete txt_modulated halfway in mlp
282
+ del txt_modulated
283
+ apply_gate_and_accumulate_(txt, txt_mlp, gate=txt_mod2_gate)
284
+ return img, txt
285
+
286
+
287
+ class MMSingleStreamBlock(nn.Module):
288
+ """
289
+ A DiT block with parallel linear layers as described in
290
+ https://arxiv.org/abs/2302.05442 and adapted modulation interface.
291
+ Also refer to (SD3): https://arxiv.org/abs/2403.03206
292
+ (Flux.1): https://github.com/black-forest-labs/flux
293
+ """
294
+
295
+ def __init__(
296
+ self,
297
+ hidden_size: int,
298
+ heads_num: int,
299
+ mlp_width_ratio: float = 4.0,
300
+ mlp_act_type: str = "gelu_tanh",
301
+ qk_norm: bool = True,
302
+ qk_norm_type: str = "rms",
303
+ qk_scale: float = None,
304
+ dtype: Optional[torch.dtype] = None,
305
+ device: Optional[torch.device] = None,
306
+ attention_mode: str = "sdpa",
307
+ ):
308
+ factory_kwargs = {"device": device, "dtype": dtype}
309
+ super().__init__()
310
+ self.attention_mode = attention_mode
311
+ self.deterministic = False
312
+ self.hidden_size = hidden_size
313
+ self.heads_num = heads_num
314
+ head_dim = hidden_size // heads_num
315
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
316
+ self.mlp_hidden_dim = mlp_hidden_dim
317
+ self.scale = qk_scale or head_dim ** -0.5
318
+
319
+ # qkv and mlp_in
320
+ self.linear1 = nn.Linear(
321
+ hidden_size, hidden_size * 3 + mlp_hidden_dim, **factory_kwargs
322
+ )
323
+ # proj and mlp_out
324
+ self.linear2 = nn.Linear(
325
+ hidden_size + mlp_hidden_dim, hidden_size, **factory_kwargs
326
+ )
327
+
328
+ qk_norm_layer = get_norm_layer(qk_norm_type)
329
+ self.q_norm = (
330
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
331
+ if qk_norm
332
+ else nn.Identity()
333
+ )
334
+ self.k_norm = (
335
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
336
+ if qk_norm
337
+ else nn.Identity()
338
+ )
339
+
340
+ self.pre_norm = nn.LayerNorm(
341
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
342
+ )
343
+
344
+ self.mlp_act = get_activation_layer(mlp_act_type)()
345
+ self.modulation = ModulateDiT(
346
+ hidden_size,
347
+ factor=3,
348
+ act_layer=get_activation_layer("silu"),
349
+ **factory_kwargs,
350
+ )
351
+ self.hybrid_seq_parallel_attn = None
352
+
353
+ def enable_deterministic(self):
354
+ self.deterministic = True
355
+
356
+ def disable_deterministic(self):
357
+ self.deterministic = False
358
+
359
+ def forward(
360
+ self,
361
+ # x: torch.Tensor,
362
+ img: torch.Tensor,
363
+ txt: torch.Tensor,
364
+ vec: torch.Tensor,
365
+ txt_len: int,
366
+ attn_mask= None,
367
+ cu_seqlens_q: Optional[torch.Tensor] = None,
368
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
369
+ max_seqlen_q: Optional[int] = None,
370
+ max_seqlen_kv: Optional[int] = None,
371
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
372
+
373
+ ) -> torch.Tensor:
374
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
375
+
376
+ ##### More spagheti VRAM optimizations done by DeepBeepMeep !
377
+ # I am sure you are a nice person and as you copy this code, you will give me proper credits:
378
+ # Please link to https://github.com/deepbeepmeep/HunyuanVideoGP and @deepbeepmeep on twitter
379
+
380
+ img_mod = self.pre_norm(img)
381
+ img_mod = img_mod.to(torch.bfloat16)
382
+ txt_mod = self.pre_norm(txt)
383
+ txt_mod = txt_mod.to(torch.bfloat16)
384
+
385
+
386
+ modulate_(img_mod, shift=mod_shift, scale=mod_scale)
387
+ modulate_(txt_mod, shift=mod_shift, scale=mod_scale)
388
+
389
+ shape = (*img_mod.shape[:2], self.heads_num, int(img_mod.shape[-1] / self.heads_num) )
390
+ img_q = self.linear1_attn_q(img_mod).view(*shape)
391
+ img_k = self.linear1_attn_k(img_mod).view(*shape)
392
+ img_v = self.linear1_attn_v(img_mod).view(*shape)
393
+
394
+ shape = (*txt_mod.shape[:2], self.heads_num, int(txt_mod.shape[-1] / self.heads_num) )
395
+ txt_q = self.linear1_attn_q(txt_mod).view(*shape)
396
+ txt_k = self.linear1_attn_k(txt_mod).view(*shape)
397
+ txt_v = self.linear1_attn_v(txt_mod).view(*shape)
398
+
399
+ batch_size = img_mod.shape[0]
400
+
401
+ # Apply QK-Norm if needed.
402
+ # q = self.q_norm(q).to(v)
403
+ self.q_norm.apply_(img_q)
404
+ self.k_norm.apply_(img_k)
405
+ self.q_norm.apply_(txt_q)
406
+ self.k_norm.apply_(txt_k)
407
+
408
+ # Apply RoPE if needed.
409
+ if freqs_cis is not None:
410
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
411
+ assert (
412
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
413
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
414
+ img_q, img_k = img_qq, img_kk
415
+ img_q_len=img_q.shape[1]
416
+ q = torch.cat((img_q, txt_q), dim=1)
417
+ del img_q, txt_q, img_qq,
418
+ k = torch.cat((img_k, txt_k), dim=1)
419
+ img_kv_len=img_k.shape[1]
420
+ del img_k, txt_k, img_kk
421
+
422
+ v = torch.cat((img_v, txt_v), dim=1)
423
+ del img_v, txt_v
424
+ # attention computation start
425
+ if not self.hybrid_seq_parallel_attn:
426
+ qkv_list = [q,k,v]
427
+ del q, k, v
428
+
429
+ attn = attention(
430
+ qkv_list,
431
+ mode=self.attention_mode,
432
+ attn_mask=attn_mask,
433
+ cu_seqlens_q=cu_seqlens_q,
434
+ cu_seqlens_kv=cu_seqlens_kv,
435
+ max_seqlen_q=max_seqlen_q,
436
+ max_seqlen_kv=max_seqlen_kv,
437
+ batch_size=batch_size,
438
+ )
439
+ del qkv_list
440
+ else:
441
+ attn = parallel_attention(
442
+ self.hybrid_seq_parallel_attn,
443
+ q,
444
+ k,
445
+ v,
446
+ img_q_len=img_q_len,
447
+ img_kv_len=img_kv_len,
448
+ cu_seqlens_q=cu_seqlens_q,
449
+ cu_seqlens_kv=cu_seqlens_kv
450
+ )
451
+ del q, k, v
452
+ # attention computation end
453
+
454
+ x_mod = torch.cat((img_mod, txt_mod), 1)
455
+ del img_mod, txt_mod
456
+ x_mod_shape = x_mod.shape
457
+ x_mod = x_mod.view(-1, x_mod.shape[-1])
458
+ chunk_size = int(x_mod_shape[1]/6)
459
+ x_chunks = torch.split(x_mod, chunk_size)
460
+ attn = attn.view(-1, attn.shape[-1])
461
+ attn_chunks =torch.split(attn, chunk_size)
462
+ for x_chunk, attn_chunk in zip(x_chunks, attn_chunks):
463
+ mlp_chunk = self.linear1_mlp(x_chunk)
464
+ mlp_chunk = self.mlp_act(mlp_chunk)
465
+ attn_mlp_chunk = torch.cat((attn_chunk, mlp_chunk), -1)
466
+ del attn_chunk, mlp_chunk
467
+ x_chunk[...] = self.linear2(attn_mlp_chunk)
468
+ del attn_mlp_chunk
469
+ x_mod = x_mod.view(x_mod_shape)
470
+
471
+ apply_gate_and_accumulate_(img, x_mod[:, :-txt_len, :], gate=mod_gate)
472
+ apply_gate_and_accumulate_(txt, x_mod[:, -txt_len:, :], gate=mod_gate)
473
+
474
+ return img, txt
475
+
476
+ class HYVideoDiffusionTransformer(ModelMixin, ConfigMixin):
477
+ """
478
+ HunyuanVideo Transformer backbone
479
+
480
+ Inherited from ModelMixin and ConfigMixin for compatibility with diffusers' sampler StableDiffusionPipeline.
481
+
482
+ Reference:
483
+ [1] Flux.1: https://github.com/black-forest-labs/flux
484
+ [2] MMDiT: http://arxiv.org/abs/2403.03206
485
+
486
+ Parameters
487
+ ----------
488
+ args: argparse.Namespace
489
+ The arguments parsed by argparse.
490
+ patch_size: list
491
+ The size of the patch.
492
+ in_channels: int
493
+ The number of input channels.
494
+ out_channels: int
495
+ The number of output channels.
496
+ hidden_size: int
497
+ The hidden size of the transformer backbone.
498
+ heads_num: int
499
+ The number of attention heads.
500
+ mlp_width_ratio: float
501
+ The ratio of the hidden size of the MLP in the transformer block.
502
+ mlp_act_type: str
503
+ The activation function of the MLP in the transformer block.
504
+ depth_double_blocks: int
505
+ The number of transformer blocks in the double blocks.
506
+ depth_single_blocks: int
507
+ The number of transformer blocks in the single blocks.
508
+ rope_dim_list: list
509
+ The dimension of the rotary embedding for t, h, w.
510
+ qkv_bias: bool
511
+ Whether to use bias in the qkv linear layer.
512
+ qk_norm: bool
513
+ Whether to use qk norm.
514
+ qk_norm_type: str
515
+ The type of qk norm.
516
+ guidance_embed: bool
517
+ Whether to use guidance embedding for distillation.
518
+ text_projection: str
519
+ The type of the text projection, default is single_refiner.
520
+ use_attention_mask: bool
521
+ Whether to use attention mask for text encoder.
522
+ dtype: torch.dtype
523
+ The dtype of the model.
524
+ device: torch.device
525
+ The device of the model.
526
+ """
527
+
528
+ @register_to_config
529
+ def __init__(
530
+ self,
531
+ args: Any,
532
+ patch_size: list = [1, 2, 2],
533
+ in_channels: int = 4, # Should be VAE.config.latent_channels.
534
+ out_channels: int = None,
535
+ hidden_size: int = 3072,
536
+ heads_num: int = 24,
537
+ mlp_width_ratio: float = 4.0,
538
+ mlp_act_type: str = "gelu_tanh",
539
+ mm_double_blocks_depth: int = 20,
540
+ mm_single_blocks_depth: int = 40,
541
+ rope_dim_list: List[int] = [16, 56, 56],
542
+ qkv_bias: bool = True,
543
+ qk_norm: bool = True,
544
+ qk_norm_type: str = "rms",
545
+ guidance_embed: bool = False, # For modulation.
546
+ text_projection: str = "single_refiner",
547
+ use_attention_mask: bool = True,
548
+ dtype: Optional[torch.dtype] = None,
549
+ device: Optional[torch.device] = None,
550
+ attention_mode: Optional[str] = "sdpa"
551
+ ):
552
+ factory_kwargs = {"device": device, "dtype": dtype}
553
+ super().__init__()
554
+
555
+ self.patch_size = patch_size
556
+ self.in_channels = in_channels
557
+ self.out_channels = in_channels if out_channels is None else out_channels
558
+ self.unpatchify_channels = self.out_channels
559
+ self.guidance_embed = guidance_embed
560
+ self.rope_dim_list = rope_dim_list
561
+ self.attention_mode = attention_mode
562
+
563
+ # Text projection. Default to linear projection.
564
+ # Alternative: TokenRefiner. See more details (LI-DiT): http://arxiv.org/abs/2406.11831
565
+ self.use_attention_mask = use_attention_mask
566
+ self.text_projection = text_projection
567
+
568
+ self.text_states_dim = args.text_states_dim
569
+ self.text_states_dim_2 = args.text_states_dim_2
570
+
571
+ if hidden_size % heads_num != 0:
572
+ raise ValueError(
573
+ f"Hidden size {hidden_size} must be divisible by heads_num {heads_num}"
574
+ )
575
+ pe_dim = hidden_size // heads_num
576
+ if sum(rope_dim_list) != pe_dim:
577
+ raise ValueError(
578
+ f"Got {rope_dim_list} but expected positional dim {pe_dim}"
579
+ )
580
+ self.hidden_size = hidden_size
581
+ self.heads_num = heads_num
582
+
583
+ # image projection
584
+ self.img_in = PatchEmbed(
585
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
586
+ )
587
+
588
+ # text projection
589
+ if self.text_projection == "linear":
590
+ self.txt_in = TextProjection(
591
+ self.text_states_dim,
592
+ self.hidden_size,
593
+ get_activation_layer("silu"),
594
+ **factory_kwargs,
595
+ )
596
+ elif self.text_projection == "single_refiner":
597
+ self.txt_in = SingleTokenRefiner(
598
+ self.text_states_dim, hidden_size, heads_num, depth=2, **factory_kwargs
599
+ )
600
+ else:
601
+ raise NotImplementedError(
602
+ f"Unsupported text_projection: {self.text_projection}"
603
+ )
604
+
605
+ # time modulation
606
+ self.time_in = TimestepEmbedder(
607
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
608
+ )
609
+
610
+ # text modulation
611
+ self.vector_in = MLPEmbedder(
612
+ self.text_states_dim_2, self.hidden_size, **factory_kwargs
613
+ )
614
+
615
+ # guidance modulation
616
+ self.guidance_in = (
617
+ TimestepEmbedder(
618
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
619
+ )
620
+ if guidance_embed
621
+ else None
622
+ )
623
+
624
+ # double blocks
625
+ self.double_blocks = nn.ModuleList(
626
+ [
627
+ MMDoubleStreamBlock(
628
+ self.hidden_size,
629
+ self.heads_num,
630
+ mlp_width_ratio=mlp_width_ratio,
631
+ mlp_act_type=mlp_act_type,
632
+ qk_norm=qk_norm,
633
+ qk_norm_type=qk_norm_type,
634
+ qkv_bias=qkv_bias,
635
+ attention_mode = attention_mode,
636
+ **factory_kwargs,
637
+ )
638
+ for _ in range(mm_double_blocks_depth)
639
+ ]
640
+ )
641
+
642
+ # single blocks
643
+ self.single_blocks = nn.ModuleList(
644
+ [
645
+ MMSingleStreamBlock(
646
+ self.hidden_size,
647
+ self.heads_num,
648
+ mlp_width_ratio=mlp_width_ratio,
649
+ mlp_act_type=mlp_act_type,
650
+ qk_norm=qk_norm,
651
+ qk_norm_type=qk_norm_type,
652
+ attention_mode = attention_mode,
653
+ **factory_kwargs,
654
+ )
655
+ for _ in range(mm_single_blocks_depth)
656
+ ]
657
+ )
658
+
659
+ self.final_layer = FinalLayer(
660
+ self.hidden_size,
661
+ self.patch_size,
662
+ self.out_channels,
663
+ get_activation_layer("silu"),
664
+ **factory_kwargs,
665
+ )
666
+
667
+ def enable_deterministic(self):
668
+ for block in self.double_blocks:
669
+ block.enable_deterministic()
670
+ for block in self.single_blocks:
671
+ block.enable_deterministic()
672
+
673
+ def disable_deterministic(self):
674
+ for block in self.double_blocks:
675
+ block.disable_deterministic()
676
+ for block in self.single_blocks:
677
+ block.disable_deterministic()
678
+
679
+ def forward(
680
+ self,
681
+ x: torch.Tensor,
682
+ t: torch.Tensor, # Should be in range(0, 1000).
683
+ text_states: torch.Tensor = None,
684
+ text_mask: torch.Tensor = None, # Now we don't use it.
685
+ text_states_2: Optional[torch.Tensor] = None, # Text embedding for modulation.
686
+ freqs_cos: Optional[torch.Tensor] = None,
687
+ freqs_sin: Optional[torch.Tensor] = None,
688
+ guidance: torch.Tensor = None, # Guidance for modulation, should be cfg_scale x 1000.
689
+ pipeline=None,
690
+ return_dict: bool = True,
691
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
692
+ out = {}
693
+ img = x
694
+ batch_no, _, ot, oh, ow = x.shape
695
+ del x
696
+ txt = text_states
697
+ tt, th, tw = (
698
+ ot // self.patch_size[0],
699
+ oh // self.patch_size[1],
700
+ ow // self.patch_size[2],
701
+ )
702
+
703
+ # Prepare modulation vectors.
704
+ vec = self.time_in(t)
705
+
706
+ # text modulation
707
+ vec = vec + self.vector_in(text_states_2)
708
+ del text_states_2
709
+ # guidance modulation
710
+ if self.guidance_embed:
711
+ if guidance is None:
712
+ raise ValueError(
713
+ "Didn't get guidance strength for guidance distilled model."
714
+ )
715
+
716
+ # our timestep_embedding is merged into guidance_in(TimestepEmbedder)
717
+ vec = vec + self.guidance_in(guidance)
718
+
719
+ # Embed image and text.
720
+ img = self.img_in(img)
721
+ if self.text_projection == "linear":
722
+ txt = self.txt_in(txt)
723
+ elif self.text_projection == "single_refiner":
724
+ txt = self.txt_in(txt, t, text_mask if self.use_attention_mask else None)
725
+ else:
726
+ raise NotImplementedError(
727
+ f"Unsupported text_projection: {self.text_projection}"
728
+ )
729
+
730
+ txt_seq_len = txt.shape[1]
731
+ img_seq_len = img.shape[1]
732
+
733
+ # Compute cu_squlens and max_seqlen for flash attention
734
+ # cu_seqlens_q = get_cu_seqlens(text_mask, img_seq_len)
735
+ # cu_seqlens_kv = cu_seqlens_q
736
+ max_seqlen_q = img_seq_len + txt_seq_len
737
+ max_seqlen_kv = max_seqlen_q
738
+
739
+ if self.attention_mode == "sdpa" or self.attention_mode == "sage2":
740
+ if batch_no == 1:
741
+ # newly improved masking code that doesn't require a cumbersome mask....
742
+ text_len = text_mask[0].sum().item()
743
+ total_len = text_len + img_seq_len
744
+ cu_seqlens_q = cu_seqlens_kv = total_len
745
+ attn_mask = None
746
+ else:
747
+ cu_seqlens_q, cu_seqlens_kv = None, None
748
+ # thanks to kijai (https://github.com/kijai/ComfyUI-HunyuanVideoWrapper/), for the original code to support sdpa
749
+ # Create a square boolean mask filled with False
750
+ attn_mask = torch.zeros((1, max_seqlen_q, max_seqlen_q), dtype=torch.bool, device=text_mask.device)
751
+
752
+ # Calculate the valid attention regions
753
+ text_len = text_mask[0].sum().item()
754
+ total_len = text_len + img_seq_len
755
+
756
+ # Allow attention to 6all tokens up to total_len
757
+ attn_mask[0, :total_len, :total_len] = True
758
+ elif self.attention_mode == "xformers":
759
+ text_len = text_mask[0].sum().item()
760
+ total_len = text_len + img_seq_len
761
+ cu_seqlens_q, cu_seqlens_kv = None, None
762
+ attn_mask = BlockDiagonalPaddedKeysMask.from_seqlens([total_len, max_seqlen_q- total_len ],max_seqlen_kv, [total_len, 0] )
763
+
764
+ else:
765
+ attn_mask = None
766
+ # Compute cu_squlens for flash and sage attention
767
+ cu_seqlens_q = get_cu_seqlens(text_mask, img_seq_len)
768
+ cu_seqlens_kv = cu_seqlens_q
769
+
770
+ freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None
771
+
772
+ if self.enable_teacache:
773
+ inp = img
774
+ vec_ = vec
775
+ (
776
+ img_mod1_shift,
777
+ img_mod1_scale,
778
+ _ ,
779
+ _ ,
780
+ _ ,
781
+ _ ,
782
+
783
+ ) = self.double_blocks[0].img_mod(vec_).chunk(6, dim=-1)
784
+ normed_inp = self.double_blocks[0].img_norm1(inp)
785
+ normed_inp = normed_inp.to(torch.bfloat16)
786
+ modulated_inp = modulate(
787
+ normed_inp, shift=img_mod1_shift, scale=img_mod1_scale
788
+ )
789
+
790
+ del normed_inp, img_mod1_shift, img_mod1_scale
791
+
792
+ if self.cnt == 0 or self.cnt == self.num_steps-1:
793
+ should_calc = True
794
+ self.accumulated_rel_l1_distance = 0
795
+ else:
796
+ coefficients = [7.33226126e+02, -4.01131952e+02, 6.75869174e+01, -3.14987800e+00, 9.61237896e-02]
797
+ rescale_func = np.poly1d(coefficients)
798
+ self.accumulated_rel_l1_distance += rescale_func(((modulated_inp-self.previous_modulated_input).abs().mean() / self.previous_modulated_input.abs().mean()).cpu().item())
799
+ if self.accumulated_rel_l1_distance < self.rel_l1_thresh:
800
+ should_calc = False
801
+ else:
802
+ should_calc = True
803
+ self.accumulated_rel_l1_distance = 0
804
+ self.previous_modulated_input = modulated_inp
805
+ self.cnt += 1
806
+ if self.cnt == self.num_steps:
807
+ self.cnt = 0
808
+
809
+ if self.enable_teacache:
810
+ if not should_calc:
811
+ img += self.previous_residual
812
+ else:
813
+ ori_img = img.clone()
814
+ # --------------------- Pass through DiT blocks ------------------------
815
+ for _, block in enumerate(self.double_blocks):
816
+ if pipeline._interrupt:
817
+ return None
818
+ double_block_args = [
819
+ img,
820
+ txt,
821
+ vec,
822
+ attn_mask,
823
+ cu_seqlens_q,
824
+ cu_seqlens_kv,
825
+ max_seqlen_q,
826
+ max_seqlen_kv,
827
+ freqs_cis,
828
+ ]
829
+
830
+ img, txt = block(*double_block_args)
831
+ double_block_args = None
832
+
833
+ # Merge txt and img to pass through single stream blocks.
834
+ # x = torch.cat((img, txt), 1)
835
+ # del img, txt
836
+ if len(self.single_blocks) > 0:
837
+ for _, block in enumerate(self.single_blocks):
838
+ if pipeline._interrupt:
839
+ return None
840
+ single_block_args = [
841
+ # x,
842
+ img,
843
+ txt,
844
+ vec,
845
+ txt_seq_len,
846
+ attn_mask,
847
+ cu_seqlens_q,
848
+ cu_seqlens_kv,
849
+ max_seqlen_q,
850
+ max_seqlen_kv,
851
+ (freqs_cos, freqs_sin),
852
+ ]
853
+
854
+ img, txt = block(*single_block_args)
855
+ single_block_args = None
856
+ # img = x[:, :img_seq_len, ...]
857
+ self.previous_residual = img - ori_img
858
+ else:
859
+ # --------------------- Pass through DiT blocks ------------------------
860
+ for _, block in enumerate(self.double_blocks):
861
+ if pipeline._interrupt:
862
+ return None
863
+
864
+ double_block_args = [
865
+ img,
866
+ txt,
867
+ vec,
868
+ attn_mask,
869
+ cu_seqlens_q,
870
+ cu_seqlens_kv,
871
+ max_seqlen_q,
872
+ max_seqlen_kv,
873
+ freqs_cis,
874
+ ]
875
+
876
+ img, txt = block(*double_block_args)
877
+
878
+ double_block_args = None
879
+
880
+ # Merge txt and img to pass through single stream blocks.
881
+ # x = torch.cat((img, txt), 1)
882
+ # del img, txt
883
+ if len(self.single_blocks) > 0:
884
+ for _, block in enumerate(self.single_blocks):
885
+ if pipeline._interrupt:
886
+ return None
887
+
888
+ single_block_args = [
889
+ # x,
890
+ img,
891
+ txt,
892
+ vec,
893
+ txt_seq_len,
894
+ attn_mask,
895
+ cu_seqlens_q,
896
+ cu_seqlens_kv,
897
+ max_seqlen_q,
898
+ max_seqlen_kv,
899
+ (freqs_cos, freqs_sin),
900
+ ]
901
+
902
+ img, txt = block(*single_block_args)
903
+
904
+ single_block_args = None
905
+ # img = x[:, :img_seq_len, ...]
906
+ del txt
907
+
908
+ # ---------------------------- Final layer ------------------------------
909
+ img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
910
+
911
+ img = self.unpatchify(img, tt, th, tw)
912
+ if return_dict:
913
+ out["x"] = img
914
+ return out
915
+ return img
916
+
917
+ def unpatchify(self, x, t, h, w):
918
+ """
919
+ x: (N, T, patch_size**2 * C)
920
+ imgs: (N, H, W, C)
921
+ """
922
+ c = self.unpatchify_channels
923
+ pt, ph, pw = self.patch_size
924
+ assert t * h * w == x.shape[1]
925
+
926
+ x = x.reshape(shape=(x.shape[0], t, h, w, c, pt, ph, pw))
927
+ x = torch.einsum("nthwcopq->nctohpwq", x)
928
+ imgs = x.reshape(shape=(x.shape[0], c, t * pt, h * ph, w * pw))
929
+
930
+ return imgs
931
+
932
+ def params_count(self):
933
+ counts = {
934
+ "double": sum(
935
+ [
936
+ sum(p.numel() for p in block.img_attn_qkv.parameters())
937
+ + sum(p.numel() for p in block.img_attn_proj.parameters())
938
+ + sum(p.numel() for p in block.img_mlp.parameters())
939
+ + sum(p.numel() for p in block.txt_attn_qkv.parameters())
940
+ + sum(p.numel() for p in block.txt_attn_proj.parameters())
941
+ + sum(p.numel() for p in block.txt_mlp.parameters())
942
+ for block in self.double_blocks
943
+ ]
944
+ ),
945
+ "single": sum(
946
+ [
947
+ sum(p.numel() for p in block.linear1.parameters())
948
+ + sum(p.numel() for p in block.linear2.parameters())
949
+ for block in self.single_blocks
950
+ ]
951
+ ),
952
+ "total": sum(p.numel() for p in self.parameters()),
953
+ }
954
+ counts["attn+mlp"] = counts["double"] + counts["single"]
955
+ return counts
956
+
957
+
958
+ #################################################################################
959
+ # HunyuanVideo Configs #
960
+ #################################################################################
961
+
962
+ HUNYUAN_VIDEO_CONFIG = {
963
+ "HYVideo-T/2": {
964
+ "mm_double_blocks_depth": 20,
965
+ "mm_single_blocks_depth": 40,
966
+ "rope_dim_list": [16, 56, 56],
967
+ "hidden_size": 3072,
968
+ "heads_num": 24,
969
+ "mlp_width_ratio": 4,
970
+ },
971
+ "HYVideo-T/2-cfgdistill": {
972
+ "mm_double_blocks_depth": 20,
973
+ "mm_single_blocks_depth": 40,
974
+ "rope_dim_list": [16, 56, 56],
975
+ "hidden_size": 3072,
976
+ "heads_num": 24,
977
+ "mlp_width_ratio": 4,
978
+ "guidance_embed": True,
979
+ },
980
+ }
hyvideo/modules/modulate_layers.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+
7
+ class ModulateDiT(nn.Module):
8
+ """Modulation layer for DiT."""
9
+ def __init__(
10
+ self,
11
+ hidden_size: int,
12
+ factor: int,
13
+ act_layer: Callable,
14
+ dtype=None,
15
+ device=None,
16
+ ):
17
+ factory_kwargs = {"dtype": dtype, "device": device}
18
+ super().__init__()
19
+ self.act = act_layer()
20
+ self.linear = nn.Linear(
21
+ hidden_size, factor * hidden_size, bias=True, **factory_kwargs
22
+ )
23
+ # Zero-initialize the modulation
24
+ nn.init.zeros_(self.linear.weight)
25
+ nn.init.zeros_(self.linear.bias)
26
+
27
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
28
+ return self.linear(self.act(x))
29
+
30
+
31
+ def modulate(x, shift=None, scale=None):
32
+ """modulate by shift and scale
33
+
34
+ Args:
35
+ x (torch.Tensor): input tensor.
36
+ shift (torch.Tensor, optional): shift tensor. Defaults to None.
37
+ scale (torch.Tensor, optional): scale tensor. Defaults to None.
38
+
39
+ Returns:
40
+ torch.Tensor: the output tensor after modulate.
41
+ """
42
+ if scale is None and shift is None:
43
+ return x
44
+ elif shift is None:
45
+ return x * (1 + scale.unsqueeze(1))
46
+ elif scale is None:
47
+ return x + shift.unsqueeze(1)
48
+ else:
49
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
50
+
51
+ def modulate_(x, shift=None, scale=None):
52
+
53
+ if scale is None and shift is None:
54
+ return x
55
+ elif shift is None:
56
+ scale = scale + 1
57
+ scale = scale.unsqueeze(1)
58
+ return x.mul_(scale)
59
+ elif scale is None:
60
+ return x + shift.unsqueeze(1)
61
+ else:
62
+ scale = scale + 1
63
+ scale = scale.unsqueeze(1)
64
+ # return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
65
+ torch.addcmul(shift.unsqueeze(1), x, scale, out =x )
66
+ return x
67
+
68
+ def apply_gate(x, gate=None, tanh=False):
69
+ """AI is creating summary for apply_gate
70
+
71
+ Args:
72
+ x (torch.Tensor): input tensor.
73
+ gate (torch.Tensor, optional): gate tensor. Defaults to None.
74
+ tanh (bool, optional): whether to use tanh function. Defaults to False.
75
+
76
+ Returns:
77
+ torch.Tensor: the output tensor after apply gate.
78
+ """
79
+ if gate is None:
80
+ return x
81
+ if tanh:
82
+ return x * gate.unsqueeze(1).tanh()
83
+ else:
84
+ return x * gate.unsqueeze(1)
85
+
86
+ def apply_gate_and_accumulate_(accumulator, x, gate=None, tanh=False):
87
+ if gate is None:
88
+ return accumulator
89
+ if tanh:
90
+ return accumulator.addcmul_(x, gate.unsqueeze(1).tanh())
91
+ else:
92
+ return accumulator.addcmul_(x, gate.unsqueeze(1))
93
+
94
+ def ckpt_wrapper(module):
95
+ def ckpt_forward(*inputs):
96
+ outputs = module(*inputs)
97
+ return outputs
98
+
99
+ return ckpt_forward
hyvideo/modules/norm_layers.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+
5
+ class RMSNorm(nn.Module):
6
+ def __init__(
7
+ self,
8
+ dim: int,
9
+ elementwise_affine=True,
10
+ eps: float = 1e-6,
11
+ device=None,
12
+ dtype=None,
13
+ ):
14
+ """
15
+ Initialize the RMSNorm normalization layer.
16
+
17
+ Args:
18
+ dim (int): The dimension of the input tensor.
19
+ eps (float, optional): A small value added to the denominator for numerical stability. Default is 1e-6.
20
+
21
+ Attributes:
22
+ eps (float): A small value added to the denominator for numerical stability.
23
+ weight (nn.Parameter): Learnable scaling parameter.
24
+
25
+ """
26
+ factory_kwargs = {"device": device, "dtype": dtype}
27
+ super().__init__()
28
+ self.eps = eps
29
+ if elementwise_affine:
30
+ self.weight = nn.Parameter(torch.ones(dim, **factory_kwargs))
31
+
32
+ def _norm(self, x):
33
+ """
34
+ Apply the RMSNorm normalization to the input tensor.
35
+
36
+ Args:
37
+ x (torch.Tensor): The input tensor.
38
+
39
+ Returns:
40
+ torch.Tensor: The normalized tensor.
41
+
42
+ """
43
+
44
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
45
+
46
+ def forward(self, x):
47
+ """
48
+ Forward pass through the RMSNorm layer.
49
+
50
+ Args:
51
+ x (torch.Tensor): The input tensor.
52
+
53
+ Returns:
54
+ torch.Tensor: The output tensor after applying RMSNorm.
55
+
56
+ """
57
+ output = self._norm(x.float()).type_as(x)
58
+ if hasattr(self, "weight"):
59
+ output = output * self.weight
60
+ return output
61
+
62
+ def apply_(self, x):
63
+ y = x.pow(2).mean(-1, keepdim=True)
64
+ y.add_(self.eps)
65
+ y.rsqrt_()
66
+ x.mul_(y)
67
+ del y
68
+ if hasattr(self, "weight"):
69
+ x.mul_(self.weight)
70
+ return x
71
+
72
+
73
+ def get_norm_layer(norm_layer):
74
+ """
75
+ Get the normalization layer.
76
+
77
+ Args:
78
+ norm_layer (str): The type of normalization layer.
79
+
80
+ Returns:
81
+ norm_layer (nn.Module): The normalization layer.
82
+ """
83
+ if norm_layer == "layer":
84
+ return nn.LayerNorm
85
+ elif norm_layer == "rms":
86
+ return RMSNorm
87
+ else:
88
+ raise NotImplementedError(f"Norm layer {norm_layer} is not implemented")
hyvideo/modules/posemb_layers.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from typing import Union, Tuple, List, Optional
3
+ import numpy as np
4
+
5
+
6
+ ###### Thanks to the RifleX project (https://github.com/thu-ml/RIFLEx/) for this alternative pos embed for long videos
7
+ #
8
+ def get_1d_rotary_pos_embed_riflex(
9
+ dim: int,
10
+ pos: Union[np.ndarray, int],
11
+ theta: float = 10000.0,
12
+ use_real=False,
13
+ k: Optional[int] = None,
14
+ L_test: Optional[int] = None,
15
+ ):
16
+ """
17
+ RIFLEx: Precompute the frequency tensor for complex exponentials (cis) with given dimensions.
18
+
19
+ This function calculates a frequency tensor with complex exponentials using the given dimension 'dim' and the end
20
+ index 'end'. The 'theta' parameter scales the frequencies. The returned tensor contains complex values in complex64
21
+ data type.
22
+
23
+ Args:
24
+ dim (`int`): Dimension of the frequency tensor.
25
+ pos (`np.ndarray` or `int`): Position indices for the frequency tensor. [S] or scalar
26
+ theta (`float`, *optional*, defaults to 10000.0):
27
+ Scaling factor for frequency computation. Defaults to 10000.0.
28
+ use_real (`bool`, *optional*):
29
+ If True, return real part and imaginary part separately. Otherwise, return complex numbers.
30
+ k (`int`, *optional*, defaults to None): the index for the intrinsic frequency in RoPE
31
+ L_test (`int`, *optional*, defaults to None): the number of frames for inference
32
+ Returns:
33
+ `torch.Tensor`: Precomputed frequency tensor with complex exponentials. [S, D/2]
34
+ """
35
+ assert dim % 2 == 0
36
+
37
+ if isinstance(pos, int):
38
+ pos = torch.arange(pos)
39
+ if isinstance(pos, np.ndarray):
40
+ pos = torch.from_numpy(pos) # type: ignore # [S]
41
+
42
+ freqs = 1.0 / (
43
+ theta ** (torch.arange(0, dim, 2, device=pos.device)[: (dim // 2)].float() / dim)
44
+ ) # [D/2]
45
+
46
+ # === Riflex modification start ===
47
+ # Reduce the intrinsic frequency to stay within a single period after extrapolation (see Eq. (8)).
48
+ # Empirical observations show that a few videos may exhibit repetition in the tail frames.
49
+ # To be conservative, we multiply by 0.9 to keep the extrapolated length below 90% of a single period.
50
+ if k is not None:
51
+ freqs[k-1] = 0.9 * 2 * torch.pi / L_test
52
+ # === Riflex modification end ===
53
+
54
+ freqs = torch.outer(pos, freqs) # type: ignore # [S, D/2]
55
+ if use_real:
56
+ freqs_cos = freqs.cos().repeat_interleave(2, dim=1).float() # [S, D]
57
+ freqs_sin = freqs.sin().repeat_interleave(2, dim=1).float() # [S, D]
58
+ return freqs_cos, freqs_sin
59
+ else:
60
+ # lumina
61
+ freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64 # [S, D/2]
62
+ return freqs_cis
63
+
64
+ def identify_k( b: float, d: int, N: int):
65
+ """
66
+ This function identifies the index of the intrinsic frequency component in a RoPE-based pre-trained diffusion transformer.
67
+
68
+ Args:
69
+ b (`float`): The base frequency for RoPE.
70
+ d (`int`): Dimension of the frequency tensor
71
+ N (`int`): the first observed repetition frame in latent space
72
+ Returns:
73
+ k (`int`): the index of intrinsic frequency component
74
+ N_k (`int`): the period of intrinsic frequency component in latent space
75
+ Example:
76
+ In HunyuanVideo, b=256 and d=16, the repetition occurs approximately 8s (N=48 in latent space).
77
+ k, N_k = identify_k(b=256, d=16, N=48)
78
+ In this case, the intrinsic frequency index k is 4, and the period N_k is 50.
79
+ """
80
+
81
+ # Compute the period of each frequency in RoPE according to Eq.(4)
82
+ periods = []
83
+ for j in range(1, d // 2 + 1):
84
+ theta_j = 1.0 / (b ** (2 * (j - 1) / d))
85
+ N_j = round(2 * torch.pi / theta_j)
86
+ periods.append(N_j)
87
+
88
+ # Identify the intrinsic frequency whose period is closed to N(see Eq.(7))
89
+ diffs = [abs(N_j - N) for N_j in periods]
90
+ k = diffs.index(min(diffs)) + 1
91
+ N_k = periods[k-1]
92
+ return k, N_k
93
+
94
+ def _to_tuple(x, dim=2):
95
+ if isinstance(x, int):
96
+ return (x,) * dim
97
+ elif len(x) == dim:
98
+ return x
99
+ else:
100
+ raise ValueError(f"Expected length {dim} or int, but got {x}")
101
+
102
+
103
+ def get_meshgrid_nd(start, *args, dim=2):
104
+ """
105
+ Get n-D meshgrid with start, stop and num.
106
+
107
+ Args:
108
+ start (int or tuple): If len(args) == 0, start is num; If len(args) == 1, start is start, args[0] is stop,
109
+ step is 1; If len(args) == 2, start is start, args[0] is stop, args[1] is num. For n-dim, start/stop/num
110
+ should be int or n-tuple. If n-tuple is provided, the meshgrid will be stacked following the dim order in
111
+ n-tuples.
112
+ *args: See above.
113
+ dim (int): Dimension of the meshgrid. Defaults to 2.
114
+
115
+ Returns:
116
+ grid (np.ndarray): [dim, ...]
117
+ """
118
+ if len(args) == 0:
119
+ # start is grid_size
120
+ num = _to_tuple(start, dim=dim)
121
+ start = (0,) * dim
122
+ stop = num
123
+ elif len(args) == 1:
124
+ # start is start, args[0] is stop, step is 1
125
+ start = _to_tuple(start, dim=dim)
126
+ stop = _to_tuple(args[0], dim=dim)
127
+ num = [stop[i] - start[i] for i in range(dim)]
128
+ elif len(args) == 2:
129
+ # start is start, args[0] is stop, args[1] is num
130
+ start = _to_tuple(start, dim=dim) # Left-Top eg: 12,0
131
+ stop = _to_tuple(args[0], dim=dim) # Right-Bottom eg: 20,32
132
+ num = _to_tuple(args[1], dim=dim) # Target Size eg: 32,124
133
+ else:
134
+ raise ValueError(f"len(args) should be 0, 1 or 2, but got {len(args)}")
135
+
136
+ # PyTorch implement of np.linspace(start[i], stop[i], num[i], endpoint=False)
137
+ axis_grid = []
138
+ for i in range(dim):
139
+ a, b, n = start[i], stop[i], num[i]
140
+ g = torch.linspace(a, b, n + 1, dtype=torch.float32)[:n]
141
+ axis_grid.append(g)
142
+ grid = torch.meshgrid(*axis_grid, indexing="ij") # dim x [W, H, D]
143
+ grid = torch.stack(grid, dim=0) # [dim, W, H, D]
144
+
145
+ return grid
146
+
147
+
148
+ #################################################################################
149
+ # Rotary Positional Embedding Functions #
150
+ #################################################################################
151
+ # https://github.com/meta-llama/llama/blob/be327c427cc5e89cc1d3ab3d3fec4484df771245/llama/model.py#L80
152
+
153
+
154
+ def reshape_for_broadcast(
155
+ freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]],
156
+ x: torch.Tensor,
157
+ head_first=False,
158
+ ):
159
+ """
160
+ Reshape frequency tensor for broadcasting it with another tensor.
161
+
162
+ This function reshapes the frequency tensor to have the same shape as the target tensor 'x'
163
+ for the purpose of broadcasting the frequency tensor during element-wise operations.
164
+
165
+ Notes:
166
+ When using FlashMHAModified, head_first should be False.
167
+ When using Attention, head_first should be True.
168
+
169
+ Args:
170
+ freqs_cis (Union[torch.Tensor, Tuple[torch.Tensor]]): Frequency tensor to be reshaped.
171
+ x (torch.Tensor): Target tensor for broadcasting compatibility.
172
+ head_first (bool): head dimension first (except batch dim) or not.
173
+
174
+ Returns:
175
+ torch.Tensor: Reshaped frequency tensor.
176
+
177
+ Raises:
178
+ AssertionError: If the frequency tensor doesn't match the expected shape.
179
+ AssertionError: If the target tensor 'x' doesn't have the expected number of dimensions.
180
+ """
181
+ ndim = x.ndim
182
+ assert 0 <= 1 < ndim
183
+
184
+ if isinstance(freqs_cis, tuple):
185
+ # freqs_cis: (cos, sin) in real space
186
+ if head_first:
187
+ assert freqs_cis[0].shape == (
188
+ x.shape[-2],
189
+ x.shape[-1],
190
+ ), f"freqs_cis shape {freqs_cis[0].shape} does not match x shape {x.shape}"
191
+ shape = [
192
+ d if i == ndim - 2 or i == ndim - 1 else 1
193
+ for i, d in enumerate(x.shape)
194
+ ]
195
+ else:
196
+ assert freqs_cis[0].shape == (
197
+ x.shape[1],
198
+ x.shape[-1],
199
+ ), f"freqs_cis shape {freqs_cis[0].shape} does not match x shape {x.shape}"
200
+ shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
201
+ return freqs_cis[0].view(*shape), freqs_cis[1].view(*shape)
202
+ else:
203
+ # freqs_cis: values in complex space
204
+ if head_first:
205
+ assert freqs_cis.shape == (
206
+ x.shape[-2],
207
+ x.shape[-1],
208
+ ), f"freqs_cis shape {freqs_cis.shape} does not match x shape {x.shape}"
209
+ shape = [
210
+ d if i == ndim - 2 or i == ndim - 1 else 1
211
+ for i, d in enumerate(x.shape)
212
+ ]
213
+ else:
214
+ assert freqs_cis.shape == (
215
+ x.shape[1],
216
+ x.shape[-1],
217
+ ), f"freqs_cis shape {freqs_cis.shape} does not match x shape {x.shape}"
218
+ shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
219
+ return freqs_cis.view(*shape)
220
+
221
+
222
+ def rotate_half(x):
223
+ x_real, x_imag = (
224
+ x.float().reshape(*x.shape[:-1], -1, 2).unbind(-1)
225
+ ) # [B, S, H, D//2]
226
+ return torch.stack([-x_imag, x_real], dim=-1).flatten(3)
227
+
228
+
229
+ def apply_rotary_emb(
230
+ xq: torch.Tensor,
231
+ xk: torch.Tensor,
232
+ freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
233
+ head_first: bool = False,
234
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
235
+ """
236
+ Apply rotary embeddings to input tensors using the given frequency tensor.
237
+
238
+ This function applies rotary embeddings to the given query 'xq' and key 'xk' tensors using the provided
239
+ frequency tensor 'freqs_cis'. The input tensors are reshaped as complex numbers, and the frequency tensor
240
+ is reshaped for broadcasting compatibility. The resulting tensors contain rotary embeddings and are
241
+ returned as real tensors.
242
+
243
+ Args:
244
+ xq (torch.Tensor): Query tensor to apply rotary embeddings. [B, S, H, D]
245
+ xk (torch.Tensor): Key tensor to apply rotary embeddings. [B, S, H, D]
246
+ freqs_cis (torch.Tensor or tuple): Precomputed frequency tensor for complex exponential.
247
+ head_first (bool): head dimension first (except batch dim) or not.
248
+
249
+ Returns:
250
+ Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings.
251
+
252
+ """
253
+ xk_out = None
254
+ if isinstance(freqs_cis, tuple):
255
+ cos, sin = reshape_for_broadcast(freqs_cis, xq, head_first) # [S, D]
256
+ cos, sin = cos.to(xq.device), sin.to(xq.device)
257
+ # real * cos - imag * sin
258
+ # imag * cos + real * sin
259
+ xq_dtype = xq.dtype
260
+ xq_out = xq.to(torch.float)
261
+ xq = None
262
+ xq_out = (xq_out * cos + rotate_half(xq_out) * sin).to(xq_dtype)
263
+ xk_out = xk.to(torch.float)
264
+ xk = None
265
+ xk_out = (xk_out * cos + rotate_half(xk_out) * sin).to(xq_dtype)
266
+ else:
267
+ # view_as_complex will pack [..., D/2, 2](real) to [..., D/2](complex)
268
+ xq_ = torch.view_as_complex(
269
+ xq.float().reshape(*xq.shape[:-1], -1, 2)
270
+ ) # [B, S, H, D//2]
271
+ freqs_cis = reshape_for_broadcast(freqs_cis, xq_, head_first).to(
272
+ xq.device
273
+ ) # [S, D//2] --> [1, S, 1, D//2]
274
+ # (real, imag) * (cos, sin) = (real * cos - imag * sin, imag * cos + real * sin)
275
+ # view_as_real will expand [..., D/2](complex) to [..., D/2, 2](real)
276
+ xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3).type_as(xq)
277
+ xk_ = torch.view_as_complex(
278
+ xk.float().reshape(*xk.shape[:-1], -1, 2)
279
+ ) # [B, S, H, D//2]
280
+ xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3).type_as(xk)
281
+
282
+ return xq_out, xk_out
283
+
284
+
285
+ def _apply_rotary_emb(
286
+ xq: torch.Tensor,
287
+ xk: torch.Tensor,
288
+ freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
289
+ head_first: bool = False,
290
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
291
+ xk_out = None
292
+ if isinstance(freqs_cis, tuple):
293
+ cos, sin = reshape_for_broadcast(freqs_cis, xq, head_first) # [S, D]
294
+ cos, sin = cos.to(xq.device), sin.to(xq.device)
295
+ # real * cos - imag * sin
296
+ # imag * cos + real * sin
297
+ xq_out = (xq.float() * cos + rotate_half(xq.float()) * sin).type_as(xq)
298
+ xk_out = (xk.float() * cos + rotate_half(xk.float()) * sin).type_as(xk)
299
+ else:
300
+ # view_as_complex will pack [..., D/2, 2](real) to [..., D/2](complex)
301
+ xq_ = torch.view_as_complex(
302
+ xq.float().reshape(*xq.shape[:-1], -1, 2)
303
+ ) # [B, S, H, D//2]
304
+ freqs_cis = reshape_for_broadcast(freqs_cis, xq_, head_first).to(
305
+ xq.device
306
+ ) # [S, D//2] --> [1, S, 1, D//2]
307
+ # (real, imag) * (cos, sin) = (real * cos - imag * sin, imag * cos + real * sin)
308
+ # view_as_real will expand [..., D/2](complex) to [..., D/2, 2](real)
309
+ xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3).type_as(xq)
310
+ xk_ = torch.view_as_complex(
311
+ xk.float().reshape(*xk.shape[:-1], -1, 2)
312
+ ) # [B, S, H, D//2]
313
+ xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3).type_as(xk)
314
+
315
+ return xq_out, xk_out
316
+ def get_nd_rotary_pos_embed(
317
+ rope_dim_list,
318
+ start,
319
+ *args,
320
+ theta=10000.0,
321
+ use_real=False,
322
+ theta_rescale_factor: Union[float, List[float]] = 1.0,
323
+ interpolation_factor: Union[float, List[float]] = 1.0,
324
+ k = 4,
325
+ L_test = 66,
326
+ enable_riflex = True
327
+ ):
328
+ """
329
+ This is a n-d version of precompute_freqs_cis, which is a RoPE for tokens with n-d structure.
330
+
331
+ Args:
332
+ rope_dim_list (list of int): Dimension of each rope. len(rope_dim_list) should equal to n.
333
+ sum(rope_dim_list) should equal to head_dim of attention layer.
334
+ start (int | tuple of int | list of int): If len(args) == 0, start is num; If len(args) == 1, start is start,
335
+ args[0] is stop, step is 1; If len(args) == 2, start is start, args[0] is stop, args[1] is num.
336
+ *args: See above.
337
+ theta (float): Scaling factor for frequency computation. Defaults to 10000.0.
338
+ use_real (bool): If True, return real part and imaginary part separately. Otherwise, return complex numbers.
339
+ Some libraries such as TensorRT does not support complex64 data type. So it is useful to provide a real
340
+ part and an imaginary part separately.
341
+ theta_rescale_factor (float): Rescale factor for theta. Defaults to 1.0.
342
+
343
+ Returns:
344
+ pos_embed (torch.Tensor): [HW, D/2]
345
+ """
346
+
347
+ grid = get_meshgrid_nd(
348
+ start, *args, dim=len(rope_dim_list)
349
+ ) # [3, W, H, D] / [2, W, H]
350
+
351
+ if isinstance(theta_rescale_factor, int) or isinstance(theta_rescale_factor, float):
352
+ theta_rescale_factor = [theta_rescale_factor] * len(rope_dim_list)
353
+ elif isinstance(theta_rescale_factor, list) and len(theta_rescale_factor) == 1:
354
+ theta_rescale_factor = [theta_rescale_factor[0]] * len(rope_dim_list)
355
+ assert len(theta_rescale_factor) == len(
356
+ rope_dim_list
357
+ ), "len(theta_rescale_factor) should equal to len(rope_dim_list)"
358
+
359
+ if isinstance(interpolation_factor, int) or isinstance(interpolation_factor, float):
360
+ interpolation_factor = [interpolation_factor] * len(rope_dim_list)
361
+ elif isinstance(interpolation_factor, list) and len(interpolation_factor) == 1:
362
+ interpolation_factor = [interpolation_factor[0]] * len(rope_dim_list)
363
+ assert len(interpolation_factor) == len(
364
+ rope_dim_list
365
+ ), "len(interpolation_factor) should equal to len(rope_dim_list)"
366
+
367
+ # use 1/ndim of dimensions to encode grid_axis
368
+ embs = []
369
+ for i in range(len(rope_dim_list)):
370
+ # emb = get_1d_rotary_pos_embed(
371
+ # rope_dim_list[i],
372
+ # grid[i].reshape(-1),
373
+ # theta,
374
+ # use_real=use_real,
375
+ # theta_rescale_factor=theta_rescale_factor[i],
376
+ # interpolation_factor=interpolation_factor[i],
377
+ # ) # 2 x [WHD, rope_dim_list[i]]
378
+
379
+
380
+ # === RIFLEx modification start ===
381
+ # apply RIFLEx for time dimension
382
+ if i == 0 and enable_riflex:
383
+ emb = get_1d_rotary_pos_embed_riflex(rope_dim_list[i], grid[i].reshape(-1), theta, use_real=True, k=k, L_test=L_test)
384
+ # === RIFLEx modification end ===
385
+ else:
386
+ emb = get_1d_rotary_pos_embed(rope_dim_list[i], grid[i].reshape(-1), theta, use_real=True, theta_rescale_factor=theta_rescale_factor[i],interpolation_factor=interpolation_factor[i],)
387
+ embs.append(emb)
388
+
389
+ if use_real:
390
+ cos = torch.cat([emb[0] for emb in embs], dim=1) # (WHD, D/2)
391
+ sin = torch.cat([emb[1] for emb in embs], dim=1) # (WHD, D/2)
392
+ return cos, sin
393
+ else:
394
+ emb = torch.cat(embs, dim=1) # (WHD, D/2)
395
+ return emb
396
+
397
+
398
+ def get_1d_rotary_pos_embed(
399
+ dim: int,
400
+ pos: Union[torch.FloatTensor, int],
401
+ theta: float = 10000.0,
402
+ use_real: bool = False,
403
+ theta_rescale_factor: float = 1.0,
404
+ interpolation_factor: float = 1.0,
405
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
406
+ """
407
+ Precompute the frequency tensor for complex exponential (cis) with given dimensions.
408
+ (Note: `cis` means `cos + i * sin`, where i is the imaginary unit.)
409
+
410
+ This function calculates a frequency tensor with complex exponential using the given dimension 'dim'
411
+ and the end index 'end'. The 'theta' parameter scales the frequencies.
412
+ The returned tensor contains complex values in complex64 data type.
413
+
414
+ Args:
415
+ dim (int): Dimension of the frequency tensor.
416
+ pos (int or torch.FloatTensor): Position indices for the frequency tensor. [S] or scalar
417
+ theta (float, optional): Scaling factor for frequency computation. Defaults to 10000.0.
418
+ use_real (bool, optional): If True, return real part and imaginary part separately.
419
+ Otherwise, return complex numbers.
420
+ theta_rescale_factor (float, optional): Rescale factor for theta. Defaults to 1.0.
421
+
422
+ Returns:
423
+ freqs_cis: Precomputed frequency tensor with complex exponential. [S, D/2]
424
+ freqs_cos, freqs_sin: Precomputed frequency tensor with real and imaginary parts separately. [S, D]
425
+ """
426
+ if isinstance(pos, int):
427
+ pos = torch.arange(pos).float()
428
+
429
+ # proposed by reddit user bloc97, to rescale rotary embeddings to longer sequence length without fine-tuning
430
+ # has some connection to NTK literature
431
+ if theta_rescale_factor != 1.0:
432
+ theta *= theta_rescale_factor ** (dim / (dim - 2))
433
+
434
+ freqs = 1.0 / (
435
+ theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)
436
+ ) # [D/2]
437
+ # assert interpolation_factor == 1.0, f"interpolation_factor: {interpolation_factor}"
438
+ freqs = torch.outer(pos * interpolation_factor, freqs) # [S, D/2]
439
+ if use_real:
440
+ freqs_cos = freqs.cos().repeat_interleave(2, dim=1) # [S, D]
441
+ freqs_sin = freqs.sin().repeat_interleave(2, dim=1) # [S, D]
442
+ return freqs_cos, freqs_sin
443
+ else:
444
+ freqs_cis = torch.polar(
445
+ torch.ones_like(freqs), freqs
446
+ ) # complex64 # [S, D/2]
447
+ return freqs_cis
hyvideo/modules/token_refiner.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ from einops import rearrange
4
+ import torch
5
+ import torch.nn as nn
6
+
7
+ from .activation_layers import get_activation_layer
8
+ from .attenion import attention
9
+ from .norm_layers import get_norm_layer
10
+ from .embed_layers import TimestepEmbedder, TextProjection
11
+ from .attenion import attention
12
+ from .mlp_layers import MLP
13
+ from .modulate_layers import modulate, apply_gate
14
+
15
+
16
+ class IndividualTokenRefinerBlock(nn.Module):
17
+ def __init__(
18
+ self,
19
+ hidden_size,
20
+ heads_num,
21
+ mlp_width_ratio: str = 4.0,
22
+ mlp_drop_rate: float = 0.0,
23
+ act_type: str = "silu",
24
+ qk_norm: bool = False,
25
+ qk_norm_type: str = "layer",
26
+ qkv_bias: bool = True,
27
+ dtype: Optional[torch.dtype] = None,
28
+ device: Optional[torch.device] = None,
29
+ ):
30
+ factory_kwargs = {"device": device, "dtype": dtype}
31
+ super().__init__()
32
+ self.heads_num = heads_num
33
+ head_dim = hidden_size // heads_num
34
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
35
+
36
+ self.norm1 = nn.LayerNorm(
37
+ hidden_size, elementwise_affine=True, eps=1e-6, **factory_kwargs
38
+ )
39
+ self.self_attn_qkv = nn.Linear(
40
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
41
+ )
42
+ qk_norm_layer = get_norm_layer(qk_norm_type)
43
+ self.self_attn_q_norm = (
44
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
45
+ if qk_norm
46
+ else nn.Identity()
47
+ )
48
+ self.self_attn_k_norm = (
49
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
50
+ if qk_norm
51
+ else nn.Identity()
52
+ )
53
+ self.self_attn_proj = nn.Linear(
54
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
55
+ )
56
+
57
+ self.norm2 = nn.LayerNorm(
58
+ hidden_size, elementwise_affine=True, eps=1e-6, **factory_kwargs
59
+ )
60
+ act_layer = get_activation_layer(act_type)
61
+ self.mlp = MLP(
62
+ in_channels=hidden_size,
63
+ hidden_channels=mlp_hidden_dim,
64
+ act_layer=act_layer,
65
+ drop=mlp_drop_rate,
66
+ **factory_kwargs,
67
+ )
68
+
69
+ self.adaLN_modulation = nn.Sequential(
70
+ act_layer(),
71
+ nn.Linear(hidden_size, 2 * hidden_size, bias=True, **factory_kwargs),
72
+ )
73
+ # Zero-initialize the modulation
74
+ nn.init.zeros_(self.adaLN_modulation[1].weight)
75
+ nn.init.zeros_(self.adaLN_modulation[1].bias)
76
+
77
+ def forward(
78
+ self,
79
+ x: torch.Tensor,
80
+ c: torch.Tensor, # timestep_aware_representations + context_aware_representations
81
+ attn_mask: torch.Tensor = None,
82
+ ):
83
+ gate_msa, gate_mlp = self.adaLN_modulation(c).chunk(2, dim=1)
84
+
85
+ norm_x = self.norm1(x)
86
+ qkv = self.self_attn_qkv(norm_x)
87
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
88
+ # Apply QK-Norm if needed
89
+ q = self.self_attn_q_norm(q).to(v)
90
+ k = self.self_attn_k_norm(k).to(v)
91
+ qkv_list = [q, k, v]
92
+ del q,k
93
+ # Self-Attention
94
+ attn = attention( qkv_list, mode="torch", attn_mask=attn_mask)
95
+
96
+ x = x + apply_gate(self.self_attn_proj(attn), gate_msa)
97
+
98
+ # FFN Layer
99
+ x = x + apply_gate(self.mlp(self.norm2(x)), gate_mlp)
100
+
101
+ return x
102
+
103
+
104
+ class IndividualTokenRefiner(nn.Module):
105
+ def __init__(
106
+ self,
107
+ hidden_size,
108
+ heads_num,
109
+ depth,
110
+ mlp_width_ratio: float = 4.0,
111
+ mlp_drop_rate: float = 0.0,
112
+ act_type: str = "silu",
113
+ qk_norm: bool = False,
114
+ qk_norm_type: str = "layer",
115
+ qkv_bias: bool = True,
116
+ dtype: Optional[torch.dtype] = None,
117
+ device: Optional[torch.device] = None,
118
+ ):
119
+ factory_kwargs = {"device": device, "dtype": dtype}
120
+ super().__init__()
121
+ self.blocks = nn.ModuleList(
122
+ [
123
+ IndividualTokenRefinerBlock(
124
+ hidden_size=hidden_size,
125
+ heads_num=heads_num,
126
+ mlp_width_ratio=mlp_width_ratio,
127
+ mlp_drop_rate=mlp_drop_rate,
128
+ act_type=act_type,
129
+ qk_norm=qk_norm,
130
+ qk_norm_type=qk_norm_type,
131
+ qkv_bias=qkv_bias,
132
+ **factory_kwargs,
133
+ )
134
+ for _ in range(depth)
135
+ ]
136
+ )
137
+
138
+ def forward(
139
+ self,
140
+ x: torch.Tensor,
141
+ c: torch.LongTensor,
142
+ mask: Optional[torch.Tensor] = None,
143
+ ):
144
+ self_attn_mask = None
145
+ if mask is not None:
146
+ batch_size = mask.shape[0]
147
+ seq_len = mask.shape[1]
148
+ mask = mask.to(x.device)
149
+ # batch_size x 1 x seq_len x seq_len
150
+ self_attn_mask_1 = mask.view(batch_size, 1, 1, seq_len).repeat(
151
+ 1, 1, seq_len, 1
152
+ )
153
+ # batch_size x 1 x seq_len x seq_len
154
+ self_attn_mask_2 = self_attn_mask_1.transpose(2, 3)
155
+ # batch_size x 1 x seq_len x seq_len, 1 for broadcasting of heads_num
156
+ self_attn_mask = (self_attn_mask_1 & self_attn_mask_2).bool()
157
+ # avoids self-attention weight being NaN for padding tokens
158
+ self_attn_mask[:, :, :, 0] = True
159
+
160
+ for block in self.blocks:
161
+ x = block(x, c, self_attn_mask)
162
+ return x
163
+
164
+
165
+ class SingleTokenRefiner(nn.Module):
166
+ """
167
+ A single token refiner block for llm text embedding refine.
168
+ """
169
+ def __init__(
170
+ self,
171
+ in_channels,
172
+ hidden_size,
173
+ heads_num,
174
+ depth,
175
+ mlp_width_ratio: float = 4.0,
176
+ mlp_drop_rate: float = 0.0,
177
+ act_type: str = "silu",
178
+ qk_norm: bool = False,
179
+ qk_norm_type: str = "layer",
180
+ qkv_bias: bool = True,
181
+ attn_mode: str = "torch",
182
+ dtype: Optional[torch.dtype] = None,
183
+ device: Optional[torch.device] = None,
184
+ ):
185
+ factory_kwargs = {"device": device, "dtype": dtype}
186
+ super().__init__()
187
+ self.attn_mode = attn_mode
188
+ assert self.attn_mode == "torch", "Only support 'torch' mode for token refiner."
189
+
190
+ self.input_embedder = nn.Linear(
191
+ in_channels, hidden_size, bias=True, **factory_kwargs
192
+ )
193
+
194
+ act_layer = get_activation_layer(act_type)
195
+ # Build timestep embedding layer
196
+ self.t_embedder = TimestepEmbedder(hidden_size, act_layer, **factory_kwargs)
197
+ # Build context embedding layer
198
+ self.c_embedder = TextProjection(
199
+ in_channels, hidden_size, act_layer, **factory_kwargs
200
+ )
201
+
202
+ self.individual_token_refiner = IndividualTokenRefiner(
203
+ hidden_size=hidden_size,
204
+ heads_num=heads_num,
205
+ depth=depth,
206
+ mlp_width_ratio=mlp_width_ratio,
207
+ mlp_drop_rate=mlp_drop_rate,
208
+ act_type=act_type,
209
+ qk_norm=qk_norm,
210
+ qk_norm_type=qk_norm_type,
211
+ qkv_bias=qkv_bias,
212
+ **factory_kwargs,
213
+ )
214
+
215
+ def forward(
216
+ self,
217
+ x: torch.Tensor,
218
+ t: torch.LongTensor,
219
+ mask: Optional[torch.LongTensor] = None,
220
+ ):
221
+ timestep_aware_representations = self.t_embedder(t)
222
+
223
+ if mask is None:
224
+ context_aware_representations = x.mean(dim=1)
225
+ else:
226
+ mask_float = mask.float().unsqueeze(-1) # [b, s1, 1]
227
+ context_aware_representations = (x * mask_float).sum(
228
+ dim=1
229
+ ) / mask_float.sum(dim=1)
230
+ context_aware_representations = self.c_embedder(context_aware_representations)
231
+ c = timestep_aware_representations + context_aware_representations
232
+
233
+ x = self.input_embedder(x)
234
+
235
+ x = self.individual_token_refiner(x, c, mask)
236
+
237
+ return x
hyvideo/prompt_rewrite.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ normal_mode_prompt = """Normal mode - Video Recaption Task:
2
+
3
+ You are a large language model specialized in rewriting video descriptions. Your task is to modify the input description.
4
+
5
+ 0. Preserve ALL information, including style words and technical terms.
6
+
7
+ 1. If the input is in Chinese, translate the entire description to English.
8
+
9
+ 2. If the input is just one or two words describing an object or person, provide a brief, simple description focusing on basic visual characteristics. Limit the description to 1-2 short sentences.
10
+
11
+ 3. If the input does not include style, lighting, atmosphere, you can make reasonable associations.
12
+
13
+ 4. Output ALL must be in English.
14
+
15
+ Given Input:
16
+ input: "{input}"
17
+ """
18
+
19
+
20
+ master_mode_prompt = """Master mode - Video Recaption Task:
21
+
22
+ You are a large language model specialized in rewriting video descriptions. Your task is to modify the input description.
23
+
24
+ 0. Preserve ALL information, including style words and technical terms.
25
+
26
+ 1. If the input is in Chinese, translate the entire description to English.
27
+
28
+ 2. If the input is just one or two words describing an object or person, provide a brief, simple description focusing on basic visual characteristics. Limit the description to 1-2 short sentences.
29
+
30
+ 3. If the input does not include style, lighting, atmosphere, you can make reasonable associations.
31
+
32
+ 4. Output ALL must be in English.
33
+
34
+ Given Input:
35
+ input: "{input}"
36
+ """
37
+
38
+ def get_rewrite_prompt(ori_prompt, mode="Normal"):
39
+ if mode == "Normal":
40
+ prompt = normal_mode_prompt.format(input=ori_prompt)
41
+ elif mode == "Master":
42
+ prompt = master_mode_prompt.format(input=ori_prompt)
43
+ else:
44
+ raise Exception("Only supports Normal and Normal", mode)
45
+ return prompt
46
+
47
+ ori_prompt = "一只小狗在草地上奔跑。"
48
+ normal_prompt = get_rewrite_prompt(ori_prompt, mode="Normal")
49
+ master_prompt = get_rewrite_prompt(ori_prompt, mode="Master")
50
+
51
+ # Then you can use the normal_prompt or master_prompt to access the hunyuan-large rewrite model to get the final prompt.
hyvideo/text_encoder/__init__.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Optional, Tuple
3
+ from copy import deepcopy
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ from transformers import CLIPTextModel, CLIPTokenizer, AutoTokenizer, AutoModel
8
+ from transformers.utils import ModelOutput
9
+
10
+ from ..constants import TEXT_ENCODER_PATH, TOKENIZER_PATH
11
+ from ..constants import PRECISION_TO_TYPE
12
+
13
+
14
+ def use_default(value, default):
15
+ return value if value is not None else default
16
+
17
+
18
+ def load_text_encoder(
19
+ text_encoder_type,
20
+ text_encoder_precision=None,
21
+ text_encoder_path=None,
22
+ logger=None,
23
+ device=None,
24
+ ):
25
+ if text_encoder_path is None:
26
+ text_encoder_path = TEXT_ENCODER_PATH[text_encoder_type]
27
+ if logger is not None:
28
+ logger.info(
29
+ f"Loading text encoder model ({text_encoder_type}) from: {text_encoder_path}"
30
+ )
31
+
32
+ if text_encoder_type == "clipL":
33
+ text_encoder = CLIPTextModel.from_pretrained(text_encoder_path)
34
+ text_encoder.final_layer_norm = text_encoder.text_model.final_layer_norm
35
+ elif text_encoder_type == "llm":
36
+ text_encoder = AutoModel.from_pretrained(
37
+ text_encoder_path, low_cpu_mem_usage=True
38
+ )
39
+ text_encoder.final_layer_norm = text_encoder.norm
40
+ else:
41
+ raise ValueError(f"Unsupported text encoder type: {text_encoder_type}")
42
+ # from_pretrained will ensure that the model is in eval mode.
43
+
44
+ if text_encoder_precision is not None:
45
+ text_encoder = text_encoder.to(dtype=PRECISION_TO_TYPE[text_encoder_precision])
46
+
47
+ text_encoder.requires_grad_(False)
48
+
49
+ if logger is not None:
50
+ logger.info(f"Text encoder to dtype: {text_encoder.dtype}")
51
+
52
+ if device is not None:
53
+ text_encoder = text_encoder.to(device)
54
+
55
+ return text_encoder, text_encoder_path
56
+
57
+
58
+ def load_tokenizer(
59
+ tokenizer_type, tokenizer_path=None, padding_side="right", logger=None
60
+ ):
61
+ if tokenizer_path is None:
62
+ tokenizer_path = TOKENIZER_PATH[tokenizer_type]
63
+ if logger is not None:
64
+ logger.info(f"Loading tokenizer ({tokenizer_type}) from: {tokenizer_path}")
65
+
66
+ if tokenizer_type == "clipL":
67
+ tokenizer = CLIPTokenizer.from_pretrained(tokenizer_path, max_length=77)
68
+ elif tokenizer_type == "llm":
69
+ tokenizer = AutoTokenizer.from_pretrained(
70
+ tokenizer_path, padding_side=padding_side
71
+ )
72
+ else:
73
+ raise ValueError(f"Unsupported tokenizer type: {tokenizer_type}")
74
+
75
+ return tokenizer, tokenizer_path
76
+
77
+
78
+ @dataclass
79
+ class TextEncoderModelOutput(ModelOutput):
80
+ """
81
+ Base class for model's outputs that also contains a pooling of the last hidden states.
82
+
83
+ Args:
84
+ hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
85
+ Sequence of hidden-states at the output of the last layer of the model.
86
+ attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
87
+ Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
88
+ hidden_states_list (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed):
89
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
90
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
91
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
92
+ text_outputs (`list`, *optional*, returned when `return_texts=True` is passed):
93
+ List of decoded texts.
94
+ """
95
+
96
+ hidden_state: torch.FloatTensor = None
97
+ attention_mask: Optional[torch.LongTensor] = None
98
+ hidden_states_list: Optional[Tuple[torch.FloatTensor, ...]] = None
99
+ text_outputs: Optional[list] = None
100
+
101
+
102
+ class TextEncoder(nn.Module):
103
+ def __init__(
104
+ self,
105
+ text_encoder_type: str,
106
+ max_length: int,
107
+ text_encoder_precision: Optional[str] = None,
108
+ text_encoder_path: Optional[str] = None,
109
+ tokenizer_type: Optional[str] = None,
110
+ tokenizer_path: Optional[str] = None,
111
+ output_key: Optional[str] = None,
112
+ use_attention_mask: bool = True,
113
+ input_max_length: Optional[int] = None,
114
+ prompt_template: Optional[dict] = None,
115
+ prompt_template_video: Optional[dict] = None,
116
+ hidden_state_skip_layer: Optional[int] = None,
117
+ apply_final_norm: bool = False,
118
+ reproduce: bool = False,
119
+ logger=None,
120
+ device=None,
121
+ ):
122
+ super().__init__()
123
+ self.text_encoder_type = text_encoder_type
124
+ self.max_length = max_length
125
+ self.precision = text_encoder_precision
126
+ self.model_path = text_encoder_path
127
+ self.tokenizer_type = (
128
+ tokenizer_type if tokenizer_type is not None else text_encoder_type
129
+ )
130
+ self.tokenizer_path = (
131
+ tokenizer_path if tokenizer_path is not None else None # text_encoder_path
132
+ )
133
+ self.use_attention_mask = use_attention_mask
134
+ if prompt_template_video is not None:
135
+ assert (
136
+ use_attention_mask is True
137
+ ), "Attention mask is True required when training videos."
138
+ self.input_max_length = (
139
+ input_max_length if input_max_length is not None else max_length
140
+ )
141
+ self.prompt_template = prompt_template
142
+ self.prompt_template_video = prompt_template_video
143
+ self.hidden_state_skip_layer = hidden_state_skip_layer
144
+ self.apply_final_norm = apply_final_norm
145
+ self.reproduce = reproduce
146
+ self.logger = logger
147
+
148
+ self.use_template = self.prompt_template is not None
149
+ if self.use_template:
150
+ assert (
151
+ isinstance(self.prompt_template, dict)
152
+ and "template" in self.prompt_template
153
+ ), f"`prompt_template` must be a dictionary with a key 'template', got {self.prompt_template}"
154
+ assert "{}" in str(self.prompt_template["template"]), (
155
+ "`prompt_template['template']` must contain a placeholder `{}` for the input text, "
156
+ f"got {self.prompt_template['template']}"
157
+ )
158
+
159
+ self.use_video_template = self.prompt_template_video is not None
160
+ if self.use_video_template:
161
+ if self.prompt_template_video is not None:
162
+ assert (
163
+ isinstance(self.prompt_template_video, dict)
164
+ and "template" in self.prompt_template_video
165
+ ), f"`prompt_template_video` must be a dictionary with a key 'template', got {self.prompt_template_video}"
166
+ assert "{}" in str(self.prompt_template_video["template"]), (
167
+ "`prompt_template_video['template']` must contain a placeholder `{}` for the input text, "
168
+ f"got {self.prompt_template_video['template']}"
169
+ )
170
+
171
+ if "t5" in text_encoder_type:
172
+ self.output_key = output_key or "last_hidden_state"
173
+ elif "clip" in text_encoder_type:
174
+ self.output_key = output_key or "pooler_output"
175
+ elif "llm" in text_encoder_type or "glm" in text_encoder_type:
176
+ self.output_key = output_key or "last_hidden_state"
177
+ else:
178
+ raise ValueError(f"Unsupported text encoder type: {text_encoder_type}")
179
+
180
+ if "llm" in text_encoder_type:
181
+ from mmgp import offload
182
+
183
+ self.model= offload.fast_load_transformers_model(self.model_path) #, pinInMemory = True, partialPinning = True
184
+ # self.model= offload.fast_load_transformers_model("vlm.sft", forcedConfigPath ="ckpts/text_encoder/config.json") #, pinInMemory = True, partialPinning = True
185
+ # self.model.final_layer_norm = self.model.norm
186
+
187
+ else:
188
+ self.model, self.model_path = load_text_encoder(
189
+ text_encoder_type=self.text_encoder_type,
190
+ text_encoder_precision=self.precision,
191
+ text_encoder_path=self.model_path,
192
+ logger=self.logger,
193
+ device=device,
194
+ )
195
+
196
+ self.dtype = self.model.dtype
197
+ self.device = self.model.device
198
+
199
+ self.tokenizer, self.tokenizer_path = load_tokenizer(
200
+ tokenizer_type=self.tokenizer_type,
201
+ tokenizer_path=self.tokenizer_path,
202
+ padding_side="right",
203
+ logger=self.logger,
204
+ )
205
+
206
+ def __repr__(self):
207
+ return f"{self.text_encoder_type} ({self.precision} - {self.model_path})"
208
+
209
+ @staticmethod
210
+ def apply_text_to_template(text, template, prevent_empty_text=True):
211
+ """
212
+ Apply text to template.
213
+
214
+ Args:
215
+ text (str): Input text.
216
+ template (str or list): Template string or list of chat conversation.
217
+ prevent_empty_text (bool): If Ture, we will prevent the user text from being empty
218
+ by adding a space. Defaults to True.
219
+ """
220
+ if isinstance(template, str):
221
+ # Will send string to tokenizer. Used for llm
222
+ return template.format(text)
223
+ else:
224
+ raise TypeError(f"Unsupported template type: {type(template)}")
225
+
226
+ def text2tokens(self, text, data_type="image"):
227
+ """
228
+ Tokenize the input text.
229
+
230
+ Args:
231
+ text (str or list): Input text.
232
+ """
233
+ tokenize_input_type = "str"
234
+ if self.use_template:
235
+ if data_type == "image":
236
+ prompt_template = self.prompt_template["template"]
237
+ elif data_type == "video":
238
+ prompt_template = self.prompt_template_video["template"]
239
+ else:
240
+ raise ValueError(f"Unsupported data type: {data_type}")
241
+ if isinstance(text, (list, tuple)):
242
+ text = [
243
+ self.apply_text_to_template(one_text, prompt_template)
244
+ for one_text in text
245
+ ]
246
+ if isinstance(text[0], list):
247
+ tokenize_input_type = "list"
248
+ elif isinstance(text, str):
249
+ text = self.apply_text_to_template(text, prompt_template)
250
+ if isinstance(text, list):
251
+ tokenize_input_type = "list"
252
+ else:
253
+ raise TypeError(f"Unsupported text type: {type(text)}")
254
+
255
+ kwargs = dict(
256
+ truncation=True,
257
+ max_length=self.max_length,
258
+ padding="max_length",
259
+ return_tensors="pt",
260
+ )
261
+ if tokenize_input_type == "str":
262
+ return self.tokenizer(
263
+ text,
264
+ return_length=False,
265
+ return_overflowing_tokens=False,
266
+ return_attention_mask=True,
267
+ **kwargs,
268
+ )
269
+ elif tokenize_input_type == "list":
270
+ return self.tokenizer.apply_chat_template(
271
+ text,
272
+ add_generation_prompt=True,
273
+ tokenize=True,
274
+ return_dict=True,
275
+ **kwargs,
276
+ )
277
+ else:
278
+ raise ValueError(f"Unsupported tokenize_input_type: {tokenize_input_type}")
279
+
280
+ def encode(
281
+ self,
282
+ batch_encoding,
283
+ use_attention_mask=None,
284
+ output_hidden_states=False,
285
+ do_sample=None,
286
+ hidden_state_skip_layer=None,
287
+ return_texts=False,
288
+ data_type="image",
289
+ device=None,
290
+ ):
291
+ """
292
+ Args:
293
+ batch_encoding (dict): Batch encoding from tokenizer.
294
+ use_attention_mask (bool): Whether to use attention mask. If None, use self.use_attention_mask.
295
+ Defaults to None.
296
+ output_hidden_states (bool): Whether to output hidden states. If False, return the value of
297
+ self.output_key. If True, return the entire output. If set self.hidden_state_skip_layer,
298
+ output_hidden_states will be set True. Defaults to False.
299
+ do_sample (bool): Whether to sample from the model. Used for Decoder-Only LLMs. Defaults to None.
300
+ When self.produce is False, do_sample is set to True by default.
301
+ hidden_state_skip_layer (int): Number of hidden states to hidden_state_skip_layer. 0 means the last layer.
302
+ If None, self.output_key will be used. Defaults to None.
303
+ return_texts (bool): Whether to return the decoded texts. Defaults to False.
304
+ """
305
+ device = self.model.device if device is None else device
306
+ use_attention_mask = use_default(use_attention_mask, self.use_attention_mask)
307
+ hidden_state_skip_layer = use_default(
308
+ hidden_state_skip_layer, self.hidden_state_skip_layer
309
+ )
310
+ do_sample = use_default(do_sample, not self.reproduce)
311
+ attention_mask = (
312
+ batch_encoding["attention_mask"].to(device) if use_attention_mask else None
313
+ )
314
+ outputs = self.model(
315
+ input_ids=batch_encoding["input_ids"].to(device),
316
+ attention_mask=attention_mask,
317
+ output_hidden_states=output_hidden_states
318
+ or hidden_state_skip_layer is not None,
319
+ )
320
+ if hidden_state_skip_layer is not None:
321
+ last_hidden_state = outputs.hidden_states[-(hidden_state_skip_layer + 1)]
322
+ # Real last hidden state already has layer norm applied. So here we only apply it
323
+ # for intermediate layers.
324
+ if hidden_state_skip_layer > 0 and self.apply_final_norm:
325
+ last_hidden_state = self.model.final_layer_norm(last_hidden_state)
326
+ else:
327
+ last_hidden_state = outputs[self.output_key]
328
+
329
+ # Remove hidden states of instruction tokens, only keep prompt tokens.
330
+ if self.use_template:
331
+ if data_type == "image":
332
+ crop_start = self.prompt_template.get("crop_start", -1)
333
+ elif data_type == "video":
334
+ crop_start = self.prompt_template_video.get("crop_start", -1)
335
+ else:
336
+ raise ValueError(f"Unsupported data type: {data_type}")
337
+ if crop_start > 0:
338
+ last_hidden_state = last_hidden_state[:, crop_start:]
339
+ attention_mask = (
340
+ attention_mask[:, crop_start:] if use_attention_mask else None
341
+ )
342
+
343
+ if output_hidden_states:
344
+ return TextEncoderModelOutput(
345
+ last_hidden_state, attention_mask, outputs.hidden_states
346
+ )
347
+ return TextEncoderModelOutput(last_hidden_state, attention_mask)
348
+
349
+ def forward(
350
+ self,
351
+ text,
352
+ use_attention_mask=None,
353
+ output_hidden_states=False,
354
+ do_sample=False,
355
+ hidden_state_skip_layer=None,
356
+ return_texts=False,
357
+ ):
358
+ batch_encoding = self.text2tokens(text)
359
+ return self.encode(
360
+ batch_encoding,
361
+ use_attention_mask=use_attention_mask,
362
+ output_hidden_states=output_hidden_states,
363
+ do_sample=do_sample,
364
+ hidden_state_skip_layer=hidden_state_skip_layer,
365
+ return_texts=return_texts,
366
+ )
hyvideo/utils/__init__.py ADDED
File without changes
hyvideo/utils/data_utils.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import math
3
+
4
+
5
+ def align_to(value, alignment):
6
+ """align hight, width according to alignment
7
+
8
+ Args:
9
+ value (int): height or width
10
+ alignment (int): target alignment factor
11
+
12
+ Returns:
13
+ int: the aligned value
14
+ """
15
+ return int(math.ceil(value / alignment) * alignment)
hyvideo/utils/file_utils.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ from einops import rearrange
4
+
5
+ import torch
6
+ import torchvision
7
+ import numpy as np
8
+ import imageio
9
+
10
+ CODE_SUFFIXES = {
11
+ ".py", # Python codes
12
+ ".sh", # Shell scripts
13
+ ".yaml",
14
+ ".yml", # Configuration files
15
+ }
16
+
17
+
18
+ def safe_dir(path):
19
+ """
20
+ Create a directory (or the parent directory of a file) if it does not exist.
21
+
22
+ Args:
23
+ path (str or Path): Path to the directory.
24
+
25
+ Returns:
26
+ path (Path): Path object of the directory.
27
+ """
28
+ path = Path(path)
29
+ path.mkdir(exist_ok=True, parents=True)
30
+ return path
31
+
32
+
33
+ def safe_file(path):
34
+ """
35
+ Create the parent directory of a file if it does not exist.
36
+
37
+ Args:
38
+ path (str or Path): Path to the file.
39
+
40
+ Returns:
41
+ path (Path): Path object of the file.
42
+ """
43
+ path = Path(path)
44
+ path.parent.mkdir(exist_ok=True, parents=True)
45
+ return path
46
+
47
+ def save_videos_grid(videos: torch.Tensor, path: str, rescale=False, n_rows=1, fps=24):
48
+ """save videos by video tensor
49
+ copy from https://github.com/guoyww/AnimateDiff/blob/e92bd5671ba62c0d774a32951453e328018b7c5b/animatediff/utils/util.py#L61
50
+
51
+ Args:
52
+ videos (torch.Tensor): video tensor predicted by the model
53
+ path (str): path to save video
54
+ rescale (bool, optional): rescale the video tensor from [-1, 1] to . Defaults to False.
55
+ n_rows (int, optional): Defaults to 1.
56
+ fps (int, optional): video save fps. Defaults to 8.
57
+ """
58
+ videos = rearrange(videos, "b c t h w -> t b c h w")
59
+ outputs = []
60
+ for x in videos:
61
+ x = torchvision.utils.make_grid(x, nrow=n_rows)
62
+ x = x.transpose(0, 1).transpose(1, 2).squeeze(-1)
63
+ if rescale:
64
+ x = (x + 1.0) / 2.0 # -1,1 -> 0,1
65
+ x = torch.clamp(x, 0, 1)
66
+ x = (x * 255).numpy().astype(np.uint8)
67
+ outputs.append(x)
68
+
69
+ os.makedirs(os.path.dirname(path), exist_ok=True)
70
+ imageio.mimsave(path, outputs, fps=fps)
hyvideo/utils/helpers.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections.abc
2
+
3
+ from itertools import repeat
4
+
5
+
6
+ def _ntuple(n):
7
+ def parse(x):
8
+ if isinstance(x, collections.abc.Iterable) and not isinstance(x, str):
9
+ x = tuple(x)
10
+ if len(x) == 1:
11
+ x = tuple(repeat(x[0], n))
12
+ return x
13
+ return tuple(repeat(x, n))
14
+ return parse
15
+
16
+
17
+ to_1tuple = _ntuple(1)
18
+ to_2tuple = _ntuple(2)
19
+ to_3tuple = _ntuple(3)
20
+ to_4tuple = _ntuple(4)
21
+
22
+
23
+ def as_tuple(x):
24
+ if isinstance(x, collections.abc.Iterable) and not isinstance(x, str):
25
+ return tuple(x)
26
+ if x is None or isinstance(x, (int, float, str)):
27
+ return (x,)
28
+ else:
29
+ raise ValueError(f"Unknown type {type(x)}")
30
+
31
+
32
+ def as_list_of_2tuple(x):
33
+ x = as_tuple(x)
34
+ if len(x) == 1:
35
+ x = (x[0], x[0])
36
+ assert len(x) % 2 == 0, f"Expect even length, got {len(x)}."
37
+ lst = []
38
+ for i in range(0, len(x), 2):
39
+ lst.append((x[i], x[i + 1]))
40
+ return lst
hyvideo/utils/preprocess_text_encoder_tokenizer_utils.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import torch
3
+ from transformers import (
4
+ AutoProcessor,
5
+ LlavaForConditionalGeneration,
6
+ )
7
+
8
+
9
+ def preprocess_text_encoder_tokenizer(args):
10
+
11
+ processor = AutoProcessor.from_pretrained(args.input_dir)
12
+ model = LlavaForConditionalGeneration.from_pretrained(
13
+ args.input_dir,
14
+ torch_dtype=torch.float16,
15
+ low_cpu_mem_usage=True,
16
+ ).to(0)
17
+
18
+ model.language_model.save_pretrained(
19
+ f"{args.output_dir}"
20
+ )
21
+ processor.tokenizer.save_pretrained(
22
+ f"{args.output_dir}"
23
+ )
24
+
25
+ if __name__ == "__main__":
26
+
27
+ parser = argparse.ArgumentParser()
28
+ parser.add_argument(
29
+ "--input_dir",
30
+ type=str,
31
+ required=True,
32
+ help="The path to the llava-llama-3-8b-v1_1-transformers.",
33
+ )
34
+ parser.add_argument(
35
+ "--output_dir",
36
+ type=str,
37
+ default="",
38
+ help="The output path of the llava-llama-3-8b-text-encoder-tokenizer."
39
+ "if '', the parent dir of output will be the same as input dir.",
40
+ )
41
+ args = parser.parse_args()
42
+
43
+ if len(args.output_dir) == 0:
44
+ args.output_dir = "/".join(args.input_dir.split("/")[:-1])
45
+
46
+ preprocess_text_encoder_tokenizer(args)
hyvideo/vae/__init__.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ import torch
4
+
5
+ from .autoencoder_kl_causal_3d import AutoencoderKLCausal3D
6
+ from ..constants import VAE_PATH, PRECISION_TO_TYPE
7
+
8
+ def load_vae(vae_type: str="884-16c-hy",
9
+ vae_precision: str=None,
10
+ sample_size: tuple=None,
11
+ vae_path: str=None,
12
+ logger=None,
13
+ device=None
14
+ ):
15
+ """the fucntion to load the 3D VAE model
16
+
17
+ Args:
18
+ vae_type (str): the type of the 3D VAE model. Defaults to "884-16c-hy".
19
+ vae_precision (str, optional): the precision to load vae. Defaults to None.
20
+ sample_size (tuple, optional): the tiling size. Defaults to None.
21
+ vae_path (str, optional): the path to vae. Defaults to None.
22
+ logger (_type_, optional): logger. Defaults to None.
23
+ device (_type_, optional): device to load vae. Defaults to None.
24
+ """
25
+ if vae_path is None:
26
+ vae_path = VAE_PATH[vae_type]
27
+
28
+ if logger is not None:
29
+ logger.info(f"Loading 3D VAE model ({vae_type}) from: {vae_path}")
30
+ config = AutoencoderKLCausal3D.load_config(vae_path)
31
+ if sample_size:
32
+ vae = AutoencoderKLCausal3D.from_config(config, sample_size=sample_size)
33
+ else:
34
+ vae = AutoencoderKLCausal3D.from_config(config)
35
+
36
+ vae_ckpt = Path(vae_path) / "pytorch_model.pt"
37
+ assert vae_ckpt.exists(), f"VAE checkpoint not found: {vae_ckpt}"
38
+
39
+ ckpt = torch.load(vae_ckpt, weights_only=True, map_location=vae.device)
40
+ if "state_dict" in ckpt:
41
+ ckpt = ckpt["state_dict"]
42
+ if any(k.startswith("vae.") for k in ckpt.keys()):
43
+ ckpt = {k.replace("vae.", ""): v for k, v in ckpt.items() if k.startswith("vae.")}
44
+ vae.load_state_dict(ckpt)
45
+
46
+ spatial_compression_ratio = vae.config.spatial_compression_ratio
47
+ time_compression_ratio = vae.config.time_compression_ratio
48
+
49
+ if vae_precision is not None:
50
+ vae = vae.to(dtype=PRECISION_TO_TYPE[vae_precision])
51
+
52
+ vae.requires_grad_(False)
53
+
54
+ if logger is not None:
55
+ logger.info(f"VAE to dtype: {vae.dtype}")
56
+
57
+ if device is not None:
58
+ vae = vae.to(device)
59
+
60
+ vae.eval()
61
+
62
+ return vae, vae_path, spatial_compression_ratio, time_compression_ratio
hyvideo/vae/autoencoder_kl_causal_3d.py ADDED
@@ -0,0 +1,603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ #
16
+ # Modified from diffusers==0.29.2
17
+ #
18
+ # ==============================================================================
19
+ from typing import Dict, Optional, Tuple, Union
20
+ from dataclasses import dataclass
21
+
22
+ import torch
23
+ import torch.nn as nn
24
+
25
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
26
+
27
+ try:
28
+ # This diffusers is modified and packed in the mirror.
29
+ from diffusers.loaders import FromOriginalVAEMixin
30
+ except ImportError:
31
+ # Use this to be compatible with the original diffusers.
32
+ from diffusers.loaders.single_file_model import FromOriginalModelMixin as FromOriginalVAEMixin
33
+ from diffusers.utils.accelerate_utils import apply_forward_hook
34
+ from diffusers.models.attention_processor import (
35
+ ADDED_KV_ATTENTION_PROCESSORS,
36
+ CROSS_ATTENTION_PROCESSORS,
37
+ Attention,
38
+ AttentionProcessor,
39
+ AttnAddedKVProcessor,
40
+ AttnProcessor,
41
+ )
42
+ from diffusers.models.modeling_outputs import AutoencoderKLOutput
43
+ from diffusers.models.modeling_utils import ModelMixin
44
+ from .vae import DecoderCausal3D, BaseOutput, DecoderOutput, DiagonalGaussianDistribution, EncoderCausal3D
45
+
46
+
47
+ @dataclass
48
+ class DecoderOutput2(BaseOutput):
49
+ sample: torch.FloatTensor
50
+ posterior: Optional[DiagonalGaussianDistribution] = None
51
+
52
+
53
+ class AutoencoderKLCausal3D(ModelMixin, ConfigMixin, FromOriginalVAEMixin):
54
+ r"""
55
+ A VAE model with KL loss for encoding images/videos into latents and decoding latent representations into images/videos.
56
+
57
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
58
+ for all models (such as downloading or saving).
59
+ """
60
+
61
+ _supports_gradient_checkpointing = True
62
+
63
+ @register_to_config
64
+ def __init__(
65
+ self,
66
+ in_channels: int = 3,
67
+ out_channels: int = 3,
68
+ down_block_types: Tuple[str] = ("DownEncoderBlockCausal3D",),
69
+ up_block_types: Tuple[str] = ("UpDecoderBlockCausal3D",),
70
+ block_out_channels: Tuple[int] = (64,),
71
+ layers_per_block: int = 1,
72
+ act_fn: str = "silu",
73
+ latent_channels: int = 4,
74
+ norm_num_groups: int = 32,
75
+ sample_size: int = 32,
76
+ sample_tsize: int = 64,
77
+ scaling_factor: float = 0.18215,
78
+ force_upcast: float = True,
79
+ spatial_compression_ratio: int = 8,
80
+ time_compression_ratio: int = 4,
81
+ mid_block_add_attention: bool = True,
82
+ ):
83
+ super().__init__()
84
+
85
+ self.time_compression_ratio = time_compression_ratio
86
+
87
+ self.encoder = EncoderCausal3D(
88
+ in_channels=in_channels,
89
+ out_channels=latent_channels,
90
+ down_block_types=down_block_types,
91
+ block_out_channels=block_out_channels,
92
+ layers_per_block=layers_per_block,
93
+ act_fn=act_fn,
94
+ norm_num_groups=norm_num_groups,
95
+ double_z=True,
96
+ time_compression_ratio=time_compression_ratio,
97
+ spatial_compression_ratio=spatial_compression_ratio,
98
+ mid_block_add_attention=mid_block_add_attention,
99
+ )
100
+
101
+ self.decoder = DecoderCausal3D(
102
+ in_channels=latent_channels,
103
+ out_channels=out_channels,
104
+ up_block_types=up_block_types,
105
+ block_out_channels=block_out_channels,
106
+ layers_per_block=layers_per_block,
107
+ norm_num_groups=norm_num_groups,
108
+ act_fn=act_fn,
109
+ time_compression_ratio=time_compression_ratio,
110
+ spatial_compression_ratio=spatial_compression_ratio,
111
+ mid_block_add_attention=mid_block_add_attention,
112
+ )
113
+
114
+ self.quant_conv = nn.Conv3d(2 * latent_channels, 2 * latent_channels, kernel_size=1)
115
+ self.post_quant_conv = nn.Conv3d(latent_channels, latent_channels, kernel_size=1)
116
+
117
+ self.use_slicing = False
118
+ self.use_spatial_tiling = False
119
+ self.use_temporal_tiling = False
120
+
121
+ # only relevant if vae tiling is enabled
122
+ self.tile_sample_min_tsize = sample_tsize
123
+ self.tile_latent_min_tsize = sample_tsize // time_compression_ratio
124
+
125
+ self.tile_sample_min_size = self.config.sample_size
126
+ sample_size = (
127
+ self.config.sample_size[0]
128
+ if isinstance(self.config.sample_size, (list, tuple))
129
+ else self.config.sample_size
130
+ )
131
+ self.tile_latent_min_size = int(sample_size / (2 ** (len(self.config.block_out_channels) - 1)))
132
+ self.tile_overlap_factor = 0.25
133
+
134
+ def _set_gradient_checkpointing(self, module, value=False):
135
+ if isinstance(module, (EncoderCausal3D, DecoderCausal3D)):
136
+ module.gradient_checkpointing = value
137
+
138
+ def enable_temporal_tiling(self, use_tiling: bool = True):
139
+ self.use_temporal_tiling = use_tiling
140
+
141
+ def disable_temporal_tiling(self):
142
+ self.enable_temporal_tiling(False)
143
+
144
+ def enable_spatial_tiling(self, use_tiling: bool = True):
145
+ self.use_spatial_tiling = use_tiling
146
+
147
+ def disable_spatial_tiling(self):
148
+ self.enable_spatial_tiling(False)
149
+
150
+ def enable_tiling(self, use_tiling: bool = True):
151
+ r"""
152
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
153
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
154
+ processing larger videos.
155
+ """
156
+ self.enable_spatial_tiling(use_tiling)
157
+ self.enable_temporal_tiling(use_tiling)
158
+
159
+ def disable_tiling(self):
160
+ r"""
161
+ Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
162
+ decoding in one step.
163
+ """
164
+ self.disable_spatial_tiling()
165
+ self.disable_temporal_tiling()
166
+
167
+ def enable_slicing(self):
168
+ r"""
169
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
170
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
171
+ """
172
+ self.use_slicing = True
173
+
174
+ def disable_slicing(self):
175
+ r"""
176
+ Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
177
+ decoding in one step.
178
+ """
179
+ self.use_slicing = False
180
+
181
+ @property
182
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
183
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
184
+ r"""
185
+ Returns:
186
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
187
+ indexed by its weight name.
188
+ """
189
+ # set recursively
190
+ processors = {}
191
+
192
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
193
+ if hasattr(module, "get_processor"):
194
+ processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
195
+
196
+ for sub_name, child in module.named_children():
197
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
198
+
199
+ return processors
200
+
201
+ for name, module in self.named_children():
202
+ fn_recursive_add_processors(name, module, processors)
203
+
204
+ return processors
205
+
206
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
207
+ def set_attn_processor(
208
+ self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]], _remove_lora=False
209
+ ):
210
+ r"""
211
+ Sets the attention processor to use to compute attention.
212
+
213
+ Parameters:
214
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
215
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
216
+ for **all** `Attention` layers.
217
+
218
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
219
+ processor. This is strongly recommended when setting trainable attention processors.
220
+
221
+ """
222
+ count = len(self.attn_processors.keys())
223
+
224
+ if isinstance(processor, dict) and len(processor) != count:
225
+ raise ValueError(
226
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
227
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
228
+ )
229
+
230
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
231
+ if hasattr(module, "set_processor"):
232
+ if not isinstance(processor, dict):
233
+ module.set_processor(processor, _remove_lora=_remove_lora)
234
+ else:
235
+ module.set_processor(processor.pop(f"{name}.processor"), _remove_lora=_remove_lora)
236
+
237
+ for sub_name, child in module.named_children():
238
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
239
+
240
+ for name, module in self.named_children():
241
+ fn_recursive_attn_processor(name, module, processor)
242
+
243
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
244
+ def set_default_attn_processor(self):
245
+ """
246
+ Disables custom attention processors and sets the default attention implementation.
247
+ """
248
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
249
+ processor = AttnAddedKVProcessor()
250
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
251
+ processor = AttnProcessor()
252
+ else:
253
+ raise ValueError(
254
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
255
+ )
256
+
257
+ self.set_attn_processor(processor, _remove_lora=True)
258
+
259
+ @apply_forward_hook
260
+ def encode(
261
+ self, x: torch.FloatTensor, return_dict: bool = True
262
+ ) -> Union[AutoencoderKLOutput, Tuple[DiagonalGaussianDistribution]]:
263
+ """
264
+ Encode a batch of images/videos into latents.
265
+
266
+ Args:
267
+ x (`torch.FloatTensor`): Input batch of images/videos.
268
+ return_dict (`bool`, *optional*, defaults to `True`):
269
+ Whether to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.
270
+
271
+ Returns:
272
+ The latent representations of the encoded images/videos. If `return_dict` is True, a
273
+ [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain `tuple` is returned.
274
+ """
275
+ assert len(x.shape) == 5, "The input tensor should have 5 dimensions."
276
+
277
+ if self.use_temporal_tiling and x.shape[2] > self.tile_sample_min_tsize:
278
+ return self.temporal_tiled_encode(x, return_dict=return_dict)
279
+
280
+ if self.use_spatial_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size):
281
+ return self.spatial_tiled_encode(x, return_dict=return_dict)
282
+
283
+ if self.use_slicing and x.shape[0] > 1:
284
+ encoded_slices = [self.encoder(x_slice) for x_slice in x.split(1)]
285
+ h = torch.cat(encoded_slices)
286
+ else:
287
+ h = self.encoder(x)
288
+
289
+ moments = self.quant_conv(h)
290
+ posterior = DiagonalGaussianDistribution(moments)
291
+
292
+ if not return_dict:
293
+ return (posterior,)
294
+
295
+ return AutoencoderKLOutput(latent_dist=posterior)
296
+
297
+ def _decode(self, z: torch.FloatTensor, return_dict: bool = True) -> Union[DecoderOutput, torch.FloatTensor]:
298
+ assert len(z.shape) == 5, "The input tensor should have 5 dimensions."
299
+
300
+ if self.use_temporal_tiling and z.shape[2] > self.tile_latent_min_tsize:
301
+ return self.temporal_tiled_decode(z, return_dict=return_dict)
302
+
303
+ if self.use_spatial_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size):
304
+ return self.spatial_tiled_decode(z, return_dict=return_dict)
305
+
306
+ z = self.post_quant_conv(z)
307
+ dec = self.decoder(z)
308
+
309
+ if not return_dict:
310
+ return (dec,)
311
+
312
+ return DecoderOutput(sample=dec)
313
+
314
+ @apply_forward_hook
315
+ def decode(
316
+ self, z: torch.FloatTensor, return_dict: bool = True, generator=None
317
+ ) -> Union[DecoderOutput, torch.FloatTensor]:
318
+ """
319
+ Decode a batch of images/videos.
320
+
321
+ Args:
322
+ z (`torch.FloatTensor`): Input batch of latent vectors.
323
+ return_dict (`bool`, *optional*, defaults to `True`):
324
+ Whether to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.
325
+
326
+ Returns:
327
+ [`~models.vae.DecoderOutput`] or `tuple`:
328
+ If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
329
+ returned.
330
+
331
+ """
332
+ if self.use_slicing and z.shape[0] > 1:
333
+ decoded_slices = [self._decode(z_slice).sample for z_slice in z.split(1)]
334
+ decoded = torch.cat(decoded_slices)
335
+ else:
336
+ decoded = self._decode(z).sample
337
+
338
+ if not return_dict:
339
+ return (decoded,)
340
+
341
+ return DecoderOutput(sample=decoded)
342
+
343
+ def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
344
+ blend_extent = min(a.shape[-2], b.shape[-2], blend_extent)
345
+ for y in range(blend_extent):
346
+ b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, :, y, :] * (y / blend_extent)
347
+ return b
348
+
349
+ def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
350
+ blend_extent = min(a.shape[-1], b.shape[-1], blend_extent)
351
+ for x in range(blend_extent):
352
+ b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, :, x] * (x / blend_extent)
353
+ return b
354
+
355
+ def blend_t(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
356
+ blend_extent = min(a.shape[-3], b.shape[-3], blend_extent)
357
+ for x in range(blend_extent):
358
+ b[:, :, x, :, :] = a[:, :, -blend_extent + x, :, :] * (1 - x / blend_extent) + b[:, :, x, :, :] * (x / blend_extent)
359
+ return b
360
+
361
+ def spatial_tiled_encode(self, x: torch.FloatTensor, return_dict: bool = True, return_moments: bool = False) -> AutoencoderKLOutput:
362
+ r"""Encode a batch of images/videos using a tiled encoder.
363
+
364
+ When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
365
+ steps. This is useful to keep memory use constant regardless of image/videos size. The end result of tiled encoding is
366
+ different from non-tiled encoding because each tile uses a different encoder. To avoid tiling artifacts, the
367
+ tiles overlap and are blended together to form a smooth output. You may still see tile-sized changes in the
368
+ output, but they should be much less noticeable.
369
+
370
+ Args:
371
+ x (`torch.FloatTensor`): Input batch of images/videos.
372
+ return_dict (`bool`, *optional*, defaults to `True`):
373
+ Whether or not to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.
374
+
375
+ Returns:
376
+ [`~models.autoencoder_kl.AutoencoderKLOutput`] or `tuple`:
377
+ If return_dict is True, a [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain
378
+ `tuple` is returned.
379
+ """
380
+ overlap_size = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor))
381
+ blend_extent = int(self.tile_latent_min_size * self.tile_overlap_factor)
382
+ row_limit = self.tile_latent_min_size - blend_extent
383
+
384
+ # Split video into tiles and encode them separately.
385
+ rows = []
386
+ for i in range(0, x.shape[-2], overlap_size):
387
+ row = []
388
+ for j in range(0, x.shape[-1], overlap_size):
389
+ tile = x[:, :, :, i: i + self.tile_sample_min_size, j: j + self.tile_sample_min_size]
390
+ tile = self.encoder(tile)
391
+ tile = self.quant_conv(tile)
392
+ row.append(tile)
393
+ rows.append(row)
394
+ result_rows = []
395
+ for i, row in enumerate(rows):
396
+ result_row = []
397
+ for j, tile in enumerate(row):
398
+ # blend the above tile and the left tile
399
+ # to the current tile and add the current tile to the result row
400
+ if i > 0:
401
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
402
+ if j > 0:
403
+ tile = self.blend_h(row[j - 1], tile, blend_extent)
404
+ result_row.append(tile[:, :, :, :row_limit, :row_limit])
405
+ result_rows.append(torch.cat(result_row, dim=-1))
406
+
407
+ moments = torch.cat(result_rows, dim=-2)
408
+ if return_moments:
409
+ return moments
410
+
411
+ posterior = DiagonalGaussianDistribution(moments)
412
+ if not return_dict:
413
+ return (posterior,)
414
+
415
+ return AutoencoderKLOutput(latent_dist=posterior)
416
+
417
+ def spatial_tiled_decode(self, z: torch.FloatTensor, return_dict: bool = True) -> Union[DecoderOutput, torch.FloatTensor]:
418
+ r"""
419
+ Decode a batch of images/videos using a tiled decoder.
420
+
421
+ Args:
422
+ z (`torch.FloatTensor`): Input batch of latent vectors.
423
+ return_dict (`bool`, *optional*, defaults to `True`):
424
+ Whether or not to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.
425
+
426
+ Returns:
427
+ [`~models.vae.DecoderOutput`] or `tuple`:
428
+ If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
429
+ returned.
430
+ """
431
+ overlap_size = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor))
432
+ blend_extent = int(self.tile_sample_min_size * self.tile_overlap_factor)
433
+ row_limit = self.tile_sample_min_size - blend_extent
434
+
435
+ # Split z into overlapping tiles and decode them separately.
436
+ # The tiles have an overlap to avoid seams between tiles.
437
+ rows = []
438
+ for i in range(0, z.shape[-2], overlap_size):
439
+ row = []
440
+ for j in range(0, z.shape[-1], overlap_size):
441
+ tile = z[:, :, :, i: i + self.tile_latent_min_size, j: j + self.tile_latent_min_size]
442
+ tile = self.post_quant_conv(tile)
443
+ decoded = self.decoder(tile)
444
+ row.append(decoded)
445
+ rows.append(row)
446
+ result_rows = []
447
+ for i, row in enumerate(rows):
448
+ result_row = []
449
+ for j, tile in enumerate(row):
450
+ # blend the above tile and the left tile
451
+ # to the current tile and add the current tile to the result row
452
+ if i > 0:
453
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
454
+ if j > 0:
455
+ tile = self.blend_h(row[j - 1], tile, blend_extent)
456
+ result_row.append(tile[:, :, :, :row_limit, :row_limit])
457
+ result_rows.append(torch.cat(result_row, dim=-1))
458
+
459
+ dec = torch.cat(result_rows, dim=-2)
460
+ if not return_dict:
461
+ return (dec,)
462
+
463
+ return DecoderOutput(sample=dec)
464
+
465
+ def temporal_tiled_encode(self, x: torch.FloatTensor, return_dict: bool = True) -> AutoencoderKLOutput:
466
+
467
+ B, C, T, H, W = x.shape
468
+ overlap_size = int(self.tile_sample_min_tsize * (1 - self.tile_overlap_factor))
469
+ blend_extent = int(self.tile_latent_min_tsize * self.tile_overlap_factor)
470
+ t_limit = self.tile_latent_min_tsize - blend_extent
471
+
472
+ # Split the video into tiles and encode them separately.
473
+ row = []
474
+ for i in range(0, T, overlap_size):
475
+ tile = x[:, :, i: i + self.tile_sample_min_tsize + 1, :, :]
476
+ if self.use_spatial_tiling and (tile.shape[-1] > self.tile_sample_min_size or tile.shape[-2] > self.tile_sample_min_size):
477
+ tile = self.spatial_tiled_encode(tile, return_moments=True)
478
+ else:
479
+ tile = self.encoder(tile)
480
+ tile = self.quant_conv(tile)
481
+ if i > 0:
482
+ tile = tile[:, :, 1:, :, :]
483
+ row.append(tile)
484
+ result_row = []
485
+ for i, tile in enumerate(row):
486
+ if i > 0:
487
+ tile = self.blend_t(row[i - 1], tile, blend_extent)
488
+ result_row.append(tile[:, :, :t_limit, :, :])
489
+ else:
490
+ result_row.append(tile[:, :, :t_limit + 1, :, :])
491
+
492
+ moments = torch.cat(result_row, dim=2)
493
+ posterior = DiagonalGaussianDistribution(moments)
494
+
495
+ if not return_dict:
496
+ return (posterior,)
497
+
498
+ return AutoencoderKLOutput(latent_dist=posterior)
499
+
500
+ def temporal_tiled_decode(self, z: torch.FloatTensor, return_dict: bool = True) -> Union[DecoderOutput, torch.FloatTensor]:
501
+ # Split z into overlapping tiles and decode them separately.
502
+
503
+ B, C, T, H, W = z.shape
504
+ overlap_size = int(self.tile_latent_min_tsize * (1 - self.tile_overlap_factor))
505
+ blend_extent = int(self.tile_sample_min_tsize * self.tile_overlap_factor)
506
+ t_limit = self.tile_sample_min_tsize - blend_extent
507
+
508
+ row = []
509
+ for i in range(0, T, overlap_size):
510
+ tile = z[:, :, i: i + self.tile_latent_min_tsize + 1, :, :]
511
+ if self.use_spatial_tiling and (tile.shape[-1] > self.tile_latent_min_size or tile.shape[-2] > self.tile_latent_min_size):
512
+ decoded = self.spatial_tiled_decode(tile, return_dict=True).sample
513
+ else:
514
+ tile = self.post_quant_conv(tile)
515
+ decoded = self.decoder(tile)
516
+ if i > 0:
517
+ decoded = decoded[:, :, 1:, :, :]
518
+ row.append(decoded)
519
+ result_row = []
520
+ for i, tile in enumerate(row):
521
+ if i > 0:
522
+ tile = self.blend_t(row[i - 1], tile, blend_extent)
523
+ result_row.append(tile[:, :, :t_limit, :, :])
524
+ else:
525
+ result_row.append(tile[:, :, :t_limit + 1, :, :])
526
+
527
+ dec = torch.cat(result_row, dim=2)
528
+ if not return_dict:
529
+ return (dec,)
530
+
531
+ return DecoderOutput(sample=dec)
532
+
533
+ def forward(
534
+ self,
535
+ sample: torch.FloatTensor,
536
+ sample_posterior: bool = False,
537
+ return_dict: bool = True,
538
+ return_posterior: bool = False,
539
+ generator: Optional[torch.Generator] = None,
540
+ ) -> Union[DecoderOutput2, torch.FloatTensor]:
541
+ r"""
542
+ Args:
543
+ sample (`torch.FloatTensor`): Input sample.
544
+ sample_posterior (`bool`, *optional*, defaults to `False`):
545
+ Whether to sample from the posterior.
546
+ return_dict (`bool`, *optional*, defaults to `True`):
547
+ Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
548
+ """
549
+ x = sample
550
+ posterior = self.encode(x).latent_dist
551
+ if sample_posterior:
552
+ z = posterior.sample(generator=generator)
553
+ else:
554
+ z = posterior.mode()
555
+ dec = self.decode(z).sample
556
+
557
+ if not return_dict:
558
+ if return_posterior:
559
+ return (dec, posterior)
560
+ else:
561
+ return (dec,)
562
+ if return_posterior:
563
+ return DecoderOutput2(sample=dec, posterior=posterior)
564
+ else:
565
+ return DecoderOutput2(sample=dec)
566
+
567
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections
568
+ def fuse_qkv_projections(self):
569
+ """
570
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query,
571
+ key, value) are fused. For cross-attention modules, key and value projection matrices are fused.
572
+
573
+ <Tip warning={true}>
574
+
575
+ This API is 🧪 experimental.
576
+
577
+ </Tip>
578
+ """
579
+ self.original_attn_processors = None
580
+
581
+ for _, attn_processor in self.attn_processors.items():
582
+ if "Added" in str(attn_processor.__class__.__name__):
583
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
584
+
585
+ self.original_attn_processors = self.attn_processors
586
+
587
+ for module in self.modules():
588
+ if isinstance(module, Attention):
589
+ module.fuse_projections(fuse=True)
590
+
591
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
592
+ def unfuse_qkv_projections(self):
593
+ """Disables the fused QKV projection if enabled.
594
+
595
+ <Tip warning={true}>
596
+
597
+ This API is 🧪 experimental.
598
+
599
+ </Tip>
600
+
601
+ """
602
+ if self.original_attn_processors is not None:
603
+ self.set_attn_processor(self.original_attn_processors)
hyvideo/vae/unet_causal_3d_blocks.py ADDED
@@ -0,0 +1,764 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ #
16
+ # Modified from diffusers==0.29.2
17
+ #
18
+ # ==============================================================================
19
+
20
+ from typing import Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ from torch import nn
25
+ from einops import rearrange
26
+
27
+ from diffusers.utils import logging
28
+ from diffusers.models.activations import get_activation
29
+ from diffusers.models.attention_processor import SpatialNorm
30
+ from diffusers.models.attention_processor import Attention
31
+ from diffusers.models.normalization import AdaGroupNorm
32
+ from diffusers.models.normalization import RMSNorm
33
+
34
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
35
+
36
+
37
+ def prepare_causal_attention_mask(n_frame: int, n_hw: int, dtype, device, batch_size: int = None):
38
+ seq_len = n_frame * n_hw
39
+ mask = torch.full((seq_len, seq_len), float("-inf"), dtype=dtype, device=device)
40
+ for i in range(seq_len):
41
+ i_frame = i // n_hw
42
+ mask[i, : (i_frame + 1) * n_hw] = 0
43
+ if batch_size is not None:
44
+ mask = mask.unsqueeze(0).expand(batch_size, -1, -1)
45
+ return mask
46
+
47
+
48
+ class CausalConv3d(nn.Module):
49
+ """
50
+ Implements a causal 3D convolution layer where each position only depends on previous timesteps and current spatial locations.
51
+ This maintains temporal causality in video generation tasks.
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ chan_in,
57
+ chan_out,
58
+ kernel_size: Union[int, Tuple[int, int, int]],
59
+ stride: Union[int, Tuple[int, int, int]] = 1,
60
+ dilation: Union[int, Tuple[int, int, int]] = 1,
61
+ pad_mode='replicate',
62
+ **kwargs
63
+ ):
64
+ super().__init__()
65
+
66
+ self.pad_mode = pad_mode
67
+ padding = (kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size - 1, 0) # W, H, T
68
+ self.time_causal_padding = padding
69
+
70
+ self.conv = nn.Conv3d(chan_in, chan_out, kernel_size, stride=stride, dilation=dilation, **kwargs)
71
+
72
+ def forward(self, x):
73
+ x = F.pad(x, self.time_causal_padding, mode=self.pad_mode)
74
+ return self.conv(x)
75
+
76
+
77
+ class UpsampleCausal3D(nn.Module):
78
+ """
79
+ A 3D upsampling layer with an optional convolution.
80
+ """
81
+
82
+ def __init__(
83
+ self,
84
+ channels: int,
85
+ use_conv: bool = False,
86
+ use_conv_transpose: bool = False,
87
+ out_channels: Optional[int] = None,
88
+ name: str = "conv",
89
+ kernel_size: Optional[int] = None,
90
+ padding=1,
91
+ norm_type=None,
92
+ eps=None,
93
+ elementwise_affine=None,
94
+ bias=True,
95
+ interpolate=True,
96
+ upsample_factor=(2, 2, 2),
97
+ ):
98
+ super().__init__()
99
+ self.channels = channels
100
+ self.out_channels = out_channels or channels
101
+ self.use_conv = use_conv
102
+ self.use_conv_transpose = use_conv_transpose
103
+ self.name = name
104
+ self.interpolate = interpolate
105
+ self.upsample_factor = upsample_factor
106
+
107
+ if norm_type == "ln_norm":
108
+ self.norm = nn.LayerNorm(channels, eps, elementwise_affine)
109
+ elif norm_type == "rms_norm":
110
+ self.norm = RMSNorm(channels, eps, elementwise_affine)
111
+ elif norm_type is None:
112
+ self.norm = None
113
+ else:
114
+ raise ValueError(f"unknown norm_type: {norm_type}")
115
+
116
+ conv = None
117
+ if use_conv_transpose:
118
+ raise NotImplementedError
119
+ elif use_conv:
120
+ if kernel_size is None:
121
+ kernel_size = 3
122
+ conv = CausalConv3d(self.channels, self.out_channels, kernel_size=kernel_size, bias=bias)
123
+
124
+ if name == "conv":
125
+ self.conv = conv
126
+ else:
127
+ self.Conv2d_0 = conv
128
+
129
+ def forward(
130
+ self,
131
+ hidden_states: torch.FloatTensor,
132
+ output_size: Optional[int] = None,
133
+ scale: float = 1.0,
134
+ ) -> torch.FloatTensor:
135
+ assert hidden_states.shape[1] == self.channels
136
+
137
+ if self.norm is not None:
138
+ raise NotImplementedError
139
+
140
+ if self.use_conv_transpose:
141
+ return self.conv(hidden_states)
142
+
143
+ # Cast to float32 to as 'upsample_nearest2d_out_frame' op does not support bfloat16
144
+ dtype = hidden_states.dtype
145
+ if dtype == torch.bfloat16:
146
+ hidden_states = hidden_states.to(torch.float32)
147
+
148
+ # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
149
+ if hidden_states.shape[0] >= 64:
150
+ hidden_states = hidden_states.contiguous()
151
+
152
+ # if `output_size` is passed we force the interpolation output
153
+ # size and do not make use of `scale_factor=2`
154
+ if self.interpolate:
155
+ B, C, T, H, W = hidden_states.shape
156
+ first_h, other_h = hidden_states.split((1, T - 1), dim=2)
157
+ if output_size is None:
158
+ if T > 1:
159
+ other_h = F.interpolate(other_h, scale_factor=self.upsample_factor, mode="nearest")
160
+
161
+ first_h = first_h.squeeze(2)
162
+ first_h = F.interpolate(first_h, scale_factor=self.upsample_factor[1:], mode="nearest")
163
+ first_h = first_h.unsqueeze(2)
164
+ else:
165
+ raise NotImplementedError
166
+
167
+ if T > 1:
168
+ hidden_states = torch.cat((first_h, other_h), dim=2)
169
+ else:
170
+ hidden_states = first_h
171
+
172
+ # If the input is bfloat16, we cast back to bfloat16
173
+ if dtype == torch.bfloat16:
174
+ hidden_states = hidden_states.to(dtype)
175
+
176
+ if self.use_conv:
177
+ if self.name == "conv":
178
+ hidden_states = self.conv(hidden_states)
179
+ else:
180
+ hidden_states = self.Conv2d_0(hidden_states)
181
+
182
+ return hidden_states
183
+
184
+
185
+ class DownsampleCausal3D(nn.Module):
186
+ """
187
+ A 3D downsampling layer with an optional convolution.
188
+ """
189
+
190
+ def __init__(
191
+ self,
192
+ channels: int,
193
+ use_conv: bool = False,
194
+ out_channels: Optional[int] = None,
195
+ padding: int = 1,
196
+ name: str = "conv",
197
+ kernel_size=3,
198
+ norm_type=None,
199
+ eps=None,
200
+ elementwise_affine=None,
201
+ bias=True,
202
+ stride=2,
203
+ ):
204
+ super().__init__()
205
+ self.channels = channels
206
+ self.out_channels = out_channels or channels
207
+ self.use_conv = use_conv
208
+ self.padding = padding
209
+ stride = stride
210
+ self.name = name
211
+
212
+ if norm_type == "ln_norm":
213
+ self.norm = nn.LayerNorm(channels, eps, elementwise_affine)
214
+ elif norm_type == "rms_norm":
215
+ self.norm = RMSNorm(channels, eps, elementwise_affine)
216
+ elif norm_type is None:
217
+ self.norm = None
218
+ else:
219
+ raise ValueError(f"unknown norm_type: {norm_type}")
220
+
221
+ if use_conv:
222
+ conv = CausalConv3d(
223
+ self.channels, self.out_channels, kernel_size=kernel_size, stride=stride, bias=bias
224
+ )
225
+ else:
226
+ raise NotImplementedError
227
+
228
+ if name == "conv":
229
+ self.Conv2d_0 = conv
230
+ self.conv = conv
231
+ elif name == "Conv2d_0":
232
+ self.conv = conv
233
+ else:
234
+ self.conv = conv
235
+
236
+ def forward(self, hidden_states: torch.FloatTensor, scale: float = 1.0) -> torch.FloatTensor:
237
+ assert hidden_states.shape[1] == self.channels
238
+
239
+ if self.norm is not None:
240
+ hidden_states = self.norm(hidden_states.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
241
+
242
+ assert hidden_states.shape[1] == self.channels
243
+
244
+ hidden_states = self.conv(hidden_states)
245
+
246
+ return hidden_states
247
+
248
+
249
+ class ResnetBlockCausal3D(nn.Module):
250
+ r"""
251
+ A Resnet block.
252
+ """
253
+
254
+ def __init__(
255
+ self,
256
+ *,
257
+ in_channels: int,
258
+ out_channels: Optional[int] = None,
259
+ conv_shortcut: bool = False,
260
+ dropout: float = 0.0,
261
+ temb_channels: int = 512,
262
+ groups: int = 32,
263
+ groups_out: Optional[int] = None,
264
+ pre_norm: bool = True,
265
+ eps: float = 1e-6,
266
+ non_linearity: str = "swish",
267
+ skip_time_act: bool = False,
268
+ # default, scale_shift, ada_group, spatial
269
+ time_embedding_norm: str = "default",
270
+ kernel: Optional[torch.FloatTensor] = None,
271
+ output_scale_factor: float = 1.0,
272
+ use_in_shortcut: Optional[bool] = None,
273
+ up: bool = False,
274
+ down: bool = False,
275
+ conv_shortcut_bias: bool = True,
276
+ conv_3d_out_channels: Optional[int] = None,
277
+ ):
278
+ super().__init__()
279
+ self.pre_norm = pre_norm
280
+ self.pre_norm = True
281
+ self.in_channels = in_channels
282
+ out_channels = in_channels if out_channels is None else out_channels
283
+ self.out_channels = out_channels
284
+ self.use_conv_shortcut = conv_shortcut
285
+ self.up = up
286
+ self.down = down
287
+ self.output_scale_factor = output_scale_factor
288
+ self.time_embedding_norm = time_embedding_norm
289
+ self.skip_time_act = skip_time_act
290
+
291
+ linear_cls = nn.Linear
292
+
293
+ if groups_out is None:
294
+ groups_out = groups
295
+
296
+ if self.time_embedding_norm == "ada_group":
297
+ self.norm1 = AdaGroupNorm(temb_channels, in_channels, groups, eps=eps)
298
+ elif self.time_embedding_norm == "spatial":
299
+ self.norm1 = SpatialNorm(in_channels, temb_channels)
300
+ else:
301
+ self.norm1 = torch.nn.GroupNorm(num_groups=groups, num_channels=in_channels, eps=eps, affine=True)
302
+
303
+ self.conv1 = CausalConv3d(in_channels, out_channels, kernel_size=3, stride=1)
304
+
305
+ if temb_channels is not None:
306
+ if self.time_embedding_norm == "default":
307
+ self.time_emb_proj = linear_cls(temb_channels, out_channels)
308
+ elif self.time_embedding_norm == "scale_shift":
309
+ self.time_emb_proj = linear_cls(temb_channels, 2 * out_channels)
310
+ elif self.time_embedding_norm == "ada_group" or self.time_embedding_norm == "spatial":
311
+ self.time_emb_proj = None
312
+ else:
313
+ raise ValueError(f"Unknown time_embedding_norm : {self.time_embedding_norm} ")
314
+ else:
315
+ self.time_emb_proj = None
316
+
317
+ if self.time_embedding_norm == "ada_group":
318
+ self.norm2 = AdaGroupNorm(temb_channels, out_channels, groups_out, eps=eps)
319
+ elif self.time_embedding_norm == "spatial":
320
+ self.norm2 = SpatialNorm(out_channels, temb_channels)
321
+ else:
322
+ self.norm2 = torch.nn.GroupNorm(num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True)
323
+
324
+ self.dropout = torch.nn.Dropout(dropout)
325
+ conv_3d_out_channels = conv_3d_out_channels or out_channels
326
+ self.conv2 = CausalConv3d(out_channels, conv_3d_out_channels, kernel_size=3, stride=1)
327
+
328
+ self.nonlinearity = get_activation(non_linearity)
329
+
330
+ self.upsample = self.downsample = None
331
+ if self.up:
332
+ self.upsample = UpsampleCausal3D(in_channels, use_conv=False)
333
+ elif self.down:
334
+ self.downsample = DownsampleCausal3D(in_channels, use_conv=False, name="op")
335
+
336
+ self.use_in_shortcut = self.in_channels != conv_3d_out_channels if use_in_shortcut is None else use_in_shortcut
337
+
338
+ self.conv_shortcut = None
339
+ if self.use_in_shortcut:
340
+ self.conv_shortcut = CausalConv3d(
341
+ in_channels,
342
+ conv_3d_out_channels,
343
+ kernel_size=1,
344
+ stride=1,
345
+ bias=conv_shortcut_bias,
346
+ )
347
+
348
+ def forward(
349
+ self,
350
+ input_tensor: torch.FloatTensor,
351
+ temb: torch.FloatTensor,
352
+ scale: float = 1.0,
353
+ ) -> torch.FloatTensor:
354
+ hidden_states = input_tensor
355
+
356
+ if self.time_embedding_norm == "ada_group" or self.time_embedding_norm == "spatial":
357
+ hidden_states = self.norm1(hidden_states, temb)
358
+ else:
359
+ hidden_states = self.norm1(hidden_states)
360
+
361
+ hidden_states = self.nonlinearity(hidden_states)
362
+
363
+ if self.upsample is not None:
364
+ # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
365
+ if hidden_states.shape[0] >= 64:
366
+ input_tensor = input_tensor.contiguous()
367
+ hidden_states = hidden_states.contiguous()
368
+ input_tensor = (
369
+ self.upsample(input_tensor, scale=scale)
370
+ )
371
+ hidden_states = (
372
+ self.upsample(hidden_states, scale=scale)
373
+ )
374
+ elif self.downsample is not None:
375
+ input_tensor = (
376
+ self.downsample(input_tensor, scale=scale)
377
+ )
378
+ hidden_states = (
379
+ self.downsample(hidden_states, scale=scale)
380
+ )
381
+
382
+ hidden_states = self.conv1(hidden_states)
383
+
384
+ if self.time_emb_proj is not None:
385
+ if not self.skip_time_act:
386
+ temb = self.nonlinearity(temb)
387
+ temb = (
388
+ self.time_emb_proj(temb, scale)[:, :, None, None]
389
+ )
390
+
391
+ if temb is not None and self.time_embedding_norm == "default":
392
+ hidden_states = hidden_states + temb
393
+
394
+ if self.time_embedding_norm == "ada_group" or self.time_embedding_norm == "spatial":
395
+ hidden_states = self.norm2(hidden_states, temb)
396
+ else:
397
+ hidden_states = self.norm2(hidden_states)
398
+
399
+ if temb is not None and self.time_embedding_norm == "scale_shift":
400
+ scale, shift = torch.chunk(temb, 2, dim=1)
401
+ hidden_states = hidden_states * (1 + scale) + shift
402
+
403
+ hidden_states = self.nonlinearity(hidden_states)
404
+
405
+ hidden_states = self.dropout(hidden_states)
406
+ hidden_states = self.conv2(hidden_states)
407
+
408
+ if self.conv_shortcut is not None:
409
+ input_tensor = (
410
+ self.conv_shortcut(input_tensor)
411
+ )
412
+
413
+ output_tensor = (input_tensor + hidden_states) / self.output_scale_factor
414
+
415
+ return output_tensor
416
+
417
+
418
+ def get_down_block3d(
419
+ down_block_type: str,
420
+ num_layers: int,
421
+ in_channels: int,
422
+ out_channels: int,
423
+ temb_channels: int,
424
+ add_downsample: bool,
425
+ downsample_stride: int,
426
+ resnet_eps: float,
427
+ resnet_act_fn: str,
428
+ transformer_layers_per_block: int = 1,
429
+ num_attention_heads: Optional[int] = None,
430
+ resnet_groups: Optional[int] = None,
431
+ cross_attention_dim: Optional[int] = None,
432
+ downsample_padding: Optional[int] = None,
433
+ dual_cross_attention: bool = False,
434
+ use_linear_projection: bool = False,
435
+ only_cross_attention: bool = False,
436
+ upcast_attention: bool = False,
437
+ resnet_time_scale_shift: str = "default",
438
+ attention_type: str = "default",
439
+ resnet_skip_time_act: bool = False,
440
+ resnet_out_scale_factor: float = 1.0,
441
+ cross_attention_norm: Optional[str] = None,
442
+ attention_head_dim: Optional[int] = None,
443
+ downsample_type: Optional[str] = None,
444
+ dropout: float = 0.0,
445
+ ):
446
+ # If attn head dim is not defined, we default it to the number of heads
447
+ if attention_head_dim is None:
448
+ logger.warn(
449
+ f"It is recommended to provide `attention_head_dim` when calling `get_down_block`. Defaulting `attention_head_dim` to {num_attention_heads}."
450
+ )
451
+ attention_head_dim = num_attention_heads
452
+
453
+ down_block_type = down_block_type[7:] if down_block_type.startswith("UNetRes") else down_block_type
454
+ if down_block_type == "DownEncoderBlockCausal3D":
455
+ return DownEncoderBlockCausal3D(
456
+ num_layers=num_layers,
457
+ in_channels=in_channels,
458
+ out_channels=out_channels,
459
+ dropout=dropout,
460
+ add_downsample=add_downsample,
461
+ downsample_stride=downsample_stride,
462
+ resnet_eps=resnet_eps,
463
+ resnet_act_fn=resnet_act_fn,
464
+ resnet_groups=resnet_groups,
465
+ downsample_padding=downsample_padding,
466
+ resnet_time_scale_shift=resnet_time_scale_shift,
467
+ )
468
+ raise ValueError(f"{down_block_type} does not exist.")
469
+
470
+
471
+ def get_up_block3d(
472
+ up_block_type: str,
473
+ num_layers: int,
474
+ in_channels: int,
475
+ out_channels: int,
476
+ prev_output_channel: int,
477
+ temb_channels: int,
478
+ add_upsample: bool,
479
+ upsample_scale_factor: Tuple,
480
+ resnet_eps: float,
481
+ resnet_act_fn: str,
482
+ resolution_idx: Optional[int] = None,
483
+ transformer_layers_per_block: int = 1,
484
+ num_attention_heads: Optional[int] = None,
485
+ resnet_groups: Optional[int] = None,
486
+ cross_attention_dim: Optional[int] = None,
487
+ dual_cross_attention: bool = False,
488
+ use_linear_projection: bool = False,
489
+ only_cross_attention: bool = False,
490
+ upcast_attention: bool = False,
491
+ resnet_time_scale_shift: str = "default",
492
+ attention_type: str = "default",
493
+ resnet_skip_time_act: bool = False,
494
+ resnet_out_scale_factor: float = 1.0,
495
+ cross_attention_norm: Optional[str] = None,
496
+ attention_head_dim: Optional[int] = None,
497
+ upsample_type: Optional[str] = None,
498
+ dropout: float = 0.0,
499
+ ) -> nn.Module:
500
+ # If attn head dim is not defined, we default it to the number of heads
501
+ if attention_head_dim is None:
502
+ logger.warn(
503
+ f"It is recommended to provide `attention_head_dim` when calling `get_up_block`. Defaulting `attention_head_dim` to {num_attention_heads}."
504
+ )
505
+ attention_head_dim = num_attention_heads
506
+
507
+ up_block_type = up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type
508
+ if up_block_type == "UpDecoderBlockCausal3D":
509
+ return UpDecoderBlockCausal3D(
510
+ num_layers=num_layers,
511
+ in_channels=in_channels,
512
+ out_channels=out_channels,
513
+ resolution_idx=resolution_idx,
514
+ dropout=dropout,
515
+ add_upsample=add_upsample,
516
+ upsample_scale_factor=upsample_scale_factor,
517
+ resnet_eps=resnet_eps,
518
+ resnet_act_fn=resnet_act_fn,
519
+ resnet_groups=resnet_groups,
520
+ resnet_time_scale_shift=resnet_time_scale_shift,
521
+ temb_channels=temb_channels,
522
+ )
523
+ raise ValueError(f"{up_block_type} does not exist.")
524
+
525
+
526
+ class UNetMidBlockCausal3D(nn.Module):
527
+ """
528
+ A 3D UNet mid-block [`UNetMidBlockCausal3D`] with multiple residual blocks and optional attention blocks.
529
+ """
530
+
531
+ def __init__(
532
+ self,
533
+ in_channels: int,
534
+ temb_channels: int,
535
+ dropout: float = 0.0,
536
+ num_layers: int = 1,
537
+ resnet_eps: float = 1e-6,
538
+ resnet_time_scale_shift: str = "default", # default, spatial
539
+ resnet_act_fn: str = "swish",
540
+ resnet_groups: int = 32,
541
+ attn_groups: Optional[int] = None,
542
+ resnet_pre_norm: bool = True,
543
+ add_attention: bool = True,
544
+ attention_head_dim: int = 1,
545
+ output_scale_factor: float = 1.0,
546
+ ):
547
+ super().__init__()
548
+ resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
549
+ self.add_attention = add_attention
550
+
551
+ if attn_groups is None:
552
+ attn_groups = resnet_groups if resnet_time_scale_shift == "default" else None
553
+
554
+ # there is always at least one resnet
555
+ resnets = [
556
+ ResnetBlockCausal3D(
557
+ in_channels=in_channels,
558
+ out_channels=in_channels,
559
+ temb_channels=temb_channels,
560
+ eps=resnet_eps,
561
+ groups=resnet_groups,
562
+ dropout=dropout,
563
+ time_embedding_norm=resnet_time_scale_shift,
564
+ non_linearity=resnet_act_fn,
565
+ output_scale_factor=output_scale_factor,
566
+ pre_norm=resnet_pre_norm,
567
+ )
568
+ ]
569
+ attentions = []
570
+
571
+ if attention_head_dim is None:
572
+ logger.warn(
573
+ f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {in_channels}."
574
+ )
575
+ attention_head_dim = in_channels
576
+
577
+ for _ in range(num_layers):
578
+ if self.add_attention:
579
+ attentions.append(
580
+ Attention(
581
+ in_channels,
582
+ heads=in_channels // attention_head_dim,
583
+ dim_head=attention_head_dim,
584
+ rescale_output_factor=output_scale_factor,
585
+ eps=resnet_eps,
586
+ norm_num_groups=attn_groups,
587
+ spatial_norm_dim=temb_channels if resnet_time_scale_shift == "spatial" else None,
588
+ residual_connection=True,
589
+ bias=True,
590
+ upcast_softmax=True,
591
+ _from_deprecated_attn_block=True,
592
+ )
593
+ )
594
+ else:
595
+ attentions.append(None)
596
+
597
+ resnets.append(
598
+ ResnetBlockCausal3D(
599
+ in_channels=in_channels,
600
+ out_channels=in_channels,
601
+ temb_channels=temb_channels,
602
+ eps=resnet_eps,
603
+ groups=resnet_groups,
604
+ dropout=dropout,
605
+ time_embedding_norm=resnet_time_scale_shift,
606
+ non_linearity=resnet_act_fn,
607
+ output_scale_factor=output_scale_factor,
608
+ pre_norm=resnet_pre_norm,
609
+ )
610
+ )
611
+
612
+ self.attentions = nn.ModuleList(attentions)
613
+ self.resnets = nn.ModuleList(resnets)
614
+
615
+ def forward(self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None) -> torch.FloatTensor:
616
+ hidden_states = self.resnets[0](hidden_states, temb)
617
+ for attn, resnet in zip(self.attentions, self.resnets[1:]):
618
+ if attn is not None:
619
+ B, C, T, H, W = hidden_states.shape
620
+ hidden_states = rearrange(hidden_states, "b c f h w -> b (f h w) c")
621
+ attention_mask = prepare_causal_attention_mask(
622
+ T, H * W, hidden_states.dtype, hidden_states.device, batch_size=B
623
+ )
624
+ hidden_states = attn(hidden_states, temb=temb, attention_mask=attention_mask)
625
+ hidden_states = rearrange(hidden_states, "b (f h w) c -> b c f h w", f=T, h=H, w=W)
626
+ hidden_states = resnet(hidden_states, temb)
627
+
628
+ return hidden_states
629
+
630
+
631
+ class DownEncoderBlockCausal3D(nn.Module):
632
+ def __init__(
633
+ self,
634
+ in_channels: int,
635
+ out_channels: int,
636
+ dropout: float = 0.0,
637
+ num_layers: int = 1,
638
+ resnet_eps: float = 1e-6,
639
+ resnet_time_scale_shift: str = "default",
640
+ resnet_act_fn: str = "swish",
641
+ resnet_groups: int = 32,
642
+ resnet_pre_norm: bool = True,
643
+ output_scale_factor: float = 1.0,
644
+ add_downsample: bool = True,
645
+ downsample_stride: int = 2,
646
+ downsample_padding: int = 1,
647
+ ):
648
+ super().__init__()
649
+ resnets = []
650
+
651
+ for i in range(num_layers):
652
+ in_channels = in_channels if i == 0 else out_channels
653
+ resnets.append(
654
+ ResnetBlockCausal3D(
655
+ in_channels=in_channels,
656
+ out_channels=out_channels,
657
+ temb_channels=None,
658
+ eps=resnet_eps,
659
+ groups=resnet_groups,
660
+ dropout=dropout,
661
+ time_embedding_norm=resnet_time_scale_shift,
662
+ non_linearity=resnet_act_fn,
663
+ output_scale_factor=output_scale_factor,
664
+ pre_norm=resnet_pre_norm,
665
+ )
666
+ )
667
+
668
+ self.resnets = nn.ModuleList(resnets)
669
+
670
+ if add_downsample:
671
+ self.downsamplers = nn.ModuleList(
672
+ [
673
+ DownsampleCausal3D(
674
+ out_channels,
675
+ use_conv=True,
676
+ out_channels=out_channels,
677
+ padding=downsample_padding,
678
+ name="op",
679
+ stride=downsample_stride,
680
+ )
681
+ ]
682
+ )
683
+ else:
684
+ self.downsamplers = None
685
+
686
+ def forward(self, hidden_states: torch.FloatTensor, scale: float = 1.0) -> torch.FloatTensor:
687
+ for resnet in self.resnets:
688
+ hidden_states = resnet(hidden_states, temb=None, scale=scale)
689
+
690
+ if self.downsamplers is not None:
691
+ for downsampler in self.downsamplers:
692
+ hidden_states = downsampler(hidden_states, scale)
693
+
694
+ return hidden_states
695
+
696
+
697
+ class UpDecoderBlockCausal3D(nn.Module):
698
+ def __init__(
699
+ self,
700
+ in_channels: int,
701
+ out_channels: int,
702
+ resolution_idx: Optional[int] = None,
703
+ dropout: float = 0.0,
704
+ num_layers: int = 1,
705
+ resnet_eps: float = 1e-6,
706
+ resnet_time_scale_shift: str = "default", # default, spatial
707
+ resnet_act_fn: str = "swish",
708
+ resnet_groups: int = 32,
709
+ resnet_pre_norm: bool = True,
710
+ output_scale_factor: float = 1.0,
711
+ add_upsample: bool = True,
712
+ upsample_scale_factor=(2, 2, 2),
713
+ temb_channels: Optional[int] = None,
714
+ ):
715
+ super().__init__()
716
+ resnets = []
717
+
718
+ for i in range(num_layers):
719
+ input_channels = in_channels if i == 0 else out_channels
720
+
721
+ resnets.append(
722
+ ResnetBlockCausal3D(
723
+ in_channels=input_channels,
724
+ out_channels=out_channels,
725
+ temb_channels=temb_channels,
726
+ eps=resnet_eps,
727
+ groups=resnet_groups,
728
+ dropout=dropout,
729
+ time_embedding_norm=resnet_time_scale_shift,
730
+ non_linearity=resnet_act_fn,
731
+ output_scale_factor=output_scale_factor,
732
+ pre_norm=resnet_pre_norm,
733
+ )
734
+ )
735
+
736
+ self.resnets = nn.ModuleList(resnets)
737
+
738
+ if add_upsample:
739
+ self.upsamplers = nn.ModuleList(
740
+ [
741
+ UpsampleCausal3D(
742
+ out_channels,
743
+ use_conv=True,
744
+ out_channels=out_channels,
745
+ upsample_factor=upsample_scale_factor,
746
+ )
747
+ ]
748
+ )
749
+ else:
750
+ self.upsamplers = None
751
+
752
+ self.resolution_idx = resolution_idx
753
+
754
+ def forward(
755
+ self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, scale: float = 1.0
756
+ ) -> torch.FloatTensor:
757
+ for resnet in self.resnets:
758
+ hidden_states = resnet(hidden_states, temb=temb, scale=scale)
759
+
760
+ if self.upsamplers is not None:
761
+ for upsampler in self.upsamplers:
762
+ hidden_states = upsampler(hidden_states)
763
+
764
+ return hidden_states
hyvideo/vae/vae.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Optional, Tuple
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+ from diffusers.utils import BaseOutput, is_torch_version
9
+ from diffusers.utils.torch_utils import randn_tensor
10
+ from diffusers.models.attention_processor import SpatialNorm
11
+ from .unet_causal_3d_blocks import (
12
+ CausalConv3d,
13
+ UNetMidBlockCausal3D,
14
+ get_down_block3d,
15
+ get_up_block3d,
16
+ )
17
+
18
+
19
+ @dataclass
20
+ class DecoderOutput(BaseOutput):
21
+ r"""
22
+ Output of decoding method.
23
+
24
+ Args:
25
+ sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
26
+ The decoded output sample from the last layer of the model.
27
+ """
28
+
29
+ sample: torch.FloatTensor
30
+
31
+
32
+ class EncoderCausal3D(nn.Module):
33
+ r"""
34
+ The `EncoderCausal3D` layer of a variational autoencoder that encodes its input into a latent representation.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ in_channels: int = 3,
40
+ out_channels: int = 3,
41
+ down_block_types: Tuple[str, ...] = ("DownEncoderBlockCausal3D",),
42
+ block_out_channels: Tuple[int, ...] = (64,),
43
+ layers_per_block: int = 2,
44
+ norm_num_groups: int = 32,
45
+ act_fn: str = "silu",
46
+ double_z: bool = True,
47
+ mid_block_add_attention=True,
48
+ time_compression_ratio: int = 4,
49
+ spatial_compression_ratio: int = 8,
50
+ ):
51
+ super().__init__()
52
+ self.layers_per_block = layers_per_block
53
+
54
+ self.conv_in = CausalConv3d(in_channels, block_out_channels[0], kernel_size=3, stride=1)
55
+ self.mid_block = None
56
+ self.down_blocks = nn.ModuleList([])
57
+
58
+ # down
59
+ output_channel = block_out_channels[0]
60
+ for i, down_block_type in enumerate(down_block_types):
61
+ input_channel = output_channel
62
+ output_channel = block_out_channels[i]
63
+ is_final_block = i == len(block_out_channels) - 1
64
+ num_spatial_downsample_layers = int(np.log2(spatial_compression_ratio))
65
+ num_time_downsample_layers = int(np.log2(time_compression_ratio))
66
+
67
+ if time_compression_ratio == 4:
68
+ add_spatial_downsample = bool(i < num_spatial_downsample_layers)
69
+ add_time_downsample = bool(
70
+ i >= (len(block_out_channels) - 1 - num_time_downsample_layers)
71
+ and not is_final_block
72
+ )
73
+ else:
74
+ raise ValueError(f"Unsupported time_compression_ratio: {time_compression_ratio}.")
75
+
76
+ downsample_stride_HW = (2, 2) if add_spatial_downsample else (1, 1)
77
+ downsample_stride_T = (2,) if add_time_downsample else (1,)
78
+ downsample_stride = tuple(downsample_stride_T + downsample_stride_HW)
79
+ down_block = get_down_block3d(
80
+ down_block_type,
81
+ num_layers=self.layers_per_block,
82
+ in_channels=input_channel,
83
+ out_channels=output_channel,
84
+ add_downsample=bool(add_spatial_downsample or add_time_downsample),
85
+ downsample_stride=downsample_stride,
86
+ resnet_eps=1e-6,
87
+ downsample_padding=0,
88
+ resnet_act_fn=act_fn,
89
+ resnet_groups=norm_num_groups,
90
+ attention_head_dim=output_channel,
91
+ temb_channels=None,
92
+ )
93
+ self.down_blocks.append(down_block)
94
+
95
+ # mid
96
+ self.mid_block = UNetMidBlockCausal3D(
97
+ in_channels=block_out_channels[-1],
98
+ resnet_eps=1e-6,
99
+ resnet_act_fn=act_fn,
100
+ output_scale_factor=1,
101
+ resnet_time_scale_shift="default",
102
+ attention_head_dim=block_out_channels[-1],
103
+ resnet_groups=norm_num_groups,
104
+ temb_channels=None,
105
+ add_attention=mid_block_add_attention,
106
+ )
107
+
108
+ # out
109
+ self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[-1], num_groups=norm_num_groups, eps=1e-6)
110
+ self.conv_act = nn.SiLU()
111
+
112
+ conv_out_channels = 2 * out_channels if double_z else out_channels
113
+ self.conv_out = CausalConv3d(block_out_channels[-1], conv_out_channels, kernel_size=3)
114
+
115
+ def forward(self, sample: torch.FloatTensor) -> torch.FloatTensor:
116
+ r"""The forward method of the `EncoderCausal3D` class."""
117
+ assert len(sample.shape) == 5, "The input tensor should have 5 dimensions"
118
+
119
+ sample = self.conv_in(sample)
120
+
121
+ # down
122
+ for down_block in self.down_blocks:
123
+ sample = down_block(sample)
124
+
125
+ # middle
126
+ sample = self.mid_block(sample)
127
+
128
+ # post-process
129
+ sample = self.conv_norm_out(sample)
130
+ sample = self.conv_act(sample)
131
+ sample = self.conv_out(sample)
132
+
133
+ return sample
134
+
135
+
136
+ class DecoderCausal3D(nn.Module):
137
+ r"""
138
+ The `DecoderCausal3D` layer of a variational autoencoder that decodes its latent representation into an output sample.
139
+ """
140
+
141
+ def __init__(
142
+ self,
143
+ in_channels: int = 3,
144
+ out_channels: int = 3,
145
+ up_block_types: Tuple[str, ...] = ("UpDecoderBlockCausal3D",),
146
+ block_out_channels: Tuple[int, ...] = (64,),
147
+ layers_per_block: int = 2,
148
+ norm_num_groups: int = 32,
149
+ act_fn: str = "silu",
150
+ norm_type: str = "group", # group, spatial
151
+ mid_block_add_attention=True,
152
+ time_compression_ratio: int = 4,
153
+ spatial_compression_ratio: int = 8,
154
+ ):
155
+ super().__init__()
156
+ self.layers_per_block = layers_per_block
157
+
158
+ self.conv_in = CausalConv3d(in_channels, block_out_channels[-1], kernel_size=3, stride=1)
159
+ self.mid_block = None
160
+ self.up_blocks = nn.ModuleList([])
161
+
162
+ temb_channels = in_channels if norm_type == "spatial" else None
163
+
164
+ # mid
165
+ self.mid_block = UNetMidBlockCausal3D(
166
+ in_channels=block_out_channels[-1],
167
+ resnet_eps=1e-6,
168
+ resnet_act_fn=act_fn,
169
+ output_scale_factor=1,
170
+ resnet_time_scale_shift="default" if norm_type == "group" else norm_type,
171
+ attention_head_dim=block_out_channels[-1],
172
+ resnet_groups=norm_num_groups,
173
+ temb_channels=temb_channels,
174
+ add_attention=mid_block_add_attention,
175
+ )
176
+
177
+ # up
178
+ reversed_block_out_channels = list(reversed(block_out_channels))
179
+ output_channel = reversed_block_out_channels[0]
180
+ for i, up_block_type in enumerate(up_block_types):
181
+ prev_output_channel = output_channel
182
+ output_channel = reversed_block_out_channels[i]
183
+ is_final_block = i == len(block_out_channels) - 1
184
+ num_spatial_upsample_layers = int(np.log2(spatial_compression_ratio))
185
+ num_time_upsample_layers = int(np.log2(time_compression_ratio))
186
+
187
+ if time_compression_ratio == 4:
188
+ add_spatial_upsample = bool(i < num_spatial_upsample_layers)
189
+ add_time_upsample = bool(
190
+ i >= len(block_out_channels) - 1 - num_time_upsample_layers
191
+ and not is_final_block
192
+ )
193
+ else:
194
+ raise ValueError(f"Unsupported time_compression_ratio: {time_compression_ratio}.")
195
+
196
+ upsample_scale_factor_HW = (2, 2) if add_spatial_upsample else (1, 1)
197
+ upsample_scale_factor_T = (2,) if add_time_upsample else (1,)
198
+ upsample_scale_factor = tuple(upsample_scale_factor_T + upsample_scale_factor_HW)
199
+ up_block = get_up_block3d(
200
+ up_block_type,
201
+ num_layers=self.layers_per_block + 1,
202
+ in_channels=prev_output_channel,
203
+ out_channels=output_channel,
204
+ prev_output_channel=None,
205
+ add_upsample=bool(add_spatial_upsample or add_time_upsample),
206
+ upsample_scale_factor=upsample_scale_factor,
207
+ resnet_eps=1e-6,
208
+ resnet_act_fn=act_fn,
209
+ resnet_groups=norm_num_groups,
210
+ attention_head_dim=output_channel,
211
+ temb_channels=temb_channels,
212
+ resnet_time_scale_shift=norm_type,
213
+ )
214
+ self.up_blocks.append(up_block)
215
+ prev_output_channel = output_channel
216
+
217
+ # out
218
+ if norm_type == "spatial":
219
+ self.conv_norm_out = SpatialNorm(block_out_channels[0], temb_channels)
220
+ else:
221
+ self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=1e-6)
222
+ self.conv_act = nn.SiLU()
223
+ self.conv_out = CausalConv3d(block_out_channels[0], out_channels, kernel_size=3)
224
+
225
+ self.gradient_checkpointing = False
226
+
227
+ def forward(
228
+ self,
229
+ sample: torch.FloatTensor,
230
+ latent_embeds: Optional[torch.FloatTensor] = None,
231
+ ) -> torch.FloatTensor:
232
+ r"""The forward method of the `DecoderCausal3D` class."""
233
+ assert len(sample.shape) == 5, "The input tensor should have 5 dimensions."
234
+
235
+ sample = self.conv_in(sample)
236
+
237
+ upscale_dtype = next(iter(self.up_blocks.parameters())).dtype
238
+ if self.training and self.gradient_checkpointing:
239
+
240
+ def create_custom_forward(module):
241
+ def custom_forward(*inputs):
242
+ return module(*inputs)
243
+
244
+ return custom_forward
245
+
246
+ if is_torch_version(">=", "1.11.0"):
247
+ # middle
248
+ sample = torch.utils.checkpoint.checkpoint(
249
+ create_custom_forward(self.mid_block),
250
+ sample,
251
+ latent_embeds,
252
+ use_reentrant=False,
253
+ )
254
+ sample = sample.to(upscale_dtype)
255
+
256
+ # up
257
+ for up_block in self.up_blocks:
258
+ sample = torch.utils.checkpoint.checkpoint(
259
+ create_custom_forward(up_block),
260
+ sample,
261
+ latent_embeds,
262
+ use_reentrant=False,
263
+ )
264
+ else:
265
+ # middle
266
+ sample = torch.utils.checkpoint.checkpoint(
267
+ create_custom_forward(self.mid_block), sample, latent_embeds
268
+ )
269
+ sample = sample.to(upscale_dtype)
270
+
271
+ # up
272
+ for up_block in self.up_blocks:
273
+ sample = torch.utils.checkpoint.checkpoint(create_custom_forward(up_block), sample, latent_embeds)
274
+ else:
275
+ # middle
276
+ sample = self.mid_block(sample, latent_embeds)
277
+ sample = sample.to(upscale_dtype)
278
+
279
+ # up
280
+ for up_block in self.up_blocks:
281
+ sample = up_block(sample, latent_embeds)
282
+
283
+ # post-process
284
+ if latent_embeds is None:
285
+ sample = self.conv_norm_out(sample)
286
+ else:
287
+ sample = self.conv_norm_out(sample, latent_embeds)
288
+ sample = self.conv_act(sample)
289
+ sample = self.conv_out(sample)
290
+
291
+ return sample
292
+
293
+
294
+ class DiagonalGaussianDistribution(object):
295
+ def __init__(self, parameters: torch.Tensor, deterministic: bool = False):
296
+ if parameters.ndim == 3:
297
+ dim = 2 # (B, L, C)
298
+ elif parameters.ndim == 5 or parameters.ndim == 4:
299
+ dim = 1 # (B, C, T, H ,W) / (B, C, H, W)
300
+ else:
301
+ raise NotImplementedError
302
+ self.parameters = parameters
303
+ self.mean, self.logvar = torch.chunk(parameters, 2, dim=dim)
304
+ self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
305
+ self.deterministic = deterministic
306
+ self.std = torch.exp(0.5 * self.logvar)
307
+ self.var = torch.exp(self.logvar)
308
+ if self.deterministic:
309
+ self.var = self.std = torch.zeros_like(
310
+ self.mean, device=self.parameters.device, dtype=self.parameters.dtype
311
+ )
312
+
313
+ def sample(self, generator: Optional[torch.Generator] = None) -> torch.FloatTensor:
314
+ # make sure sample is on the same device as the parameters and has same dtype
315
+ sample = randn_tensor(
316
+ self.mean.shape,
317
+ generator=generator,
318
+ device=self.parameters.device,
319
+ dtype=self.parameters.dtype,
320
+ )
321
+ x = self.mean + self.std * sample
322
+ return x
323
+
324
+ def kl(self, other: "DiagonalGaussianDistribution" = None) -> torch.Tensor:
325
+ if self.deterministic:
326
+ return torch.Tensor([0.0])
327
+ else:
328
+ reduce_dim = list(range(1, self.mean.ndim))
329
+ if other is None:
330
+ return 0.5 * torch.sum(
331
+ torch.pow(self.mean, 2) + self.var - 1.0 - self.logvar,
332
+ dim=reduce_dim,
333
+ )
334
+ else:
335
+ return 0.5 * torch.sum(
336
+ torch.pow(self.mean - other.mean, 2) / other.var
337
+ + self.var / other.var
338
+ - 1.0
339
+ - self.logvar
340
+ + other.logvar,
341
+ dim=reduce_dim,
342
+ )
343
+
344
+ def nll(self, sample: torch.Tensor, dims: Tuple[int, ...] = [1, 2, 3]) -> torch.Tensor:
345
+ if self.deterministic:
346
+ return torch.Tensor([0.0])
347
+ logtwopi = np.log(2.0 * np.pi)
348
+ return 0.5 * torch.sum(
349
+ logtwopi + self.logvar +
350
+ torch.pow(sample - self.mean, 2) / self.var,
351
+ dim=dims,
352
+ )
353
+
354
+ def mode(self) -> torch.Tensor:
355
+ return self.mean