File size: 53,897 Bytes
8f06535
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
import os
import sys
import argparse
import importlib.util
from pathlib import Path

import numpy as np
import torch
from diffusers import (CogVideoXDDIMScheduler, DDIMScheduler,
                       DPMSolverMultistepScheduler,
                       EulerAncestralDiscreteScheduler, EulerDiscreteScheduler,
                       PNDMScheduler)
from PIL import Image

current_file_path = os.path.abspath(__file__)
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
for project_root in project_roots:
    sys.path.insert(0, project_root) if project_root not in sys.path else None

from videox_fun.dist import set_multi_gpus_devices, shard_model
from videox_fun.models import (AutoencoderKLCogVideoX,
                              CogVideoXTransformer3DModel, T5EncoderModel,
                              T5Tokenizer)
from videox_fun.pipeline import (CogVideoXFunInpaintPipeline,
                                CogVideoXFunPipeline)
from videox_fun.data.dataset_image_video import (
    CAMERA_POSES_CSV_NAME,
    EMG_CONTEXT_SEC,
    compute_normalization_stats_from_participant,
    extract_emg_bbox_rows,
    frame_name_to_idx,
    list_frame_files,
    load_bimanual_signal_df,
    load_camera_pose_feature_df,
    load_camera_pose_time_dict,
    load_participant_bbox_df,
    relative_pose_to_features,
    resample_feature_window,
    zero_emg_bbox_rows,
    zero_head_pose_rows,
)
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
                                              convert_weight_dtype_wrapper)
from videox_fun.utils.lora_utils import create_network
from videox_fun.utils.utils import get_image_to_video_latent, save_videos_grid
from videox_fun.utils.hypernet import VideoHyperDream
import json


def load_module_from_path(module_name: str, module_path: str):
    spec = importlib.util.spec_from_file_location(module_name, module_path)
    module = importlib.util.module_from_spec(spec)
    assert spec.loader is not None
    spec.loader.exec_module(module)
    return module


class MultimodalReferenceEncoder(torch.nn.Module):
    def __init__(self, encoder_model: torch.nn.Module):
        super().__init__()
        self.encoder_model = encoder_model

    def forward(self, ref_values):
        emg_x = ref_values["emg_values"].float()
        hand_bbox_x = ref_values["hand_bbox_values"].float()
        head_pose_x = ref_values["head_pose_values"].float()

        hand_camera_x = torch.cat([hand_bbox_x, head_pose_x], dim=-1)
        emg_features = self.encoder_model.emg_encoder(emg_x)
        hand_camera_features = self.encoder_model.hand_camera_encoder(hand_camera_x)
        emg_features = torch.nn.functional.adaptive_avg_pool1d(
            emg_features.transpose(1, 2),
            hand_camera_features.shape[1],
        ).transpose(1, 2)
        fused = torch.cat([emg_features, hand_camera_features], dim=-2)
        return fused


def parse_args():
    parser = argparse.ArgumentParser(description="CogVideoX-Fun I2V Inference with LiLoRA and HyperNetwork")
    
    # GPU memory mode
    parser.add_argument("--gpu_memory_mode", type=str, default="model_full_load",
                       choices=["model_full_load", "model_full_load_and_qfloat8", "model_cpu_offload", 
                               "model_cpu_offload_and_qfloat8", "sequential_cpu_offload"],
                       help="GPU memory mode")
    
    # Multi GPUs config
    parser.add_argument("--ulysses_degree", type=int, default=1, help="Ulysses degree for multi-GPU inference")
    parser.add_argument("--ring_degree", type=int, default=1, help="Ring degree for multi-GPU inference")
    parser.add_argument("--fsdp_dit", action="store_true", help="Use FSDP for transformer")
    parser.add_argument("--fsdp_text_encoder", action="store_true", default=True, help="Use FSDP for text encoder")
    parser.add_argument("--compile_dit", action="store_true", help="Compile transformer for speedup")
    
    # Model paths
    parser.add_argument("--model_name", type=str, default="models/Diffusion_Transformer/CogVideoX-Fun-V1.1-2b-InP",
                       help="Path to pretrained model")
    parser.add_argument("--sampler_name", type=str, default="DDIM_Origin",
                       choices=["Euler", "Euler A", "DPM++", "PNDM", "DDIM_Cog", "DDIM_Origin"],
                       help="Sampler name")
    parser.add_argument("--transformer_path", type=str, default=None, help="Path to transformer checkpoint")
    parser.add_argument("--vae_path", type=str, default=None, help="Path to VAE checkpoint")
    
    # LiLoRA and HyperNetwork paths
    parser.add_argument("--lilora_path", type=str, default=None, help="Path to LiLoRA weights (.safetensors)")
    parser.add_argument("--hypernetwork_path", type=str, default=None, help="Path to HyperNetwork weights (.safetensors)")
    parser.add_argument("--hypernetwork_input_dim", type=int, default=None,
                       help="Override HyperNetwork input feature dimension. If unset, infer from checkpoint or multimodal encoder.")
    parser.add_argument("--multimodal_ref_encoder_ckpt_path", type=str, default=None,
                       help="Checkpoint for the EMG multimodal reference encoder used during training.")
    parser.add_argument("--multimodal_ref_encoder_script", type=str, default=None,
                       help="Python script that defines MultimodalEMGMaskedAutoencoder and load_emg2pose_backbone.")
    parser.add_argument("--emg2pose_ckpt_path", type=str, default=None,
                       help="Path to the EMG2Pose backbone checkpoint required by the multimodal reference encoder.")
    parser.add_argument("--emg2pose_repo", type=str, default=None,
                       help="Path to the EMG2Pose repository required by the multimodal reference encoder.")
    parser.add_argument("--emg_normalization_participant", type=str, default=None,
                       help="Participant directory used to compute EMG normalization stats when building ref_values from raw CSVs.")
    parser.add_argument("--emg_camera_pose_csv_name", type=str, default=CAMERA_POSES_CSV_NAME,
                       help="Camera pose CSV filename under each participant directory.")
    parser.add_argument("--emg_bbox_csv_name", type=str, default="hand_bboxes.csv",
                       help="Hand bbox CSV filename under each participant directory.")
    parser.add_argument("--emg_context_sec", type=float, default=EMG_CONTEXT_SEC,
                       help="Extra sensor context before/after the selected video clip.")
    
    # LiLoRA params (should match training config)
    parser.add_argument("--lora_rank", type=int, default=1, help="LiLoRA rank")
    parser.add_argument("--lora_down_dim", type=int, default=200, help="LiLoRA down dimension")
    parser.add_argument("--lora_up_dim", type=int, default=100, help="LiLoRA up dimension")
    parser.add_argument("--lora_weight", type=float, default=0.55, help="LiLoRA weight multiplier")
    
    # Input data paths
    parser.add_argument("--first_frame_path", type=str, default=None, help="Path to first frame image")
    parser.add_argument("--ref_video_path", type=str, default=None, help="Path to reference video for HyperNetwork")
    
    # Video generation params
    parser.add_argument("--video_length", type=int, default=49, help="Number of frames to generate")
    parser.add_argument("--fps", type=int, default=8, help="FPS for output video")
    parser.add_argument("--partial_video_length", type=int, default=None, 
                       help="Length of each sub video segment for ultra long video generation")
    parser.add_argument("--overlap_video_length", type=int, default=4, 
                       help="Overlap length between segments for ultra long video generation")
    
    # Weight dtype
    parser.add_argument("--weight_dtype", type=str, default="bfloat16", choices=["bfloat16", "float16", "float32"],
                       help="Weight dtype")
    
    # Prompts
    parser.add_argument("--prompt", type=str, default=None, help="Prompt for video generation")
    parser.add_argument("--negative_prompt", type=str, 
                       default="The video is not of a high quality, it has a low resolution. "
                               "Watermark present in each frame. The background is solid. "
                               "Strange body and strange trajectory. Distortion.",
                       help="Negative prompt")
    
    # Inference params
    parser.add_argument("--guidance_scale", type=float, default=6.0, help="Guidance scale")
    parser.add_argument("--seed", type=int, default=43, help="Random seed")
    parser.add_argument("--num_inference_steps", type=int, default=50, help="Number of inference steps")
    
    # Output
    parser.add_argument("--save_path", type=str, default="samples/cogvideox-fun-videos_i2v", 
                       help="Path to save generated videos")
    
    # Test set (JSON)
    parser.add_argument("--test_json_path", type=str, default=None, 
                       help="Path to JSON file containing test samples")
    
    return parser.parse_args()


