-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathnode_adv.py
More file actions
1757 lines (1523 loc) · 78.1 KB
/
node_adv.py
File metadata and controls
1757 lines (1523 loc) · 78.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2025 yuanyuan-spec
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import os
import sys
import inspect
from typing import Any, Dict, List, Optional, Union
import torch
import loguru
import re
from PIL import Image
import numpy as np
import torchvision.transforms as transforms
from diffusers.utils.torch_utils import randn_tensor
from diffusers.utils import BaseOutput
from torch import distributed as dist
import subprocess
from diffusers.utils.torch_utils import randn_tensor
from hyvideo.utils.multitask_utils import (
merge_tensor_by_mask,
)
from hyvideo.commons import (
PRECISION_TO_TYPE, auto_offload_model, get_gpu_memory, is_sparse_attn_supported, is_angelslim_available
)
from hyvideo.models.autoencoders import hunyuanvideo_15_vae
from hyvideo.models.transformers.hunyuanvideo_1_5_transformer import HunyuanVideo_1_5_DiffusionTransformer
from hyvideo.models.transformers.modules.upsample import SRTo720pUpsampler, SRTo1080pUpsampler
from hyvideo.models.vision_encoder import VisionEncoder
from hyvideo.models.text_encoders import TextEncoder, PROMPT_TEMPLATE
from hyvideo.schedulers.scheduling_flow_match_discrete import FlowMatchDiscreteScheduler
from hyvideo.models.transformers.modules.upsample import SRTo720pUpsampler, SRTo1080pUpsampler
from hyvideo.utils.data_utils import (
generate_crop_size_list, get_closest_ratio, resize_and_center_crop,
)
from hyvideo.pipelines.pipeline_utils import (retrieve_timesteps, rescale_noise_cfg)
from hyvideo.commons import (SR_PIPELINE_CONFIGS, TRANSFORMER_VERSION_TO_SR_VERSION)
from einops import rearrange
from hyvideo.models.autoencoders import hunyuanvideo_15_vae
from hyvideo.models.text_encoders.byT5 import load_glyph_byT5_v2
from hyvideo.models.text_encoders.byT5.format_prompt import MultilingualPromptFormat
from hyvideo.commons.parallel_states import get_parallel_state
from hyvideo.commons.infer_state import get_infer_state
import comfy.model_management as mm
import comfy.utils
import folder_paths
from pathlib import Path
from typing import List
import shutil
target_size_config = {
"360p": {"bucket_hw_base_size": 480, "bucket_hw_bucket_stride": 16},
"480p": {"bucket_hw_base_size": 640, "bucket_hw_bucket_stride": 16},
"720p": {"bucket_hw_base_size": 960, "bucket_hw_bucket_stride": 16},
"1080p": {"bucket_hw_base_size": 1440, "bucket_hw_bucket_stride": 16},
}
dtype_options = {
"float32": torch.float32,
"float64": torch.float64,
"float16": torch.float16,
"bfloat16": torch.bfloat16,
"uint8": torch.uint8,
"int8": torch.int8,
"int16": torch.int16,
"int32": torch.int32,
"int64": torch.int64,
}
def run_cmd(cmd):
result = subprocess.run(cmd, shell=True, capture_output=True, text=True,check=True)
return result.stdout
def get_immediate_subdirectories(folder_path: str) -> List[str]:
path = Path(folder_path)
return ["None"] + sorted([str(item) for item in path.iterdir() if item.is_dir()])
def get_model_dir_path(model_dir):
all_paths = folder_paths.get_folder_paths(model_dir)
for path in all_paths:
if "ComfyUI/models" in path.replace("\\", "/"):
return path
return all_paths[0] if all_paths else ""
def tensor_to_pil(comfyui_tensor):
if comfyui_tensor is None:
return None
image_np = comfyui_tensor[0].cpu().numpy()
image_np = (image_np * 255).astype(np.uint8)
return Image.fromarray(image_np)
def get_closest_resolution_given_reference_image(reference_image,target_resolution):
"""
Get closest supported resolution for a reference image.
Args:
reference_image: PIL Image or numpy array.
target_resolution: Target resolution string (e.g., "720p", "1080p").
Returns:
tuple[int, int]: (height, width) of closest supported resolution.
"""
assert reference_image is not None
if isinstance(reference_image, Image.Image):
origin_size = reference_image.size
elif isinstance(reference_image, np.ndarray):
H, W, C = reference_image.shape
origin_size = (W, H)
else:
raise ValueError(f"Unsupported reference_image type: {type(reference_image)}. Must be PIL Image or numpy array")
return get_closest_resolution_given_original_size(origin_size, target_resolution)
def get_closest_resolution_given_original_size(origin_size,target_size):
"""
Get closest supported resolution for given original size and targetresolution.
Args:
origin_size: Tuple of (width, height) of original image.
target_size: Target resolution string (e.g., "720p", "1080p").
Returns:
tuple[int, int]: (height, width) of closest supported resolution.
"""
bucket_hw_base_size = target_size_config[target_size]["bucket_hw_base_size"]
bucket_hw_bucket_stride = target_size_config[target_size]["bucket_hw_bucket_stride"]
assert bucket_hw_base_size in [128, 256, 480, 512, 640, 720, 960, 1440], \
f"bucket_hw_base_size must be in [128, 256, 480, 512, 640, 720, 960, 1440], but got {bucket_hw_base_size}"
crop_size_list = generate_crop_size_list(bucket_hw_base_size, bucket_hw_bucket_stride)
aspect_ratios = np.array([round(float(h) / float(w), 5) for h, w in crop_size_list])
closest_size, closest_ratio = get_closest_ratio(origin_size[1], origin_size[0], aspect_ratios, crop_size_list)
height = closest_size[0]
width = closest_size[1]
return height, width
def register_dir():
comfyui_root = os.path.dirname(folder_paths.__file__)
model_dir_list = ["diffusion_models"]
for model_dir in model_dir_list:
folder_paths.add_model_folder_path(model_dir, os.path.join(folder_paths.models_dir, model_dir))
register_dir()
# class HyVideoSRModelLoader:
# @classmethod
# def INPUT_TYPES(s):
# return {
# "required": {
# "path": (get_immediate_subdirectories(get_model_dir_path("upscale_models")),),
# "sr_version": (["720p_sr_distilled", "1080p_sr_distilled"], {"default": "720p_sr_distilled"}),
# "transformer_dtype": (["float32","float64","float16","bfloat16","uint8","int8","int16","int32","int64"], {"default": "bfloat16"}),
# },
# "optional": {
# }
# }
# RETURN_TYPES = ("HYVID15TRANSFORMER", "HYVID15UPASAMPLER", )
# RETURN_NAMES = ("transformer", "upsampler",)
# FUNCTION = "loadmodel"
# CATEGORY = "HunyuanVideoWrapper1.5"
# def loadmodel(self, path, sr_version, transformer_dtype="bfloat16"):
# device = mm.get_torch_device()
# if path == "None":
# path = os.path.join(folder_paths.models_dir, "upscale_models", "hyvideo15")
# if not os.path.exists(path):
# tmp_path = folder_paths.get_temp_directory()
# run_cmd(f"hf download tencent/HunyuanVideo-1.5 --include upsampler --local-dir {tmp_path}")
# run_cmd(f"mv {tmp_path}/upsampler {path}")
# transformer = HunyuanVideo_1_5_DiffusionTransformer.from_pretrained(os.path.join(path, sr_version), torch_dtype=dtype_options[transformer_dtype]).to(device)
# upsampler_cls = SRTo720pUpsampler if "720p" in sr_version else SRTo1080pUpsampler
# upsampler = upsampler_cls.from_pretrained(os.path.join(path, sr_version)).to(device)
# return transformer, upsampler
class HyVideoTransformerLoader:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"path": (get_immediate_subdirectories(os.path.join(folder_paths.models_dir,"diffusion_models")),),
"resolution": (["480p", "720p"], {"default": "480p"}),
"task_type": (["t2v", "i2v"], {"default": "i2v"}),
"transformer_dtype": (["float32","float64","float16","bfloat16","uint8","int8","int16","int32","int64"], {"default": "bfloat16"}),
},
"optional": {
"attn_mode": (["flash", "flex-block-attn", "ptm_sparse_attn","flash3",], {"default": "flash"}),
"force_sparse_attn": ("BOOLEAN", {"default": False, "tooltip": "Force to use sparse attention even if the model is not trained with sparse attention."}),
}
}
RETURN_TYPES = ("HYVID15TRANSFORMER", "HYVID15TRANSFORMERCONFIG",)
FUNCTION = "loadmodel"
CATEGORY = "HunyuanVideoWrapper1.5"
def loadmodel(self, path, resolution, task_type, transformer_dtype, attn_mode="flash", force_sparse_attn=False):
device = torch.device('cuda')
transformer_version = f"{resolution}_{task_type}"
if path == "None":
path = os.path.join(folder_paths.models_dir, "diffusion_models", "hyvideo15")
if not os.path.exists(os.path.join(path,transformer_version)):
os.makedirs(path, exist_ok=True)
tmp_path = folder_paths.get_temp_directory()
run_cmd(f"hf download tencent/HunyuanVideo-1.5 --include \"transformer/{transformer_version}/*\" --local-dir {tmp_path}")
shutil.move(os.path.join(tmp_path, "transformer",transformer_version), path)
# run_cmd(f"mv {tmp_path}/transformer {path}")
if force_sparse_attn:
if not is_sparse_attn_supported():
raise RuntimeError(f"Current GPU is {torch.cuda.get_device_properties(0).name}, which does not support sparse attention.")
if transformer.config.attn_mode != 'flex-block-attn':
loguru.logger.warning(
f"The transformer loaded ({transformer_version}) is not trained with sparse attention. Forcing to use sparse attention may lead to artifacts in the generated video."
f"To enable sparse attention, we recommend loading `{transformer_version}_distilled_sparse` instead."
)
transformer.set_attn_mode('flex-block-attn')
transformer = HunyuanVideo_1_5_DiffusionTransformer.from_pretrained(os.path.join(path, transformer_version), torch_dtype=dtype_options[transformer_dtype]).to(device)
transformer.set_attn_mode(attn_mode)
return (transformer, transformer.config)
class HyVideoVaeLoader:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"path": (get_immediate_subdirectories(get_model_dir_path("vae")),),
},
"optional": {
"enable_tile_parallelism": ("BOOLEAN", {"default": True, "tooltip": "Enable tile parallelism for VAE inference to reduce memory usage."}),
}
}
RETURN_TYPES = ("HYVID15VAE",)
RETURN_NAMES = ("model", )
FUNCTION = "loadmodel"
CATEGORY = "HunyuanVideoWrapper1.5"
def loadmodel(self, path, enable_tile_parallelism=True):
device = torch.device('cuda')
vae_inference_config = self._get_vae_inference_config()
if path == "None":
path = os.path.join(folder_paths.models_dir, "vae", "hyvideo15")
if not os.path.exists(path):
tmp_path = folder_paths.get_temp_directory()
run_cmd(f"hf download tencent/HunyuanVideo-1.5 --include \"vae/*\" --local-dir {tmp_path}")
shutil.move(os.path.join(tmp_path, "vae"), path)
# run_cmd(f"mv {tmp_path}/vae {path}")
vae = hunyuanvideo_15_vae.AutoencoderKLConv3D.from_pretrained(
path,
torch_dtype=vae_inference_config['dtype']
).to(device)
vae.set_tile_sample_min_size(vae_inference_config['sample_size'], vae_inference_config['tile_overlap_factor'])
if enable_tile_parallelism:
vae.enable_tile_parallelism()
return (vae,)
def _get_vae_inference_config(self,memory_limitation=None):
if memory_limitation is None:
memory_limitation = get_gpu_memory()
GB = 1024 * 1024 * 1024
if memory_limitation < 28 * GB:
sample_size = 128
tile_overlap_factor = 0.25
dtype = torch.float16
else:
sample_size = 256
tile_overlap_factor = 0.25
dtype = torch.float32
return {'sample_size': sample_size, 'tile_overlap_factor': tile_overlap_factor, 'dtype': dtype}
class HyTextEncoderLoader:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"path": (get_immediate_subdirectories(get_model_dir_path("text_encoders")),),
"text_encoder_type": (["llm","None"], {"default": "llm"}),
"load_device": (["main_device", "offload_device"], {"default": "main_device"}),
},
"optional": {
}
}
RETURN_TYPES = ("HYVID15TEXTENCODER", "HYVID15TEXTENCODER",)
RETURN_NAMES = ("text_encoder", "text_encoder_2",)
FUNCTION = "loadmodel"
CATEGORY = "HunyuanVideoWrapper1.5"
def loadmodel(self, path, text_encoder_type, load_device):
device = mm.get_torch_device() if load_device == "main_device" else mm.unet_offload_device()
if path == "None":
text_encoder_type = "llm"
path = os.path.join(folder_paths.models_dir, "text_encoders", "hyvideo15")
if not os.path.exists(path):
os.makedirs(path, exist_ok=True)
run_cmd(f"hf download Qwen/Qwen2.5-VL-7B-Instruct --local-dir {path}/{text_encoder_type}")
text_encoder_path=os.path.join(path, text_encoder_type)
else:
if text_encoder_type == "None":
text_encoder_path = path
else:
text_encoder_path = text_encoder_path=os.path.join(path, text_encoder_type)
text_encoder = TextEncoder(
text_encoder_type="llm",
tokenizer_type="llm",
text_encoder_path=text_encoder_path,
max_length=1000,
text_encoder_precision="fp16",
prompt_template=PROMPT_TEMPLATE['li-dit-encode-image-json'],
prompt_template_video=PROMPT_TEMPLATE['li-dit-encode-video-json'],
hidden_state_skip_layer=2,
apply_final_norm=False,
reproduce=False,
logger=loguru.logger,
device=device,
)
text_encoder_2 = None
return text_encoder, text_encoder_2
class HyVideoVisionEncoderLoader:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"path": (get_immediate_subdirectories(get_model_dir_path("clip_vision")),),
"vision_encoder_type": (["siglip","None"], {"default": "siglip"}),
"load_device": (["main_device", "offload_device"], {"default": "main_device"}),
},
"optional": {
"hf_token": ("STRING",{"default":""}),
}
}
RETURN_TYPES = ("HYVID15VISIONENCODER",)
RETURN_NAMES = ("model", )
FUNCTION = "loadmodel"
CATEGORY = "HunyuanVideoWrapper1.5"
def loadmodel(self, path, vision_encoder_type, load_device, hf_token):
device = mm.get_torch_device() if load_device == "main_device" else mm.unet_offload_device()
if path == "None":
vision_encoder_type = "siglip" # 只能自动下载这一类
path = os.path.join(folder_paths.models_dir, "clip_vision", "hyvideo15")
if not os.path.exists(path):
os.makedirs(path, exist_ok=True)
run_cmd(f"hf download black-forest-labs/FLUX.1-Redux-dev --local-dir {path}/{vision_encoder_type} --token {hf_token}")
vision_encoder_path = os.path.join(path, vision_encoder_type)
else:
if vision_encoder_type == "None":
vision_encoder_path = path
else:
vision_encoder_path = os.path.join(path, vision_encoder_type)
vision_encoder = VisionEncoder(
vision_encoder_type="siglip", # 这个输入给算法必须是固定值
vision_encoder_precision='fp16',
vision_encoder_path=vision_encoder_path,
processor_type=None,
processor_path=None,
output_key=None,
logger=loguru.logger,
device=device,
)
return (vision_encoder,)
class HyVideoByt5Loader:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"byt5_path": (get_immediate_subdirectories(get_model_dir_path("text_encoders")),),
"glyph_path": (get_immediate_subdirectories(get_model_dir_path("text_encoders")),),
"load_device": (["main_device", "offload_device"], {"default": "main_device"}),
},
"optional": {
"byt5_max_length": ("INT", {"default": 256, "tooltip": "Maximum length for byT5 tokenization."}),
}
}
RETURN_TYPES = ("HYVID15BYT5KWARGS","HYVID15MULTILINGUALPROMPTFORMAT")
RETURN_NAMES = ("byt5_kwargs","prompt_format" )
FUNCTION = "loadmodel"
CATEGORY = "HunyuanVideoWrapper1.5"
def loadmodel(self, load_device, byt5_max_length,byt5_path,glyph_path):
device = mm.get_torch_device() if load_device == "main_device" else mm.unet_offload_device()
if byt5_path == "None":
path = os.path.join(folder_paths.models_dir, "text_encoders")
byt5_path = os.path.join(path, "byt5-small")
if not os.path.exists(byt5_path):
run_cmd(f"hf download google/byt5-small --local-dir {path}/byt5-small")
if glyph_path == "None":
path = os.path.join(folder_paths.models_dir, "text_encoders")
glyph_path = os.path.join(path, "Glyph-SDXL-v2")
if not os.path.exists(glyph_path):
run_cmd(f"modelscope download --model AI-ModelScope/Glyph-SDXL-v2 --local_dir {path}/Glyph-SDXL-v2")
byt5_kwargs, prompt_format = self._load_byt5(byt5_path,glyph_path, True, byt5_max_length, device=device,)
return (byt5_kwargs, prompt_format)
def _load_byt5(self, byt5_path,glyph_path, glyph_byT5_v2, byt5_max_length, device):
if not glyph_byT5_v2:
byt5_kwargs = None
prompt_format = None
return byt5_kwargs, prompt_format
try:
glyph_root = glyph_path
if not os.path.exists(glyph_root):
raise RuntimeError(
f"Glyph checkpoint not found from '{glyph_root}'. \n"
"Please download from https://modelscope.cn/models/AI-ModelScope/Glyph-SDXL-v2/files.\n\n"
"- Required files:\n"
" Glyph-SDXL-v2\n"
" ├── assets\n"
" │ ├── color_idx.json\n"
" │ └── multilingual_10-lang_idx.json\n"
" └── checkpoints\n"
" └── byt5_model.pt\n"
)
byT5_google_path = byt5_path
if not os.path.exists(byT5_google_path):
loguru.logger.warning(f"ByT5 google path not found from: {byT5_google_path}. Try downloading from https://huggingface.co/google/byt5-small.")
byT5_google_path = "google/byt5-small"
multilingual_prompt_format_color_path = os.path.join(glyph_root, "assets/color_idx.json")
multilingual_prompt_format_font_path = os.path.join(glyph_root, "assets/multilingual_10-lang_idx.json")
byt5_args = dict(
byT5_google_path=byT5_google_path,
byT5_ckpt_path=os.path.join(glyph_root, "checkpoints/byt5_model.pt"),
multilingual_prompt_format_color_path=multilingual_prompt_format_color_path,
multilingual_prompt_format_font_path=multilingual_prompt_format_font_path,
byt5_max_length=byt5_max_length
)
byt5_kwargs = load_glyph_byT5_v2(byt5_args, device=device)
prompt_format = MultilingualPromptFormat(
font_path=multilingual_prompt_format_font_path,
color_path=multilingual_prompt_format_color_path
)
return byt5_kwargs, prompt_format
except Exception as e:
raise RuntimeError("Error loading byT5 glyph processor") from e
class HyVideoCFG:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"prompt": ("STRING", {"default": "A close-up shot captures a scene on a polished, light-colored granite kitchen counter, illuminated by soft natural light from an unseen window. Initially, the frame focuses on a tall, clear glass filled with golden, translucent apple juice standing next to a single, shiny red apple with a green leaf still attached to its stem. The camera moves horizontally to the right. As the shot progresses, a white ceramic plate smoothly enters the frame, revealing a fresh arrangement of about seven or eight more apples, a mix of vibrant reds and greens, piled neatly upon it. A shallow depth of field keeps the focus sharply on the fruit and glass, while the kitchen backsplash in the background remains softly blurred. The scene is in a realistic style.", "multiline": True} ),
"negative_prompt": ("STRING", {"default": "Aerial view, aerial view, overexposed, low quality, deformation, a poor composition, bad hands, bad teeth, bad eyes, bad limbs, distortion", "multiline": True, "tooltip": "Negative prompt(s) that describe what should NOT be shown in the generated video."} ),
"prompt_rewrite": ("BOOLEAN", {"default": False, "tooltip": "Whether to rewrite the prompt."}),
"flow_shift": ("FLOAT",{"default": None, "tooltip": "When the resolution is 480p, the recommended shift value is 5, and when the resolution is 720p, the recommended shift value is 7. If you do not set this value, it will be automatically configured according to the recommendations of this rule."}),
},
"optional": {
"guidance_scale": ("FLOAT", {"default": 6.0, "tooltip": "Scale to encourage the model to better follow the prompt. `guidance_scale > 1` enables classifier-free guidance."}),
"num_videos_per_prompt": ("INT", {"default": 1, "min": 1, "max": 100, "step": 1, "tooltip": "Number of videos to generate per prompt."} ),
"video_length": ("INT", {"default": 121, "min": 1, "max": 200, "step": 1, "tooltip": "Number of frames to generate."} ),
"seed": ("INT", {"default": 0, "min": 0, "max": 2147483647, "step": 1} ),
"transformer_config": ("HYVID15TRANSFORMERCONFIG", ),
"task_type": (["t2v", "i2v"], {"default": "i2v"}),
"sr_transformer_config": ("HYVID15TRANSFORMERCONFIG", {"default": None}),
"reference_image": ("IMAGE", {"default": None, "tooltip": "Reference image."}),
}
}
RETURN_TYPES = ("HYVID15CFG","HYVID15CFG",)
RETURN_NAMES = ("hyvid_cfg","hyvid_sr_cfg",)
FUNCTION = "config"
CATEGORY = "HunyuanVideoWrapper1.5"
DESCRIPTION = "To use CFG with HunyuanVideo"
def config(self, prompt, negative_prompt, guidance_scale, num_videos_per_prompt, video_length, seed, transformer_config, flow_shift=None, prompt_rewrite=False, reference_image=None,task_type="i2v",sr_transformer_config=None):
if flow_shift is None or flow_shift == 0:
if isinstance(transformer_config.ideal_resolution, str) and transformer_config.ideal_resolution == "480p":
flow_shift = 5.0
else:
flow_shift = 7.0
generator = torch.Generator(device=torch.device('cpu')).manual_seed(seed)
self.prompt = prompt
self.reference_image = reference_image
self.task_type = task_type
# Rewrite prompt with QwenClient
if prompt_rewrite:
from hyvideo.utils.rewrite.rewrite_utils import run_prompt_rewrite
if not dist.is_initialized() or get_parallel_state().sp_rank == 0:
prompt = run_prompt_rewrite(prompt, reference_image, task_type)
if dist.is_initialized() and get_parallel_state().sp_enabled:
obj_list = [prompt]
dist.broadcast_object_list(obj_list, group_src=0, group=get_parallel_state().sp_group)
prompt = obj_list[0]
self.prompt = prompt
self.reference_image = reference_image
self.task_type = transformer_config.ideal_task
if prompt is not None and isinstance(prompt, str):
batch_size = 1
elif prompt is not None and isinstance(prompt, list):
batch_size = len(prompt)
else:
batch_size = 1
if prompt_rewrite:
prompt = self._prompt_rewrite(prompt)
scheduler = FlowMatchDiscreteScheduler(
shift=flow_shift,
reverse=True,
solver="euler",
)
cfg_dict = {
"prompt": prompt,
"negative_prompt": negative_prompt,
"guidance_scale": guidance_scale,
"num_videos_per_prompt": num_videos_per_prompt,
"video_length": video_length,
"seed": seed,
"task_type": task_type,
"generator": generator,
"scheduler": scheduler,
"transformer_config": transformer_config,
"sr_transformer_config": sr_transformer_config,
"batch_size": batch_size,
"flow_shift": flow_shift,
}
return (cfg_dict,)
def _prompt_rewrite(self, prompt):
from hyvideo.utils.rewrite.rewrite_utils import run_prompt_rewrite
if not dist.is_initialized() or get_parallel_state().sp_rank == 0:
try:
prompt = run_prompt_rewrite(prompt, self.reference_image, self.task_type)
except Exception as e:
loguru.logger.warning(f"Failed to rewrite prompt: {e}")
prompt = prompt
if dist.is_initialized() and get_parallel_state().sp_enabled:
obj_list = [prompt]
# not use group_src to support old PyTorch
group_src_rank = dist.get_global_rank(get_parallel_state().sp_group, 0)
dist.broadcast_object_list(obj_list, src=group_src_rank, group=get_parallel_state().sp_group)
prompt = obj_list[0]
return prompt
def _prepare_extra_func_kwargs(self, func, kwargs):
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
# and should be between [0, 1]
extra_step_kwargs = {}
for k, v in kwargs.items():
accepts = k in set(inspect.signature(func).parameters.keys())
if accepts:
extra_step_kwargs[k] = v
return extra_step_kwargs
def _cmd(self,cmd):
result = subprocess.run(cmd, shell=True, capture_output=True, text=True,check=True)
def get_model_dir_path(model_dir):
all_paths = folder_paths.get_folder_paths(model_dir)
for path in all_paths:
if "ComfyUI/models" in path.replace("\\", "/"):
return path
return all_paths[0] if all_paths else ""
class HyVideoTextEncode:
@classmethod
def INPUT_TYPES(s):
return {"required": {
"text_encoder": ("HYVID15TEXTENCODER",),
"text_encoder_2": ("HYVID15TEXTENCODER",),
"hyvid_cfg": ("HYVID15CFG", ),
},
"optional": {
"enable_offloading": ("BOOLEAN", {"default": True}),
"clip_skip": ("INT", {"default": 0, "tooltip": "Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that the output of the pre-final layer will be used for computing the prompt embeddings."}),
}
}
RETURN_TYPES = ("HYVIDEMBEDS", )
RETURN_NAMES = ("hyvid_embeds",)
FUNCTION = "process"
CATEGORY = "HunyuanVideoWrapper1.5"
def process(self, text_encoder, text_encoder_2, hyvid_cfg, enable_offloading=True, clip_skip=0):
negative_prompt = hyvid_cfg["negative_prompt"]
do_classifier_free_guidance = hyvid_cfg["guidance_scale"] > 1
device = mm.text_encoder_offload_device() if enable_offloading else mm.text_encoder_device()
self.text_len = text_encoder.max_length
self.text_encoder = text_encoder
with auto_offload_model(text_encoder, device, enabled=enable_offloading):
(
prompt_embeds,
negative_prompt_embeds,
prompt_mask,
negative_prompt_mask,
) = self._encode_prompt(
hyvid_cfg["prompt"],
device,
hyvid_cfg["num_videos_per_prompt"],
do_classifier_free_guidance,
negative_prompt,
clip_skip=None if clip_skip == 0 else clip_skip,
data_type="video",
text_encoder=text_encoder,
)
# Encode prompts with second encoder if available
if text_encoder_2 is not None:
with auto_offload_model(text_encoder_2, device, enabled=enable_offloading):
(
prompt_embeds_2,
negative_prompt_embeds_2,
prompt_mask_2,
negative_prompt_mask_2,
) = self._encode_prompt(
hyvid_cfg["prompt"],
device,
hyvid_cfg["num_videos_per_prompt"],
do_classifier_free_guidance,
negative_prompt,
clip_skip=None if clip_skip == 0 else clip_skip,
text_encoder=text_encoder_2,
data_type="video",
)
else:
prompt_embeds_2 = None
negative_prompt_embeds_2 = None
prompt_mask_2 = None
negative_prompt_mask_2 = None
if do_classifier_free_guidance:
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
if prompt_mask is not None:
prompt_mask = torch.cat([negative_prompt_mask, prompt_mask])
if prompt_embeds_2 is not None:
prompt_embeds_2 = torch.cat([negative_prompt_embeds_2, prompt_embeds_2])
if prompt_mask_2 is not None:
prompt_mask_2 = torch.cat([negative_prompt_mask_2, prompt_mask_2])
hyvid_embeds = {
"prompt_embeds": prompt_embeds,
"negative_prompt_embeds": negative_prompt_embeds,
"prompt_mask": prompt_mask,
"negative_prompt_mask": negative_prompt_mask,
"prompt_embeds_2": prompt_embeds_2,
"negative_prompt_embeds_2": negative_prompt_embeds_2,
"prompt_mask_2": prompt_mask_2,
"negative_prompt_mask_2": negative_prompt_mask_2,
}
return (hyvid_embeds, )
def _encode_prompt(
self,
prompt,
device,
num_videos_per_prompt,
do_classifier_free_guidance,
negative_prompt=None,
prompt_embeds: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
negative_prompt_embeds: Optional[torch.Tensor] = None,
negative_attention_mask: Optional[torch.Tensor] = None,
clip_skip: Optional[int] = None,
text_encoder: Optional[TextEncoder] = None,
data_type: Optional[str] = "image",
):
r"""
Encodes the prompt into text encoder hidden states.
Args:
prompt (`str` or `List[str]`, *optional*):
prompt to be encoded
device: (`torch.device`):
torch device
num_videos_per_prompt (`int`):
number of videos that should be generated per prompt
do_classifier_free_guidance (`bool`):
whether to use classifier free guidance or not
negative_prompt (`str` or `List[str]`, *optional*):
The prompt or prompts not to guide the video generation. If not defined, one has to pass
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
less than `1`).
prompt_embeds (`torch.Tensor`, *optional*):
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
provided, text embeddings will be generated from `prompt` input argument.
attention_mask (`torch.Tensor`, *optional*):
negative_prompt_embeds (`torch.Tensor`, *optional*):
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
argument.
negative_attention_mask (`torch.Tensor`, *optional*):
clip_skip (`int`, *optional*):
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
the output of the pre-final layer will be used for computing the prompt embeddings.
text_encoder (TextEncoder, *optional*):
Text encoder to use. If None, uses the pipeline's default text encoder.
data_type (`str`, *optional*):
Type of data being encoded. Defaults to "image".
"""
if text_encoder is None:
text_encoder = self.text_encoder
if prompt is not None and isinstance(prompt, str):
batch_size = 1
elif prompt is not None and isinstance(prompt, list):
batch_size = len(prompt)
else:
batch_size = prompt_embeds.shape[0]
if prompt_embeds is None:
text_inputs = text_encoder.text2tokens(prompt, data_type=data_type, max_length=self.text_len)
if clip_skip is None:
prompt_outputs = text_encoder.encode(
text_inputs, data_type=data_type, device=device
)
prompt_embeds = prompt_outputs.hidden_state
else:
prompt_outputs = text_encoder.encode(
text_inputs,
output_hidden_states=True,
data_type=data_type,
device=device,
)
# Access the `hidden_states` first, that contains a tuple of
# all the hidden states from the encoder layers. Then index into
# the tuple to access the hidden states from the desired layer.
prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]
# We also need to apply the final LayerNorm here to not mess with the
# representations. The `last_hidden_states` that we typically use for
# obtaining the final prompt representations passes through the LayerNorm
# layer.
prompt_embeds = text_encoder.model.text_model.final_layer_norm(
prompt_embeds
)
attention_mask = prompt_outputs.attention_mask
if attention_mask is not None:
attention_mask = attention_mask.to(device)
bs_embed, seq_len = attention_mask.shape
attention_mask = attention_mask.repeat(1, num_videos_per_prompt)
attention_mask = attention_mask.view(
bs_embed * num_videos_per_prompt, seq_len
)
if text_encoder is not None:
prompt_embeds_dtype = text_encoder.dtype
elif self.transformer is not None:
prompt_embeds_dtype = self.transformer.dtype
else:
prompt_embeds_dtype = prompt_embeds.dtype
prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
if prompt_embeds.ndim == 2:
bs_embed, _ = prompt_embeds.shape
# duplicate text embeddings for each generation per prompt, using mps friendly method
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt)
prompt_embeds = prompt_embeds.view(bs_embed * num_videos_per_prompt, -1)
else:
bs_embed, seq_len, _ = prompt_embeds.shape
# duplicate text embeddings for each generation per prompt, using mps friendly method
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
prompt_embeds = prompt_embeds.view(
bs_embed * num_videos_per_prompt, seq_len, -1
)
# get unconditional embeddings for classifier free guidance
if do_classifier_free_guidance and negative_prompt_embeds is None:
uncond_tokens: List[str]
if negative_prompt is None:
uncond_tokens = [""] * batch_size
elif prompt is not None and type(prompt) is not type(negative_prompt):
raise TypeError(
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
f" {type(prompt)}."
)
elif isinstance(negative_prompt, str):
uncond_tokens = [negative_prompt]
elif batch_size != len(negative_prompt):
raise ValueError(
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
" the batch size of `prompt`."
)
else:
uncond_tokens = negative_prompt
uncond_input = text_encoder.text2tokens(uncond_tokens, data_type=data_type, max_length=self.text_len)
negative_prompt_outputs = text_encoder.encode(uncond_input, data_type=data_type, is_uncond=True)
negative_prompt_embeds = negative_prompt_outputs.hidden_state
negative_attention_mask = negative_prompt_outputs.attention_mask
if negative_attention_mask is not None:
negative_attention_mask = negative_attention_mask.to(device)
_, seq_len = negative_attention_mask.shape
negative_attention_mask = negative_attention_mask.repeat(1, num_videos_per_prompt)
negative_attention_mask = negative_attention_mask.view(batch_size * num_videos_per_prompt, seq_len)
if do_classifier_free_guidance:
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
seq_len = negative_prompt_embeds.shape[1]
negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
if negative_prompt_embeds.ndim == 2:
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_videos_per_prompt)
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_videos_per_prompt, -1)
else:
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_videos_per_prompt, 1)
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
return (
prompt_embeds,
negative_prompt_embeds,
attention_mask,
negative_attention_mask,
)
class HyVideoGlyphByT5:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"byt5_kwargs": ("HYVID15BYT5KWARGS", ),
"prompt_format" : ("HYVID15MULTILINGUALPROMPTFORMAT", ),
},
"optional": {
"enable_offloading": ("BOOLEAN", {"default": True}),
"hyvid_cfg": ("HYVID15CFG", ),
}
}
RETURN_TYPES = ("HYVID15EXTRAKWARGS", )
RETURN_NAMES = ("extra_kwargs",)
FUNCTION = "process"
CATEGORY = "HunyuanVideoWrapper1.5"
def process(self, byt5_kwargs, hyvid_cfg, prompt_format, enable_offloading=True):
extra_kwargs = {}
device = mm.text_encoder_offload_device() if enable_offloading else mm.text_encoder_device()
self.byt5_kwargs = byt5_kwargs
self.prompt_format = prompt_format
self.hyvid_cfg = hyvid_cfg
with auto_offload_model(byt5_kwargs["byt5_model"], device, enabled=enable_offloading):
extra_kwargs = self._prepare_byt5_embeddings(hyvid_cfg["prompt"], device)
return (extra_kwargs,)
def _prepare_byt5_embeddings(self, prompts, device):
"""
Prepare byT5 embeddings for both positive and negative prompts.
Args:
prompts: List of prompt strings or single prompt string.
device: Target device for tensors.
Returns:
dict: Dictionary containing:
- "byt5_text_states": Combined embeddings tensor.
- "byt5_text_mask": Combined attention mask tensor.
Returns empty dict if glyph_byT5_v2 is disabled.
"""
if isinstance(prompts, str):
prompt_list = [prompts]
elif isinstance(prompts, list):
prompt_list = prompts
else:
raise ValueError("prompts must be str or list of str")
positive_embeddings = []
positive_masks = []
negative_embeddings = []
negative_masks = []
for prompt in prompt_list:
pos_emb, pos_mask = self._process_single_byt5_prompt(prompt, device)
positive_embeddings.append(pos_emb)
positive_masks.append(pos_mask)
if self.hyvid_cfg["guidance_scale"] > 1:
neg_emb, neg_mask = self._process_single_byt5_prompt("", device)
negative_embeddings.append(neg_emb)
negative_masks.append(neg_mask)
byt5_positive = torch.cat(positive_embeddings, dim=0)
byt5_positive_mask = torch.cat(positive_masks, dim=0)
if self.hyvid_cfg["guidance_scale"] > 1:
byt5_negative = torch.cat(negative_embeddings, dim=0)
byt5_negative_mask = torch.cat(negative_masks, dim=0)
byt5_embeddings = torch.cat([byt5_negative, byt5_positive], dim=0)
byt5_masks = torch.cat([byt5_negative_mask, byt5_positive_mask], dim=0)
else:
byt5_embeddings = byt5_positive
byt5_masks = byt5_positive_mask
return {
"byt5_text_states": byt5_embeddings,
"byt5_text_mask": byt5_masks
}
def _process_single_byt5_prompt(self, prompt_text, device):
"""
Process a single prompt for byT5 encoding.
Args:
prompt_text: The prompt text to process.
device: Target device for tensors.
Returns:
tuple[torch.Tensor, torch.Tensor]:
- byt5_embeddings: Encoded embeddings tensor.
- byt5_mask: Attention mask tensor.
"""
byt5_embeddings = torch.zeros((1, self.byt5_kwargs["byt5_max_length"], 1472), device=device)
byt5_mask = torch.zeros((1, self.byt5_kwargs["byt5_max_length"]), device=device, dtype=torch.int64)
glyph_texts = self._extract_glyph_texts(prompt_text)
if len(glyph_texts) > 0:
text_styles = [{'color': None, 'font-family': None} for _ in range(len(glyph_texts))]
formatted_text = self.prompt_format.format_prompt(glyph_texts, text_styles)
text_ids, text_mask = self._get_byt5_text_tokens(
self.byt5_kwargs["byt5_tokenizer"], self.byt5_kwargs["byt5_max_length"], formatted_text
)
text_ids = text_ids.to(device=device)
text_mask = text_mask.to(device=device)
byt5_outputs = self.byt5_kwargs["byt5_model"](text_ids, attention_mask=text_mask.float())
byt5_embeddings = byt5_outputs[0]
byt5_mask = text_mask
return byt5_embeddings, byt5_mask
def _extract_glyph_texts(self, prompt):
"""
Extract glyph texts from prompt using regex pattern.
Args:
prompt: Input prompt string containing quoted text.
Returns:
List[str]: List of extracted glyph texts (deduplicated if multiple).
"""
pattern = r'\"(.*?)\"|“(.*?)”'
matches = re.findall(pattern, prompt)
result = [match[0] or match[1] for match in matches]
result = list(dict.fromkeys(result)) if len(result) > 1 else result