forked from vita-epfl/Stable-Video-Infinity
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain_svi.py
More file actions
1445 lines (1261 loc) · 61.7 KB
/
train_svi.py
File metadata and controls
1445 lines (1261 loc) · 61.7 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
import torch
import os
import imageio
import argparse
import yaml
import torchvision
from torchvision.transforms import v2
from einops import rearrange
import lightning as pl
from diffsynth import SVIVideoPipeline, ModelManager, load_state_dict, load_state_dict_from_folder
from peft import LoraConfig, inject_adapter_in_model
from PIL import Image
import numpy as np
import random
import csv
from utils.project_utils import *
os.environ["TOKENIZERS_PARALLELISM"] = "false"
def parse_args():
parser = argparse.ArgumentParser(description="Simple example of a training script.")
parser.add_argument(
"--exp_prefix",
default='',
type=str,
)
parser.add_argument(
"--dataset_path",
type=str,
default='data/toy_train/svi-film-shot',
help="The path of the Dataset.",
)
parser.add_argument(
"--output_path",
type=str,
default="./",
help="Path to save the model.",
)
parser.add_argument(
"--text_encoder_path",
type=str,
default="/mnt/data/hnqiu/wanx2.1_t2v/WanX2.1-T2V-14B/models_t5_umt5-xxl-enc-bf16.pth",
help="Path of text encoder.",
)
parser.add_argument(
"--image_encoder_path",
type=str,
default=None,
help="Path of image encoder.",
)
parser.add_argument(
"--vae_path",
type=str,
default="/mnt/data/hnqiu/wanx2.1_t2v/WanX2.1-T2V-14B/WanX2.1_VAE.pth",
help="Path of VAE.",
)
parser.add_argument(
"--dit_path",
type=str,
default=None,
help="Path of DiT.",
)
parser.add_argument(
"--tiled",
default=False,
action="store_true",
help="Whether enable tile encode in VAE. This option can reduce VRAM required.",
)
parser.add_argument(
"--tile_size_height",
type=int,
default=34,
help="Tile size (height) in VAE.",
)
parser.add_argument(
"--tile_size_width",
type=int,
default=34,
help="Tile size (width) in VAE.",
)
parser.add_argument(
"--tile_stride_height",
type=int,
default=18,
help="Tile stride (height) in VAE.",
)
parser.add_argument(
"--tile_stride_width",
type=int,
default=16,
help="Tile stride (width) in VAE.",
)
parser.add_argument(
"--steps_per_epoch",
type=int,
default=500,
help="Number of steps per epoch.",
)
parser.add_argument(
"--num_frames",
type=int,
default=81,
help="Number of frames.",
)
parser.add_argument(
"--height",
type=int,
default=480,
help="Image height.",
)
parser.add_argument(
"--width",
type=int,
default=832,
help="Image width.",
)
parser.add_argument(
"--dataloader_num_workers",
type=int,
default=1,
help="Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process.",
)
parser.add_argument(
"--learning_rate",
type=float,
default=1e-4,
help="Learning rate.",
)
parser.add_argument(
"--accumulate_grad_batches",
type=int,
default=1,
help="The number of batches in gradient accumulation.",
)
parser.add_argument(
"--max_epochs",
type=int,
default=1,
help="Number of epochs.",
)
parser.add_argument(
"--lora_target_modules",
type=str,
default="q,k,v,o,ffn.0,ffn.2",
help="Layers with LoRA modules.",
)
parser.add_argument(
"--init_lora_weights",
type=str,
default="kaiming",
choices=["gaussian", "kaiming"],
help="The initializing method of LoRA weight.",
)
parser.add_argument(
"--training_strategy",
type=str,
default="auto",
choices=["auto", "deepspeed_stage_1", "deepspeed_stage_2", "deepspeed_stage_3"],
help="Training strategy",
)
parser.add_argument(
"--lora_rank",
type=int,
default=4,
help="The dimension of the LoRA update matrices.",
)
parser.add_argument(
"--lora_alpha",
type=float,
default=4.0,
help="The weight of the LoRA update matrices.",
)
parser.add_argument(
"--use_gradient_checkpointing",
default=False,
action="store_true",
help="Whether to use gradient checkpointing.",
)
parser.add_argument(
"--use_gradient_checkpointing_offload",
default=False,
action="store_true",
help="Whether to use gradient checkpointing offload.",
)
parser.add_argument(
"--train_architecture",
type=str,
default="lora",
choices=["lora", "full"],
help="Model structure to train. LoRA training or full training.",
)
parser.add_argument(
"--pretrained_lora_path",
type=str,
default=None,
help="Pretrained LoRA path. Required if the training is resumed.",
)
parser.add_argument(
"--use_swanlab",
default=False,
action="store_true",
help="Whether to use SwanLab logger.",
)
parser.add_argument(
"--swanlab_mode",
default=None,
help="SwanLab mode (cloud or local).",
)
parser.add_argument(
"--num_nodes",
type=int,
default=1,
help="Number of nodes to use for distributed training.",
)
parser.add_argument(
"--use_first_aug",
default=False,
action="store_true",
)
parser.add_argument(
"--use_error_recycling",
default=False,
action="store_true",
help="Whether to enable error recycling for image_emb['y'].",
)
parser.add_argument(
"--error_buffer_k",
type=int,
default=500,
help="Maximum number of error samples to store per timestep grid.",
)
parser.add_argument(
"--timestep_grid_size",
type=int,
default=25,
help="Size of timestep grid for buffer organization. Timesteps will be grouped into grids of this size.",
)
parser.add_argument(
"--num_grids",
type=int,
default=50,
help="Size of timestep grid for buffer organization. Timesteps will be grouped into grids of this size.",
)
parser.add_argument(
"--buffer_replacement_strategy",
type=str,
default="random",
choices=["random", "l2_similarity", "l2_batch", "fifo"],
help="Strategy for replacing samples when buffer is full. 'random': random replacement (fastest), 'l2_similarity': replace most similar (slowest but best quality), 'l2_batch': batch L2 computation (balanced), 'fifo': first-in-first-out.",
)
parser.add_argument(
"--buffer_warmup_iter",
type=int,
default=50,
help="Number of warmup iterations. During warmup, all GPUs will update the error buffers. After warmup, only local GPU updates the buffer.",
)
parser.add_argument(
"--error_modulate_factor",
default=0.0,
type=float,
help="Factor to modulate error intensity.",
)
parser.add_argument(
"--ref_pad_num",
type=int,
default=0, # 0 -> no padding k-> padding k , -1 -> full padding (taling, dancing, consistency)
help="Number of reference frames to pad with",
)
parser.add_argument(
"--gradient_clip_val",
type=float,
default=1.0,
help="Maximum gradient norm for clipping. Set to 0 to disable gradient clipping.",
)
parser.add_argument(
"--num_motion_frames",
type=int,
default=1,
help="Number of non-padded latents to apply augmentation on.",
)
parser.add_argument(
"--p_motion_threshold",
type=float,
default=0.9,
help="Threshold for p_motion probability to use multiple motion frames.",
)
parser.add_argument(
"--y_error_num",
type=int,
default=1,
help="Number of non-padded latents to apply augmentation on.",
)
parser.add_argument(
"--y_error_sample_from_all_grids",
default=False,
action="store_true",
help="Whether to sample y_error from all timestep grids instead of just the current grid.",
)
parser.add_argument(
"--y_error_sample_range",
type=str,
default=None,
help="Custom timestep range for y_error sampling in format 'start,end' (e.g., '0,50'). If not specified, uses default behavior.",
)
parser.add_argument(
"--error_setting",
type=int,
default=1,
help="Number of non-padded latents to apply augmentation on.",
)
parser.add_argument(
"--noise_prob",
type=float,
default=0.9,
help="Probability threshold for noise error in error settings (range 0-1).",
)
parser.add_argument(
"--y_prob",
type=float,
default=0.9,
help="Probability threshold for y error in error settings (range 0-1).",
)
parser.add_argument(
"--latent_prob",
type=float,
default=0.9,
help="Probability threshold for latent error in error settings (range 0-1).",
)
parser.add_argument(
"--clean_prob",
type=float,
default=0.1,
help="Probability threshold for latent error in error settings (range 0-1).",
)
parser.add_argument(
"--ref_pad_cfg",
default=False,
action="store_true",
help="Whether to set mask with only 1-frame 1.",
)
parser.add_argument(
"--repeat_first_frame",
default=False,
action="store_true",
help="Whether to repeat the first frame for all condition frames.",
)
parser.add_argument(
"--clean_buffer_update_prob",
type=float,
default=0.1,
help="Probability threshold for latent error in error settings (range 0-1).",
)
parser.add_argument(
"--use_last_y_error",
default=False,
action="store_true",
help="Use last frame index for y_error instead of random selection.",
)
args = parser.parse_args()
return args
class TextVideoDataset_onestage(torch.utils.data.Dataset):
def __init__(self, base_path, metadata_path, max_num_frames=81, frame_interval=1, num_frames=81, height=480, width=832, is_i2v=False, steps_per_epoch=1, args=None):
self.max_num_frames = max_num_frames
self.frame_interval = frame_interval
self.num_frames = num_frames
self.height = height
self.width = width
self.is_i2v = is_i2v
self.steps_per_epoch = steps_per_epoch
self.args = args
self.misc_size = [height, width]
self.video_list = []
self.sample_fps = frame_interval
self.max_frames = max_num_frames
print(f"Loading videos from specified path: {base_path}")
if os.path.isdir(base_path):
subdirs = [d for d in os.listdir(base_path) if os.path.isdir(os.path.join(base_path, d))]
if subdirs:
for subdir in subdirs:
subdir_path = os.path.join(base_path, subdir)
csv_file = os.path.join(subdir_path, f"{subdir}.csv")
video_descriptions = {}
if os.path.exists(csv_file):
try:
import csv
with open(csv_file, 'r', encoding='utf-8') as f:
csv_reader = csv.DictReader(f)
for row in csv_reader:
if 'Filename' in row and 'Video Description' in row:
video_descriptions[row['Filename']] = row['Video Description']
except Exception as e:
print(f"Error reading CSV file {csv_file}: {e}")
for file in os.listdir(subdir_path):
if file.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')):
video_path = os.path.join(subdir_path, file)
self.video_list.append({
'path': video_path,
'description': video_descriptions.get(file, f"A video from {subdir} category"),
'category': subdir
})
else:
for root, dirs, files in os.walk(base_path):
for file in files:
if file.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')):
self.video_list.append({'path': os.path.join(root, file), 'description': "The mountain", 'category': 'unknown'})
elif os.path.isdir(os.path.join(root, file)):
pickle_path = os.path.join(root, file, 'frame_data.pkl')
if os.path.exists(pickle_path):
self.video_list.append({'path': os.path.join(root, file), 'description': "The mountain", 'category': 'unknown'})
else:
if base_path.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')):
self.video_list.append({'path': base_path, 'description': "The video", 'category': 'single'})
random.shuffle(self.video_list)
self.frame_process = v2.Compose([
# v2.CenterCrop(size=(height, width)),
v2.Resize(size=(height, width), antialias=True),
v2.ToTensor(),
v2.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
])
def resize(self, image):
width, height = image.size
image = torchvision.transforms.functional.resize(
image,
(self.height, self.width),
interpolation=torchvision.transforms.InterpolationMode.BILINEAR
)
return image
def crop_and_resize(self, image):
width, height = image.size
scale = max(self.width / width, self.height / height)
image = torchvision.transforms.functional.resize(
image,
(round(height*scale), round(width*scale)),
interpolation=torchvision.transforms.InterpolationMode.BILINEAR
)
return image
def load_frames_using_imageio(self, file_path, max_num_frames, start_frame_id, interval, num_frames, frame_process):
reader = imageio.get_reader(file_path)
if reader.count_frames() < max_num_frames or reader.count_frames() - 1 < start_frame_id + (num_frames - 1) * interval:
reader.close()
return None
frames = []
first_ref_frame = None
for frame_id in range(num_frames):
frame = reader.get_data(start_frame_id + frame_id * interval)
frame = Image.fromarray(frame)
frame = self.crop_and_resize(frame)
if first_ref_frame is None:
first_ref_frame = np.array(frame)
frame = frame_process(frame)
frames.append(frame)
reader.close()
frames = torch.stack(frames, dim=0)
frames = rearrange(frames, "T C H W -> C T H W")
return frames, first_ref_frame
def load_video(self, file_path):
start_frame_id = torch.randint(0, self.max_num_frames - (self.num_frames - 1) * self.frame_interval, (1,))[0]
frames = self.load_frames_using_imageio(file_path, self.max_num_frames, start_frame_id, self.frame_interval, self.num_frames, self.frame_process)
return frames
def is_image(self, file_path):
file_ext_name = file_path.split(".")[-1]
if file_ext_name.lower() in ["jpg", "jpeg", "png", "webp"]:
return True
return False
def load_image(self, file_path):
frame = Image.open(file_path).convert("RGB")
frame = self.crop_and_resize(frame)
frame = self.frame_process(frame)
frame = rearrange(frame, "C H W -> C 1 H W")
return frame
def __getitem__(self, index):
index = index % len(self.video_list)
video_item = self.video_list[index]
if isinstance(video_item, dict):
video_path = video_item['path']
video_description = video_item['description']
video_category = video_item['category']
if os.path.isdir(video_path):
mp4_files = [f for f in os.listdir(video_path) if f.endswith('.mp4')]
if mp4_files:
video_file = os.path.join(video_path, mp4_files[0])
else:
video_files = [f for f in os.listdir(video_path) if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
if video_files:
video_file = os.path.join(video_path, video_files[0])
else:
raise FileNotFoundError(f"No video files found in {video_path}")
else:
video_file = video_path
try:
reader = imageio.get_reader(video_file)
total_frames = reader.count_frames()
except (OSError, IOError) as e:
print(f"WARNING: Failed to read video file {video_file} due to {e}. Skipping and loading another random video.")
return self.__getitem__(random.randint(0, len(self.video_list) - 1))
stride = random.randint(1, self.sample_fps)
cover_frame_num = (stride * self.max_frames)
max_frames = self.max_frames
if total_frames < cover_frame_num + 1:
start_frame = 0
end_frame = total_frames - 1
stride = max((total_frames // max_frames), 1)
end_frame = min(stride * max_frames, total_frames - 1)
else:
max_start_frame = max(0, total_frames - cover_frame_num - 5)
start_frame = random.randint(0, max_start_frame) if max_start_frame > 0 else 0
end_frame = start_frame + cover_frame_num
frame_list = []
frame_indices = []
for i_index in range(start_frame, min(end_frame, total_frames), stride):
frame_indices.append(i_index)
while len(frame_indices) < max_frames:
frame_indices.append(frame_indices[-1] if frame_indices else 0)
frame_indices = frame_indices[:max_frames]
for i, frame_idx in enumerate(frame_indices):
frame = reader.get_data(frame_idx)
frame = Image.fromarray(frame).convert('RGB')
frame_list.append(frame)
num_ref_frames = 12 # prepared for motion frames
ref_frame_indices = list(range(num_ref_frames))
first_ref_frames = [frame_list[idx].copy() for idx in ref_frame_indices]
random_frame_idx = random.randint(0, len(frame_indices) - 1)
random_ref_frame = frame_list[random_frame_idx].copy()
reader.close()
have_frames = len(frame_list) > 0
if have_frames:
# Simple cropping without face detection
l_height = first_ref_frames[0].size[1]
l_width = first_ref_frames[0].size[0]
# Calculate target aspect ratio (480:832 = 15:26 ≈ 0.577)
target_aspect_ratio = self.misc_size[0] / self.misc_size[1] # height / width
# Calculate crop dimensions to maintain aspect ratio
if l_width * target_aspect_ratio <= l_height:
# Width is the limiting factor, crop height
crop_width = random.randint(l_width - l_width//14, l_width)
crop_height = int(crop_width * target_aspect_ratio)
else:
# Height is the limiting factor, crop width
crop_height = random.randint(l_height - l_height//14, l_height)
crop_width = int(crop_height / target_aspect_ratio)
# Ensure crop dimensions don't exceed original dimensions
crop_width = min(crop_width, l_width)
crop_height = min(crop_height, l_height)
# Calculate random crop position
max_x_offset = l_width - crop_width
max_y_offset = l_height - crop_height
x1 = random.randint(0, max_x_offset) if max_x_offset > 0 else 0
y1 = random.randint(0, max_y_offset) if max_y_offset > 0 else 0
x2 = x1 + crop_width
y2 = y1 + crop_height
first_ref_frames = [frame.crop((x1, y1, x2, y2)) for frame in first_ref_frames]
random_ref_frame = random_ref_frame.crop((x1, y1, x2, y2))
first_ref_frames_tmp = [torch.from_numpy(np.array(self.resize(frame))) for frame in first_ref_frames]
random_ref_frame_tmp = torch.from_numpy(np.array(self.resize(random_ref_frame)))
video_data_tmp = torch.stack([self.frame_process(self.resize(ss.crop((x1, y1, x2, y2)))) for ss in frame_list], dim=0)
video_data = torch.zeros(self.max_frames, 3, self.misc_size[0], self.misc_size[1])
if have_frames:
video_data[:len(frame_list), ...] = video_data_tmp
video_data = video_data.permute(1, 0, 2, 3)
if isinstance(video_item, dict) and 'description' in video_item:
caption = video_description
text = caption
path = video_path
video, first_ref_frames, random_ref_frame = video_data, first_ref_frames_tmp, random_ref_frame_tmp
data = {"text": text, "video": video, "path": path, "first_ref_frames": first_ref_frames, "random_ref_frame": random_ref_frame}
return data
def __len__(self):
return len(self.video_list)
class LightningModelForTrain_onestage(pl.LightningModule):
def __init__(
self,
dit_path,
learning_rate=1e-5,
lora_rank=4, lora_alpha=4, train_architecture="lora", lora_target_modules="q,k,v,o,ffn.0,ffn.2", init_lora_weights="kaiming",
use_gradient_checkpointing=True, use_gradient_checkpointing_offload=False,
pretrained_lora_path=None,
model_VAE=None,
args=None,
):
super().__init__()
model_manager = ModelManager(torch_dtype=torch.bfloat16, device="cpu", train_architecture=args.train_architecture)
self.use_first_aug = args.use_first_aug
self.use_error_recycling = args.use_error_recycling if args else False
if os.path.isfile(dit_path):
model_manager.load_models([dit_path])
else:
dit_path = dit_path.split(",")
model_manager.load_models([dit_path])
self.pipe = SVIVideoPipeline.from_model_manager(model_manager, is_test=False)
self.pipe.scheduler.set_timesteps(1000, training=True)
self.pipe_VAE = model_VAE.pipe.eval()
self.tiler_kwargs = model_VAE.tiler_kwargs
self.ref_pad_num = args.ref_pad_num
self.y_error_num = args.y_error_num
self.freeze_parameters()
if train_architecture == "lora":
self.add_lora_to_model(
self.pipe.denoising_model(),
lora_rank=lora_rank,
lora_alpha=lora_alpha,
lora_target_modules=lora_target_modules,
init_lora_weights=init_lora_weights,
pretrained_lora_path=pretrained_lora_path,
)
elif train_architecture == "full":
self.pipe.denoising_model().requires_grad_(True)
elif train_architecture == "customtalk":
for name, param in self.pipe.denoising_model().named_parameters():
if 'customtalk' in name.lower():
param.requires_grad_(True)
print(f"Trainable parameter: {name}")
else:
param.requires_grad_(False)
self.learning_rate = learning_rate
self.use_gradient_checkpointing = use_gradient_checkpointing
self.use_gradient_checkpointing_offload = use_gradient_checkpointing_offload
# Gradient clipping and monitoring settings
self.gradient_clip_val = getattr(args, 'gradient_clip_val', 1.0)
# Initialize noise buffer for storing individual noise samples with timestep grid
self.error_buffer_size = getattr(args, 'error_buffer_k', 500) # Size per timestep grid
self.buffer_replacement_strategy = getattr(args, 'buffer_replacement_strategy', 'random')
self.buffer_warmup_iter = getattr(args, 'buffer_warmup_iter', 50)
self.timestep_grid_size = getattr(args, 'timestep_grid_size', 25) # Default grid size of 25
num_grids = getattr(args, 'num_grids', 40)
self.inferece_timesteps = self.pipe.scheduler.get_timesteps(num_inference_steps=num_grids, denoising_strength=1, shift=5.0)
self.latent_error_buffer = {i: [] for i in range(num_grids)}
self.y_error_buffer = {i: [] for i in range(num_grids)}
self.iteration_count = 0
self.error_modulate_factor = args.error_modulate_factor
self.num_motion_frames = args.num_motion_frames
self.p_motion_threshold = getattr(args, 'p_motion_threshold', 0.5)
self.y_error_sample_from_all_grids = getattr(args, 'y_error_sample_from_all_grids', False)
self.error_setting = getattr(args, 'error_setting', 1)
self.noise_prob = getattr(args, 'noise_prob', 0.99)
self.y_prob = getattr(args, 'y_prob', 0.99)
self.latent_prob = getattr(args, 'latent_prob', 0.99)
self.ref_pad_cfg = getattr(args, 'ref_pad_cfg', False)
self.clean_prob = getattr(args, 'clean_prob', 0.1)
self.clean_buffer_update_prob = getattr(args, 'clean_buffer_update_prob', 0.5)
self.repeat_first_frame = getattr(args, 'repeat_first_frame', False)
self.use_last_y_error = getattr(args, 'use_last_y_error', False)
# Parse y_error_sample_range
self.y_error_sample_range = None
if hasattr(args, 'y_error_sample_range') and args.y_error_sample_range:
try:
range_parts = args.y_error_sample_range.split(',')
if len(range_parts) == 2:
start_ts, end_ts = int(range_parts[0]), int(range_parts[1])
# Convert timesteps to grid indices
start_grid = start_ts // self.timestep_grid_size
end_grid = end_ts // self.timestep_grid_size
self.y_error_sample_range = (start_grid, end_grid)
print(f"Y-error sampling range set to timesteps {start_ts}-{end_ts} (grids {start_grid}-{end_grid})")
else:
print("Warning: Invalid y_error_sample_range format. Expected 'start,end'")
except ValueError:
print("Warning: Invalid y_error_sample_range values. Expected integers.")
def _get_timestep_grid(self, timestep):
"""Get the grid index for a given timestep."""
# Handle different timestep formats (scalar tensor, tensor with batch dim, etc.)
if isinstance(timestep, torch.Tensor):
if timestep.numel() == 1:
# Single timestep value
timestep_val = timestep.item()
else:
# Tensor with batch dimension, take the first element
timestep_val = timestep.flatten()[0].item()
else:
# Already a scalar value
timestep_val = timestep
# Ensure timestep is within valid range and calculate grid index
timestep_val = max(0, min(timestep_val, 999)) # Clamp to [0, 999]
# grid_idx = int(timestep_val // self.timestep_grid_size)
grid_idx = torch.argmin((self.inferece_timesteps - timestep_val).abs()).item()
# Ensure grid index is within valid range
max_grid_idx = len(self.latent_error_buffer) - 1
grid_idx = min(grid_idx, max_grid_idx)
return grid_idx
def _compute_l2_distance_batch(self, new_tensor, stored_tensors):
"""Compute L2 distances between new tensor and all stored tensors efficiently."""
if not stored_tensors:
return torch.tensor([])
# Stack all stored tensors for batch computation
stored_stack = torch.stack(stored_tensors) # [num_stored, ...]
new_flat = new_tensor.flatten()
stored_flat = stored_stack.flatten(start_dim=1) # [num_stored, flattened_size]
# Compute L2 distances in batch
distances = torch.norm(stored_flat - new_flat.unsqueeze(0), p=2, dim=1)
return distances
def _compute_l2_distance(self, tensor1, tensor2):
"""Compute L2 distance between two tensors"""
# Flatten tensors
flat1 = tensor1.flatten()
flat2 = tensor2.flatten()
# Compute L2 distance (Euclidean distance)
l2_distance = torch.norm(flat1 - flat2, p=2)
return l2_distance.item()
def _add_error_to_latent_buffer(self, error_sample, timestep):
"""Add error sample to buffer using specified replacement strategy based on timestep grid."""
grid_idx = self._get_timestep_grid(timestep)
error_cpu = error_sample.detach().cpu()
if len(self.latent_error_buffer[grid_idx]) < self.error_buffer_size:
# Buffer not full, simply add
self.latent_error_buffer[grid_idx].append(error_cpu)
else:
# Buffer full, use specified replacement strategy
if self.buffer_replacement_strategy == "random":
# Random replacement - O(1), fastest
replace_idx = random.randint(0, len(self.latent_error_buffer[grid_idx]) - 1)
self.latent_error_buffer[grid_idx][replace_idx] = error_cpu
elif self.buffer_replacement_strategy == "fifo":
# First-in-first-out - O(1), simple queue behavior
self.latent_error_buffer[grid_idx].pop(0)
self.latent_error_buffer[grid_idx].append(error_cpu)
elif self.buffer_replacement_strategy == "l2_batch":
# Batch L2 computation - O(n) but vectorized, much faster than original
distances = self._compute_l2_distance_batch(error_cpu, self.latent_error_buffer[grid_idx])
most_similar_idx = torch.argmin(distances).item()
self.latent_error_buffer[grid_idx][most_similar_idx] = error_cpu
elif self.buffer_replacement_strategy == "l2_similarity":
# Original L2 similarity method - O(n), slowest but most precise
min_distance = float('inf')
most_similar_idx = -1
for i, stored_error in enumerate(self.latent_error_buffer[grid_idx]):
distance = self._compute_l2_distance(error_cpu, stored_error)
if distance < min_distance:
min_distance = distance
most_similar_idx = i
if most_similar_idx != -1:
self.latent_error_buffer[grid_idx][most_similar_idx] = error_cpu
def _add_error_to_y_buffer(self, error_sample, timestep):
"""Add error sample to buffer using specified replacement strategy based on timestep grid."""
grid_idx = self._get_timestep_grid(timestep)
error_cpu = error_sample.detach().cpu()
if len(self.y_error_buffer[grid_idx]) < self.error_buffer_size:
# Buffer not full, simply add
self.y_error_buffer[grid_idx].append(error_cpu)
else:
# Buffer full, use specified replacement strategy
if self.buffer_replacement_strategy == "random":
# Random replacement - O(1), fastest
replace_idx = random.randint(0, len(self.y_error_buffer[grid_idx]) - 1)
self.y_error_buffer[grid_idx][replace_idx] = error_cpu
elif self.buffer_replacement_strategy == "fifo":
# First-in-first-out - O(1), simple queue behavior
self.y_error_buffer[grid_idx].pop(0)
self.y_error_buffer[grid_idx].append(error_cpu)
elif self.buffer_replacement_strategy == "l2_batch":
# Batch L2 computation - O(n) but vectorized, much faster than original
distances = self._compute_l2_distance_batch(error_cpu, self.y_error_buffer[grid_idx])
most_similar_idx = torch.argmin(distances).item()
self.y_error_buffer[grid_idx][most_similar_idx] = error_cpu
elif self.buffer_replacement_strategy == "l2_similarity":
# Original L2 similarity method - O(n), slowest but most precise
min_distance = float('inf')
most_similar_idx = -1
for i, stored_error in enumerate(self.y_error_buffer[grid_idx]):
distance = self._compute_l2_distance(error_cpu, stored_error)
if distance < min_distance:
min_distance = distance
most_similar_idx = i
if most_similar_idx != -1:
self.y_error_buffer[grid_idx][most_similar_idx] = error_cpu
def _sample_noise_error_from_noise_buffer(self, latents, timestep):
"""Randomly sample an error from the buffer based on timestep grid."""
grid_idx = self._get_timestep_grid(timestep)
if not self.latent_error_buffer[grid_idx]:
return torch.zeros_like(latents)
# Randomly select one sample from the corresponding grid
selected_sample = random.choice(self.latent_error_buffer[grid_idx])
error_sample = selected_sample.to(self.device)
min_mod = 1.0 - self.error_modulate_factor
max_mod = 1.0 + self.error_modulate_factor
intensity_mod = random.uniform(min_mod, max_mod)
error_sample = error_sample * intensity_mod
return error_sample
def _sample_latent_error_from_latent_buffer(self, latents, timestep):
"""Randomly sample an error from the buffer based on timestep grid."""
grid_idx = self._get_timestep_grid(timestep)
if not self.y_error_buffer[grid_idx]:
return torch.zeros_like(latents)
# Randomly select one sample from the corresponding grid
selected_sample = random.choice(self.y_error_buffer[grid_idx])
error_sample = selected_sample.to(self.device)
min_mod = 1.0 - self.error_modulate_factor
max_mod = 1.0 + self.error_modulate_factor
intensity_mod = random.uniform(min_mod, max_mod)
error_sample = error_sample * intensity_mod
return error_sample
def _sample_y_error_from_latent_buffer(self, latents, timestep):
"""Specially sample y_error from buffer - can be configured to sample from all grids or custom range."""
if self.y_error_sample_range is not None:
# Sample from custom timestep range
start_grid, end_grid = self.y_error_sample_range
all_samples = []
for grid_idx in range(start_grid, min(end_grid + 1, len(self.y_error_buffer))):
buffer = self.y_error_buffer[grid_idx]
if buffer: # Only add non-empty buffers
all_samples.extend(buffer)
if not all_samples:
return torch.zeros_like(latents)
# Randomly select one sample from the custom range
selected_sample = random.choice(all_samples)
elif self.y_error_sample_from_all_grids:
# Sample from all grids that have data
all_samples = []
for grid_idx, buffer in self.y_error_buffer.items():
if buffer: # Only add non-empty buffers
all_samples.extend(buffer)
if not all_samples:
return torch.zeros_like(latents)
# Randomly select one sample from all available samples
selected_sample = random.choice(all_samples)
else:
# Sample from current timestep grid only (original behavior)
grid_idx = self._get_timestep_grid(timestep)
if not self.y_error_buffer[grid_idx]:
return torch.zeros_like(latents)
# Randomly select one sample from the corresponding grid
selected_sample = random.choice(self.y_error_buffer[grid_idx])
error_sample = selected_sample.to(self.device)
min_mod = 1.0 - self.error_modulate_factor
max_mod = 1.0 + self.error_modulate_factor
intensity_mod = random.uniform(min_mod, max_mod)
error_sample = error_sample * intensity_mod
return error_sample
def freeze_parameters(self):
# Freeze parameters
self.pipe.requires_grad_(False)
self.pipe.eval()
self.pipe.denoising_model().train()
self.pipe_VAE.requires_grad_(False)
self.pipe_VAE.eval()
def add_lora_to_model(self, model, lora_rank=4, lora_alpha=4, lora_target_modules="q,k,v,o,ffn.0,ffn.2", init_lora_weights="kaiming", pretrained_lora_path=None, state_dict_converter=None):
self.lora_alpha = lora_alpha
if init_lora_weights == "kaiming":
init_lora_weights = True
lora_config = LoraConfig(
r=lora_rank,
lora_alpha=lora_alpha,
init_lora_weights=init_lora_weights,
target_modules=lora_target_modules.split(","),
)
model = inject_adapter_in_model(lora_config, model)
for param in model.parameters():
# Upcast LoRA parameters into fp32
if param.requires_grad:
param.data = param.to(torch.float32)
# Lora pretrained lora weights
if pretrained_lora_path is not None:
try:
state_dict = load_state_dict(pretrained_lora_path)
except:
state_dict = load_state_dict_from_folder(pretrained_lora_path)
state_dict_new = {}
for key in state_dict.keys():
if 'pipe.dit.' in key:
key_new = key.split("pipe.dit.")[1]
state_dict_new[key_new] = state_dict[key]
if state_dict_converter is not None:
state_dict = state_dict_converter(state_dict)
missing_keys, unexpected_keys = model.load_state_dict(state_dict_new, strict=False)
all_keys = [i for i, _ in model.named_parameters()]
num_updated_keys = len(all_keys) - len(missing_keys)
num_unexpected_keys = len(unexpected_keys)
print(f"{num_updated_keys} parameters are loaded from {pretrained_lora_path}. {num_unexpected_keys} parameters are unexpected.")
def training_step(self, batch, batch_idx):
text, video, path = batch["text"][0], batch["video"], batch["path"][0]
self.pipe_VAE.device = self.device
with torch.no_grad():
if video is not None:
# prompt
prompt_emb = self.pipe_VAE.encode_prompt(text)
# video - use float32 for VAE encoding then convert to bf16
original_dtype = self.pipe_VAE.torch_dtype
# Temporarily convert VAE to float32
self.pipe_VAE.vae.to(torch.float32)
video = video.to(dtype=torch.float32, device=self.pipe_VAE.device)