def _resolve_path(path_value, base_dir=None):
    if path_value is None:
        return None
    if os.path.isabs(path_value):
        return path_value
    if base_dir is not None:
        candidate = os.path.join(base_dir, path_value)
        if os.path.exists(candidate):
            return candidate
    return os.path.abspath(path_value)


def _as_numpy_float32(value):
    if value is None:
        return None
    if torch.is_tensor(value):
        value = value.detach().cpu().numpy()
    return np.asarray(value, dtype=np.float32)


def _coerce_ref_values_dict(ref_values):
    if ref_values is None:
        return None

    required = ("emg_values", "hand_bbox_values", "head_pose_values")
    if not all(key in ref_values for key in required):
        missing = [key for key in required if key not in ref_values]
        raise ValueError(f"ref_values is missing required keys: {missing}")

    out = {}
    for key in required:
        out[key] = _as_numpy_float32(ref_values[key])
    return out


def _infer_participant_path(sample_info, first_frame_path):
    participant_path = sample_info.get("participant_path")
    if participant_path is not None:
        return participant_path

    if first_frame_path is None:
        return None

    frame_dir = os.path.dirname(first_frame_path)
    if os.path.basename(frame_dir) == "frames":
        return os.path.dirname(frame_dir)
    return os.path.dirname(first_frame_path)


def _infer_frame_indices(sample_info, first_frame_path, video_length):
    frame_indices = sample_info.get("frame_indices")
    if frame_indices is not None:
        return [int(x) for x in frame_indices]

    frame_dir = sample_info.get("frames_dir")
    if frame_dir is None and first_frame_path is not None:
        frame_dir = os.path.dirname(first_frame_path)

    if first_frame_path is None:
        return None

    try:
        start_idx = frame_name_to_idx(first_frame_path)
    except Exception:
        start_idx = None

    if frame_dir is not None and os.path.isdir(frame_dir):
        try:
            frame_paths = list_frame_files(frame_dir)
            filename_to_pos = {os.path.basename(path): idx for idx, path in enumerate(frame_paths)}
            start_pos = filename_to_pos.get(os.path.basename(first_frame_path))
            if start_pos is not None:
                selected = frame_paths[start_pos:start_pos + video_length]
                if len(selected) == video_length:
                    return [frame_name_to_idx(path) for path in selected]
        except Exception:
            pass

    if start_idx is not None:
        return [start_idx + i for i in range(video_length)]
    return None


def build_emg_ref_values(sample_info, first_frame_path, video_length, args):
    direct_ref_values = sample_info.get("ref_values")
    if direct_ref_values is not None:
        return _coerce_ref_values_dict(direct_ref_values)

    if all(key in sample_info for key in ("emg_values", "hand_bbox_values", "head_pose_values")):
        return _coerce_ref_values_dict(sample_info)

    participant_path = _infer_participant_path(sample_info, first_frame_path)
    frame_indices = _infer_frame_indices(sample_info, first_frame_path, video_length)
    if participant_path is None or frame_indices is None:
        return None

    participant_path = os.path.abspath(participant_path)
    pose_time_dict = load_camera_pose_time_dict(participant_path, args.emg_camera_pose_csv_name)
    hand_data, signal_cols = load_bimanual_signal_df(participant_path)

    clip_times = []
    for frame_idx in frame_indices:
        if frame_idx not in pose_time_dict:
            raise ValueError(f"Missing pose timestamp for frame_idx={frame_idx} in {participant_path}")
        clip_times.append(float(pose_time_dict[frame_idx]))

    sensor_start_t = min(clip_times) - args.emg_context_sec
    sensor_end_t = max(clip_times) + args.emg_context_sec

    emg_signal_length = int(sample_info.get("emg_fixed_signal_length") or sample_info.get("signal_length") or 1883)
    left_emg = resample_feature_window(
        hand_data["left_time"],
        hand_data["left_data"],
        sensor_start_t,
        sensor_end_t,
        emg_signal_length,
    )
    right_emg = resample_feature_window(
        hand_data["right_time"],
        hand_data["right_data"],
        sensor_start_t,
        sensor_end_t,
        emg_signal_length,
    )
    emg_values = np.concatenate([left_emg, right_emg], axis=1).astype(np.float32)

    norm_participant = args.emg_normalization_participant
    if norm_participant is not None:
        norm_participant = os.path.abspath(norm_participant)
        norm_mean, norm_std, _ = compute_normalization_stats_from_participant(norm_participant)
        emg_values = ((emg_values - norm_mean) / norm_std).astype(np.float32)

    try:
        bbox_df = load_participant_bbox_df(participant_path, args.emg_bbox_csv_name).set_index("frame_idx")
        bbox_values, _ = extract_emg_bbox_rows(bbox_df, frame_indices)
    except Exception:
        bbox_values, _ = zero_emg_bbox_rows(frame_indices)

    try:
        pose_df = load_camera_pose_feature_df(participant_path, args.emg_camera_pose_csv_name).set_index("frame_idx")
        if frame_indices[0] not in pose_df.index:
            raise ValueError(f"Reference frame {frame_indices[0]} missing from pose CSV")
        ref_row = pose_df.loc[frame_indices[0]]
        from videox_fun.data.dataset_image_video import pose_row_to_T

        T_ref = pose_row_to_T(ref_row["tx"], ref_row["ty"], ref_row["tz"], ref_row["qx"], ref_row["qy"], ref_row["qz"], ref_row["qw"])
        pose_rows = []
        for frame_idx in frame_indices:
            if frame_idx not in pose_df.index:
                raise ValueError(f"Frame {frame_idx} missing from pose CSV")
            row = pose_df.loc[frame_idx]
            T_curr = pose_row_to_T(row["tx"], row["ty"], row["tz"], row["qx"], row["qy"], row["qz"], row["qw"])
            pose_rows.append(relative_pose_to_features(T_ref, T_curr))
        head_pose_values = np.asarray(pose_rows, dtype=np.float32)
    except Exception:
        head_pose_values, _ = zero_head_pose_rows(frame_indices)

    return {
        "emg_values": emg_values.astype(np.float32),
        "hand_bbox_values": bbox_values.astype(np.float32),
        "head_pose_values": head_pose_values.astype(np.float32),
    }


def build_multimodal_ref_encoder(args, sample_ref_values, weight_dtype):
    missing = []
    if args.multimodal_ref_encoder_ckpt_path is None:
        missing.append("--multimodal_ref_encoder_ckpt_path")
    if args.multimodal_ref_encoder_script is None:
        missing.append("--multimodal_ref_encoder_script")
    if args.emg2pose_ckpt_path is None:
        missing.append("--emg2pose_ckpt_path")
    if args.emg2pose_repo is None:
        missing.append("--emg2pose_repo")
    if missing:
        raise ValueError(f"EMG-conditioned inference requires: {', '.join(missing)}")

    videox_module = load_module_from_path(
        "videox_emg_multimodal_infer",
        args.multimodal_ref_encoder_script,
    )
    checkpoint = torch.load(args.multimodal_ref_encoder_ckpt_path, map_location="cpu")
    checkpoint_config = checkpoint.get("config", {})

    emg_channels = int(sample_ref_values["emg_values"].shape[-1])
    bbox_channels = int(sample_ref_values["hand_bbox_values"].shape[-1])
    pose_channels = int(sample_ref_values["head_pose_values"].shape[-1])
    hand_camera_channels = bbox_channels + pose_channels
    seq_len = int(sample_ref_values["emg_values"].shape[0])

    emg_backbone = videox_module.load_emg2pose_backbone(
        str(args.emg2pose_ckpt_path),
        str(args.emg2pose_repo),
    )
    encoder_model = videox_module.MultimodalEMGMaskedAutoencoder(
        emg_channels=emg_channels,
        hand_camera_channels=hand_camera_channels,
        bbox_channels=bbox_channels,
        pose_channels=pose_channels,
        emg_backbone=emg_backbone,
        seq_len=seq_len,
        hidden_dim=checkpoint_config.get("hidden_dim", 256),
        latent_dim=checkpoint_config.get("latent_dim", 256),
        kernel_size=checkpoint_config.get("kernel_size", 3),
        dilation_rates=checkpoint_config.get("dilation_rates", [1, 2, 4, 8, 16, 32]),
        encoder_stacks=checkpoint_config.get("encoder_stacks", 3),
        decoder_stacks=checkpoint_config.get("decoder_stacks", 2),
        dropout=checkpoint_config.get("dropout", 0.1),
        derivative_loss_weight=checkpoint_config.get("derivative_loss_weight", 0.1),
        frequency_loss_weight=checkpoint_config.get("frequency_loss_weight", 0.05),
        high_freq_weight=checkpoint_config.get("high_freq_weight", 2.0),
    )
    encoder_model.load_state_dict(checkpoint["model"], strict=True)
    encoder_model.eval()
    encoder_model.requires_grad_(False)
    encoder_model = encoder_model.to(dtype=weight_dtype)
    return MultimodalReferenceEncoder(encoder_model), int(checkpoint_config.get("latent_dim", 256))


def get_hypernetwork_input_dim(args, hyper_state_dict, multimodal_input_dim=None):
    if args.hypernetwork_input_dim is not None:
        return int(args.hypernetwork_input_dim)
    if multimodal_input_dim is not None:
        return int(multimodal_input_dim)
    feature_proj_weight = hyper_state_dict.get("img_weight_generator.feature_proj.weight")
    if feature_proj_weight is None:
        raise ValueError("Could not infer HyperNetwork input dim from checkpoint. Please pass --hypernetwork_input_dim.")
    return int(feature_proj_weight.shape[1])


def apply_hypernetwork_weights(hypernetwork, lilora_network, ref_features):
    _, weight_list = hypernetwork(ref_features)
    for weight, lora_layer in zip(weight_list, lilora_network.unet_loras):
        if weight.dim() == 3:
            weight = weight.view(weight.size(0), -1)
        elif weight.dim() == 2:
            if weight.size(0) == 1:
                weight = weight.view(-1)
            else:
                weight = weight.view(weight.size(0), -1)
        elif weight.dim() == 1:
            weight = weight.view(-1)
        lora_layer.update_weight(weight)
        lora_layer.down_aux.data = lora_layer.down_aux.data.to(dtype=weight.dtype)
        lora_layer.up_aux.data = lora_layer.up_aux.data.to(dtype=weight.dtype)
    return len(weight_list)

def load_ref_video_frames(ref_video_path, target_size, num_frames=None):
    """
    Load reference video frames from video file or image directory
    
    Args:
        ref_video_path: Path to video file or directory containing image frames
        target_size: Target size [height, width] for resizing
        num_frames: Number of frames to load (if None, load all available)
    
    Returns:
        ref_pixel_values: Tensor of shape [B, F, C, H, W] in 0~1 range
    """
    import cv2
    
    target_h, target_w = target_size
    
    ref_frames = []
    
    if os.path.isfile(ref_video_path):
        cap = cv2.VideoCapture(ref_video_path)
        frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        
        if num_frames is None:
            num_frames = frame_count
        
        for i in range(num_frames):
            ret, frame = cap.read()
            if not ret:
                break
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            frame = Image.fromarray(frame)
            frame = frame.resize((target_w, target_h))
            ref_frames.append(np.array(frame))
        
        cap.release()
    elif os.path.isdir(ref_video_path):
        image_files = sorted([f for f in os.listdir(ref_video_path) if f.endswith(('.png', '.jpg', '.jpeg'))])
        
        if num_frames is None:
            num_frames = len(image_files)
        
        for i in range(num_frames):
            if i >= len(image_files):
                break
            frame = Image.open(os.path.join(ref_video_path, image_files[i])).convert('RGB')
            frame = frame.resize((target_w, target_h))
            ref_frames.append(np.array(frame))
    
    if len(ref_frames) == 0:
        raise ValueError(f"No frames loaded from {ref_video_path}")
    
    ref_frames_np = np.array(ref_frames)
    ref_frames_tensor = torch.from_numpy(ref_frames_np).float()
    ref_frames_tensor = ref_frames_tensor / 255.0
    
    ref_frames_tensor = ref_frames_tensor.unsqueeze(0)
    
    print(f"DEBUG: ref_frames_tensor shape after unsqueeze(0): {ref_frames_tensor.shape}")
    
    return ref_frames_tensor


def get_model_device(model):
    """安全获取模型实际设备,处理 CPU offload 模式"""
    try:
        params = list(model.parameters())
        if len(params) > 0:
            return params[0].device
        buffers = list(model.buffers())
        if len(buffers) > 0:
            return buffers[0].device
    except Exception:
        pass
    return torch.device("cpu")


def process_sample(
    pipeline,
    vae,
    device,
    weight_dtype,
    hypernetwork,
    lilora_network,
    multimodal_ref_encoder,
    sample_info,
    sample_size,
    args,
):
    """
    Process a single test sample
    
    Args:
        pipeline: CogVideoX pipeline
        vae: VAE model
        device: device
        weight_dtype: weight dtype
        hypernetwork: VideoHyperDream model (or None)
        lilora_network: LoRANetwork model (or None)
        sample_info: dict with first_frame_path, ref_video_path, text, video_name
        sample_size: [height, width]
        args: other arguments
    
    Returns:
        sample: generated video tensor
    """
    first_frame_path = sample_info.get('first_frame_path')
    ref_video_path = sample_info.get('ref_video_path')
    prompt = sample_info.get('text', '')
    video_name = sample_info.get('video_name', 'sample')
    
    # 如果 JSON 中没有提供 prompt,使用命令行参数中的默认值
    if not prompt or not prompt.strip():
        prompt = args.get('prompt', '')
        if prompt:
            print(f"Using prompt from command line: {prompt[:50]}...")
        else:
            print(f"Warning: No prompt provided for sample {video_name}")
            return None
    
    if first_frame_path is None or not os.path.exists(first_frame_path):
        print(f"Warning: first_frame_path not found: {first_frame_path}")
        return None
    
    input_video, input_video_mask, clip_image = get_image_to_video_latent(
        first_frame_path, None, video_length=args['video_length'], sample_size=sample_size
    )
    
    original_image = Image.open(first_frame_path).convert('RGB')
    original_width, original_height = original_image.size
    print(f"\n[Debug Input Video Processing]")
    print(f"[Debug Input] first_frame_path: {first_frame_path}")
    print(f"[Debug Input] Original image size: ({original_width}, {original_height})")
    print(f"[Debug Input] sample_size (after resize): {sample_size}")
    print(f"[Debug Input] input_video type: {type(input_video)}")
    if isinstance(input_video, torch.Tensor):
        print(f"[Debug Input] input_video shape: {input_video.shape}")
        if input_video.dim() == 5:
            B, C, F, H, W = input_video.shape
            print(f"[Debug Input] Input tensor: B={B}, C={C}, F={F}, H={H}, W={W}")
            print(f"[Debug Input] Height matches sample_size[0]: {H == sample_size[0]}, Width matches sample_size[1]: {W == sample_size[1]}")
    if input_video_mask is not None and isinstance(input_video_mask, torch.Tensor):
        print(f"[Debug Input] input_video_mask shape: {input_video_mask.shape}")
    print("-" * 40)
    
    if hypernetwork is not None and lilora_network is not None:
        emg_ref_values = build_emg_ref_values(sample_info, first_frame_path, args['video_length'], args['cli_args'])

        if emg_ref_values is not None:
            if multimodal_ref_encoder is None:
                multimodal_ref_encoder, _ = build_multimodal_ref_encoder(
                    args["cli_args"],
                    emg_ref_values,
                    weight_dtype,
                )
                multimodal_ref_encoder = multimodal_ref_encoder.to(device=device, dtype=weight_dtype)
                multimodal_ref_encoder.eval()

            ref_inputs = {
                key: torch.from_numpy(value).unsqueeze(0).to(device=device, dtype=weight_dtype)
                for key, value in emg_ref_values.items()
            }
            with torch.no_grad():
                ref_features = multimodal_ref_encoder(ref_inputs)
            updated_layers = apply_hypernetwork_weights(hypernetwork, lilora_network, ref_features)
            print(
                f"Updated {updated_layers} LiLoRA layers with multimodal EMG reference features "
                f"from sample {video_name}."
            )
        elif ref_video_path is not None and os.path.exists(ref_video_path):
            print(f"Generating weights from reference video: {ref_video_path}")
            ref_frames_tensor = load_ref_video_frames(ref_video_path, sample_size)
            _, F, _, _, _ = ref_frames_tensor.shape
            ref_pixel_values = ref_frames_tensor.permute(0, 4, 1, 2, 3).contiguous()
            ref_pixel_values = ref_pixel_values.to(dtype=weight_dtype)

            with torch.no_grad():
                vae_device = get_model_device(vae)
                ref_pixel_values = ref_pixel_values.to(device=vae_device, dtype=weight_dtype)
                ref_features = vae.encode(ref_pixel_values).latent_dist.sample()
                ref_features = ref_features * vae.config.scaling_factor

            updated_layers = apply_hypernetwork_weights(hypernetwork, lilora_network, ref_features)
            print(f"Updated {updated_layers} LiLoRA layers with hypernetwork weights from {F} reference frames.")
    
    generator = torch.Generator(device=device).manual_seed(args.get('seed', 43))
    
    with torch.no_grad():
        sample = pipeline(
            prompt,
            num_frames=args['video_length'],
            negative_prompt=args.get('negative_prompt', ''),
            height=sample_size[0],
            width=sample_size[1],
            generator=generator,
            guidance_scale=args.get('guidance_scale', 6.0),
            num_inference_steps=args.get('num_inference_steps', 50),
            video=input_video,
            mask_video=input_video_mask
        ).videos

    print(f"\n[Debug Pipeline Output @ Inference]")
    print(f"[Debug Pipeline] Original image size: ({original_width}, {original_height})")
    print(f"[Debug Pipeline] Sample size requested: ({sample_size[0]}, {sample_size[1]})")
    print(f"[Debug Pipeline] Pipeline output shape: {sample.shape}")
    
    if isinstance(sample, torch.Tensor):
        if sample.dim() == 5:
            B, C, F, H, W = sample.shape
            print(f"[Debug Pipeline] Output tensor shape: B={B}, C={C}, F={F}, H={H}, W={W}")
            
            expected_H = original_height
            expected_W = original_width
            print(f"\n[Debug Size Verification]")
            print(f"[Debug] Comparing: Original image ({original_height}, {original_width}) vs Output video ({H}, {W})")
            
            if H == expected_H and W == expected_W:
                print(f"[Debug] ✓ Size MATCH! Output matches original image size")
            else:
                print(f"[Debug] ✗ Size MISMATCH!")
                print(f"[Debug]   Expected: ({expected_H}, {expected_W})")
                print(f"[Debug]   Got:      ({H}, {W})")
                print(f"[Debug]   Difference: H={H-expected_H} ({((H-expected_H)/expected_H*100):.1f}%), W={W-expected_W} ({((W-expected_W)/expected_W*100):.1f}%)")
            
            if H != expected_H or W != expected_W:
                print(f"\n[Debug Analysis]")
                print(f"[Debug] VAE config - scaling_factor: {vae.config.scaling_factor}")
                print(f"[Debug] VAE config - latent_channels: {vae.config.latent_channels}")
                if hasattr(vae, 'config') and hasattr(vae.config, 'decoder'):
                    print(f"[Debug] VAE decoder will upsample by factor of 4x or 8x")
        else:
            print(f"[Debug Pipeline] Unexpected tensor dimensions: {sample.dim()}")
    
    print("-" * 80)
    
    return sample

def main():
    args = parse_args()
    
    # Convert weight dtype string to torch dtype
    weight_dtype_map = {
        "bfloat16": torch.bfloat16,
        "float16": torch.float16,
        "float32": torch.float32
    }
    weight_dtype = weight_dtype_map.get(args.weight_dtype, torch.bfloat16)
    
    # GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
    # model_full_load means that the entire model will be moved to the GPU.
    # 
    # model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
    # and the transformer model has been quantized to float8, which can save more GPU memory. 
    # 
    # model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
    # 
    # model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use, 
    # and the transformer model has been quantized to float8, which can save more GPU memory. 
    # 
    # sequential_cpu_offload means that each layer of the model will be moved to the CPU after use, 
    # resulting in slower speeds but saving a large amount of GPU memory.
    GPU_memory_mode     = args.gpu_memory_mode
    # Multi GPUs config
    # Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used. 
    # For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
    # If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
    ulysses_degree      = args.ulysses_degree
    ring_degree         = args.ring_degree
    # Use FSDP to save more GPU memory in multi gpus.
    fsdp_dit            = args.fsdp_dit
    fsdp_text_encoder   = args.fsdp_text_encoder
    # Compile will give a speedup in fixed resolution and need a little GPU memory. 
    # The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
    compile_dit         = args.compile_dit
    
    # Config and model path
    model_name          = args.model_name
    
    # Choose the sampler in "Euler" "Euler A" "DPM++" "PNDM" "DDIM_Cog" and "DDIM_Origin"
    sampler_name        = args.sampler_name
    
    # Load pretrained model if need
    transformer_path    = args.transformer_path
    vae_path            = args.vae_path
    
    # LiLoRA and HyperNetwork paths
    lilora_path         = args.lilora_path
    hypernetwork_path   = args.hypernetwork_path
    
    # Input data paths
    first_frame_path    = args.first_frame_path
    ref_video_path      = args.ref_video_path
    
    # LiLoRA params (should match training config)
    lora_rank           = args.lora_rank
    lora_down_dim       = args.lora_down_dim
    lora_up_dim         = args.lora_up_dim
    lora_weight         = args.lora_weight
    
    # Other params
    sample_size         = [384, 672]
    # V1.0 and V1.1 support up to 49 frames of video generation,
    # while V1.5 supports up to 85 frames.  
    video_length        = args.video_length
    fps                 = args.fps
    
    # If you want to generate ultra long videos, please set partial_video_length as the length of each sub video segment
    partial_video_length = args.partial_video_length
    overlap_video_length = args.overlap_video_length
    
    # If you want to generate from text, please set the validation_image_start = None and validation_image_end = None
    validation_image_start  = None  # Will be set from first_frame_path below
    validation_image_end    = None
    
    # Use first_frame_path for image-to-video generation
    # If first_frame_path is provided, it will be used as the starting frame
    # and sample_size will be set to match the first frame dimensions
    # Note: If test_json_path is provided, first_frame_path will be read from JSON
    if args.test_json_path is None:  # Only check when NOT using test JSON
        if first_frame_path is not None and os.path.exists(first_frame_path):
            first_frame = Image.open(first_frame_path).convert('RGB')
            W, H = first_frame.size
            sample_size = [H, W]  # PIL image.size is (W, H), sample_size should be [H, W]
            validation_image_start = first_frame_path
            validation_image_end = None
            print(f"Using first frame from: {first_frame_path}, sample_size: {sample_size}")
        else:
            raise ValueError("first_frame_path must be provided and exist for direct I2V inference")
    
    # HyperNetwork reference video path (required when using hypernetwork)
    # Reference video should be a video file path or a list of image frames
    # The reference video will be encoded by VAE and used by HyperNetwork to generate LiLoRA weights
    ref_video_path      = args.ref_video_path
    
    # prompts
    prompt                  = args.prompt
    negative_prompt         = args.negative_prompt
    guidance_scale          = args.guidance_scale
    seed                    = args.seed
    num_inference_steps     = args.num_inference_steps
    lora_weight             = args.lora_weight
    save_path               = args.save_path

    # 初始化多 GPU 设备
    device = set_multi_gpus_devices(ulysses_degree, ring_degree)

    transformer = CogVideoXTransformer3DModel.from_pretrained(
        model_name, 
        subfolder="transformer",
        low_cpu_mem_usage=True,
        torch_dtype=weight_dtype,
    ).to(weight_dtype)

    if transformer_path is not None:
        print(f"From checkpoint: {transformer_path}")
        if transformer_path.endswith("safetensors"):
            from safetensors.torch import load_file, safe_open
            state_dict = load_file(transformer_path)
        else:
            state_dict = torch.load(transformer_path, map_location="cpu")
        state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict

        m, u = transformer.load_state_dict(state_dict, strict=False)
        print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")

    # Get Vae
    vae = AutoencoderKLCogVideoX.from_pretrained(
        model_name, 
        subfolder="vae"
    ).to(weight_dtype)
    
    vae.enable_tiling()

    if vae_path is not None:
        print(f"From checkpoint: {vae_path}")
        if vae_path.endswith("safetensors"):
            from safetensors.torch import load_file, safe_open
            state_dict = load_file(vae_path)
        else:
            state_dict = torch.load(vae_path, map_location="cpu")
        state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict

        m, u = vae.load_state_dict(state_dict, strict=False)
        print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")

    # Get tokenizer and text_encoder
    tokenizer = T5Tokenizer.from_pretrained(
        model_name, subfolder="tokenizer"
    )
    text_encoder = T5EncoderModel.from_pretrained(
        model_name, subfolder="text_encoder", torch_dtype=weight_dtype
    )

    # Get Scheduler
    Chosen_Scheduler = scheduler_dict = {
        "Euler": EulerDiscreteScheduler,
        "Euler A": EulerAncestralDiscreteScheduler,
        "DPM++": DPMSolverMultistepScheduler, 
        "PNDM": PNDMScheduler,
        "DDIM_Cog": CogVideoXDDIMScheduler,
        "DDIM_Origin": DDIMScheduler,
    }[sampler_name]
    scheduler = Chosen_Scheduler.from_pretrained(
        model_name, 
        subfolder="scheduler"
    )

    if transformer.config.in_channels != vae.config.latent_channels:
        pipeline = CogVideoXFunInpaintPipeline(
            vae=vae,
            tokenizer=tokenizer,
            text_encoder=text_encoder,
            transformer=transformer,
            scheduler=scheduler,
        )
    else:
        pipeline = CogVideoXFunPipeline(
            vae=vae,
            tokenizer=tokenizer,
            text_encoder=text_encoder,
            transformer=transformer,
            scheduler=scheduler,
        )
    if ulysses_degree > 1 or ring_degree > 1:
        from functools import partial
        transformer.enable_multi_gpus_inference()
        if fsdp_dit:
            shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
            pipeline.transformer = shard_fn(pipeline.transformer)
            print("Add FSDP DIT")
        if fsdp_text_encoder:
            shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
            pipeline.text_encoder = shard_fn(pipeline.text_encoder)
            print("Add FSDP TEXT ENCODER")

    if compile_dit:
        for i in range(len(pipeline.transformer.transformer_blocks)):
            pipeline.transformer.transformer_blocks[i] = torch.compile(pipeline.transformer.transformer_blocks[i])
        print("Add Compile")

    if GPU_memory_mode == "sequential_cpu_offload":
        pipeline.enable_sequential_cpu_offload(device=device)
    elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
        convert_model_weight_to_float8(transformer, exclude_module_name=[], device=device)
        convert_weight_dtype_wrapper(transformer, weight_dtype)
        pipeline.enable_model_cpu_offload(device=device)
    elif GPU_memory_mode == "model_cpu_offload":
        pipeline.enable_model_cpu_offload(device=device)
    elif GPU_memory_mode == "model_full_load_and_qfloat8":
        convert_model_weight_to_float8(transformer, exclude_module_name=[], device=device)
        convert_weight_dtype_wrapper(transformer, weight_dtype)
        pipeline.to(device=device)
    else:
        pipeline.to(device=device)

    generator = torch.Generator(device=device).manual_seed(seed)

    lilora_network = None
    if lilora_path is not None:
        lora_weight_dim = (lora_down_dim + lora_up_dim) * lora_rank
        
        lilora_network = create_network(
            multiplier=lora_weight,
            network_dim=lora_rank,
            network_alpha=lora_weight,
            text_encoder=pipeline.text_encoder,
            transformer=pipeline.transformer,
            down_dim=lora_down_dim,
            up_dim=lora_up_dim,
            is_train=False,
        )
        lilora_network.apply_to(pipeline.text_encoder, pipeline.transformer, apply_text_encoder=False, apply_unet=True)
        
        from safetensors.torch import load_file
        lora_state_dict = load_file(lilora_path)
        info = lilora_network.load_weights(lilora_path)
        print(f"LiLoRA weights loaded from {lilora_path} (missing: {len(info.missing_keys)}, unexpected: {len(info.unexpected_keys)})")
        
        print(f"Total LoRA modules in UNet: {len(lilora_network.unet_loras)}")

    hypernetwork = None
    multimodal_ref_encoder = None
    if hypernetwork_path is not None and lilora_network is not None:
        from safetensors.torch import load_file
        
        lora_weight_dim = (lora_down_dim + lora_up_dim) * lora_rank
        weight_num = len(lilora_network.unet_loras)
        hyper_state_dict = load_file(hypernetwork_path)
        hypernetwork_input_dim = get_hypernetwork_input_dim(args, hyper_state_dict, None)
        
        print(
            f"Creating VideoHyperDream with weight_num={weight_num}, "
            f"weight_dim={lora_weight_dim}, video_feat_dim={hypernetwork_input_dim}"
        )
        
        hypernetwork = VideoHyperDream(
            video_feat_dim=hypernetwork_input_dim,
            weight_num=weight_num,
            weight_dim=lora_weight_dim,
        ).to(device=device, dtype=weight_dtype)
        
        hypernetwork.load_state_dict(hyper_state_dict, strict=False)
        hypernetwork.eval()
        
        if lilora_network is not None and len(lilora_network.unet_loras) > 0:
            hypernetwork.set_lilora(lilora_network.unet_loras)
            hypernetwork.set_device(device)
            print(f"HyperNetwork loaded. Connected to {len(lilora_network.unet_loras)} LiLoRA layers from create_network.")
        else:
            print("Warning: No LiLoRA layers found from create_network!")
            hypernetwork = None

    def save_results(sample, video_length, video_name=None):
        if not os.path.exists(save_path):
            os.makedirs(save_path, exist_ok=True)

        if video_name is None:
            index = len([path for path in os.listdir(save_path)]) + 1
            prefix = str(index).zfill(8)
            video_name = prefix

        if video_length == 1:
            video_path = os.path.join(save_path, video_name + ".png")

            image = sample[0, :, 0]
            image = image.transpose(0, 1).transpose(1, 2)
            image = (image * 255).numpy().astype(np.uint8)
            image = Image.fromarray(image)
            image.save(video_path)
        else:
            video_path = os.path.join(save_path, video_name + ".mp4")
            save_videos_grid(sample, video_path, fps=fps)
        
        print(f"Results saved to: {video_path}")
        return video_path

    def process_test_set():
        if args.test_json_path is None or not os.path.exists(args.test_json_path):
            print("No test JSON path provided or file not found.")
            return
        
        json_dir = os.path.dirname(os.path.abspath(args.test_json_path))
        
        with open(args.test_json_path, 'r') as f:
            test_data = json.load(f)
        
        if isinstance(test_data, list):
            samples = test_data
        elif isinstance(test_data, dict):
            samples = test_data.get('samples', [])
        else:
            print(f"Unknown test data format in {args.test_json_path}")
            return
        
        print(f"Processing {len(samples)} test samples...")
        
        for idx, sample_info in enumerate(samples):
            print(f"\n{'='*60}")
            print(f"Processing sample {idx + 1}/{len(samples)}: {sample_info.get('video_name', f'sample_{idx}')}")
            print(f"{'='*60}")
            
            try:
                sample_info_copy = sample_info.copy()
                sample_first_frame = _resolve_path(sample_info.get('first_frame_path'), json_dir)
                sample_ref_video_path = _resolve_path(sample_info.get('ref_video_path'), json_dir)
                sample_participant_path = _resolve_path(sample_info.get('participant_path'), json_dir)

                if sample_first_frame:
                    if os.path.exists(sample_first_frame):
                        first_frame = Image.open(sample_first_frame).convert('RGB')
                        W, H = first_frame.size
                        current_sample_size = [H, W]  # PIL image.size is (W, H), sample_size should be [H, W]
                        print(f"Dynamic sample_size: {current_sample_size}")
                        
                        sample_info_copy['first_frame_path'] = sample_first_frame
                    else:
                        raise FileNotFoundError(f"first_frame_path not found: {sample_first_frame}")
                else:
                    raise ValueError("first_frame_path must be provided for I2V inference")
                
                if sample_ref_video_path is not None:
                    sample_info_copy['ref_video_path'] = sample_ref_video_path
                if sample_participant_path is not None:
                    sample_info_copy['participant_path'] = sample_participant_path
                
                sample_args = {
                    'video_length': args.video_length,
                    'seed': args.seed + idx,
                    'negative_prompt': args.negative_prompt,
                    'guidance_scale': args.guidance_scale,
                    'num_inference_steps': args.num_inference_steps,
                    'prompt': args.prompt,
                    'cli_args': args,
                }
                
                sample = process_sample(
                    pipeline=pipeline,
                    vae=vae,
                    device=device,
                    weight_dtype=weight_dtype,
                    hypernetwork=hypernetwork,
                    lilora_network=lilora_network,
                    multimodal_ref_encoder=multimodal_ref_encoder,
                    sample_info=sample_info_copy,
                    sample_size=current_sample_size,
                    args=sample_args
                )
                
                if sample is not None:
                    video_name = sample_info.get('video_name', f'sample_{idx}')
                    save_results(sample, sample_args['video_length'], video_name)
                else:
                    print(f"Skipping sample {idx + 1} due to missing first frame.")
                
            except Exception as e:
                print(f"Error processing sample {idx + 1}: {str(e)}")
                import traceback
                traceback.print_exc()
        
        print(f"\nAll {len(samples)} samples processed.")

    if args.test_json_path is not None:
        process_test_set()
    else:
        if partial_video_length is not None:
            partial_video_length = int((partial_video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
            latent_frames = (partial_video_length - 1) // vae.config.temporal_compression_ratio + 1
            if partial_video_length != 1 and transformer.config.patch_size_t is not None and latent_frames % transformer.config.patch_size_t != 0:
                additional_frames = transformer.config.patch_size_t - latent_frames % transformer.config.patch_size_t
                partial_video_length += additional_frames * vae.config.temporal_compression_ratio
                
            init_frames = 0
            last_frames = init_frames + partial_video_length
            while init_frames < video_length:
                if last_frames >= video_length:
                    _partial_video_length = video_length - init_frames
                    _partial_video_length = int((_partial_video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1
                    latent_frames = (_partial_video_length - 1) // vae.config.temporal_compression_ratio + 1
                    if _partial_video_length != 1 and transformer.config.patch_size_t is not None and latent_frames % transformer.config.patch_size_t != 0:
                        additional_frames = transformer.config.patch_size_t - latent_frames % transformer.config.patch_size_t
                        _partial_video_length += additional_frames * vae.config.temporal_compression_ratio

                    if _partial_video_length <= 0:
                        break
                else:
                    _partial_video_length = partial_video_length

                input_video, input_video_mask, clip_image = get_image_to_video_latent(validation_image, None, video_length=_partial_video_length, sample_size=sample_size)
                
                if hypernetwork is not None and ref_video_path is not None and init_frames == 0:
                    print(f"Loading reference video from {ref_video_path}...")
                    ref_frames_tensor = load_ref_video_frames(ref_video_path, sample_size)
                    _, F, _, _, _ = ref_frames_tensor.shape
                    ref_pixel_values = ref_frames_tensor.permute(0, 4, 1, 2, 3).contiguous()

                    with torch.no_grad():
                        vae_device = get_model_device(vae)
                        ref_pixel_values = ref_pixel_values.to(device=vae_device, dtype=weight_dtype)
                        ref_features = vae.encode(ref_pixel_values).latent_dist.sample()
                        ref_features = ref_features * vae.config.scaling_factor

                    updated_layers = apply_hypernetwork_weights(hypernetwork, lilora_network, ref_features)
                    print(f"Updated {updated_layers} LiLoRA layers with hypernetwork weights from {F} reference frames.")
                
                with torch.no_grad():
                    sample = pipeline(
                        args.prompt, 
                        num_frames = _partial_video_length,
                        negative_prompt = negative_prompt,
                        height      = sample_size[0],
                        width       = sample_size[1],
                        generator   = generator,
                        guidance_scale = guidance_scale,
                        num_inference_steps = num_inference_steps,

                        video        = input_video,
                        mask_video   = input_video_mask
                    ).videos
                
                if init_frames != 0:
                    mix_ratio = torch.from_numpy(
                        np.array([float(_index) / float(overlap_video_length) for _index in range(overlap_video_length)], np.float32)
                    ).unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)
                    
                    new_sample[:, :, -overlap_video_length:] = new_sample[:, :, -overlap_video_length:] * (1 - mix_ratio) + \
                        sample[:, :, :overlap_video_length] * mix_ratio
                    new_sample = torch.cat([new_sample, sample[:, :, overlap_video_length:]], dim = 2)

                    sample = new_sample
                else:
                    new_sample = sample

                if last_frames >= video_length:
                    break

                validation_image = [
                    Image.fromarray(
                        (sample[0, :, _index].transpose(0, 1).transpose(1, 2) * 255).numpy().astype(np.uint8)
                    ) for _index in range(-overlap_video_length, 0)
                ]

                init_frames = init_frames + _partial_video_length - overlap_video_length
                last_frames = init_frames + _partial_video_length
        else:
            video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
        latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
        if video_length != 1 and transformer.config.patch_size_t is not None and latent_frames % transformer.config.patch_size_t != 0:
            additional_frames = transformer.config.patch_size_t - latent_frames % transformer.config.patch_size_t
            video_length += additional_frames * vae.config.temporal_compression_ratio
        input_video, input_video_mask, clip_image = get_image_to_video_latent(validation_image_start, validation_image_end, video_length=video_length, sample_size=sample_size)

        if hypernetwork is not None and ref_video_path is not None:
            print(f"Loading reference video from {ref_video_path}...")
            ref_frames_tensor = load_ref_video_frames(ref_video_path, sample_size)
            _, F, _, _, _ = ref_frames_tensor.shape
            ref_pixel_values = ref_frames_tensor.permute(0, 4, 1, 2, 3).contiguous()

            with torch.no_grad():
                vae_device = get_model_device(vae)
                ref_pixel_values = ref_pixel_values.to(device=vae_device, dtype=weight_dtype)
                ref_features = vae.encode(ref_pixel_values).latent_dist.sample()
                ref_features = ref_features * vae.config.scaling_factor

            updated_layers = apply_hypernetwork_weights(hypernetwork, lilora_network, ref_features)
            print(f"Updated {updated_layers} LiLoRA layers with hypernetwork weights from {F} reference frames.")

        with torch.no_grad():
            sample = pipeline(
                args.prompt, 
                num_frames = video_length,
                negative_prompt = negative_prompt,
                height      = sample_size[0],
                width       = sample_size[1],
                generator   = generator,
                guidance_scale = guidance_scale,
                num_inference_steps = num_inference_steps,

                video        = input_video,
                mask_video   = input_video_mask
            ).videos

    if args.test_json_path is not None:
        process_test_set()
    else:
        if ulysses_degree * ring_degree > 1:
            import torch.distributed as dist
            if dist.get_rank() == 0:
                save_results(sample, video_length)
        else:
            save_results(sample, video_length)

if __name__ == "__main__":
    main()