-
Notifications
You must be signed in to change notification settings - Fork 25
/
train.py
1349 lines (1166 loc) · 67.7 KB
/
train.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2024 ConsisID Authors and The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import math
import os
import pickle
import random
import shutil
import threading
from datetime import timedelta
from pathlib import Path
import accelerate
import insightface
import numpy as np
import torch
import transformers
from accelerate import Accelerator
from accelerate.logging import get_logger
from accelerate.utils import (
DistributedDataParallelKwargs,
DistributedType,
InitProcessGroupKwargs,
ProjectConfiguration,
set_seed,
)
from consisid_eva_clip import create_model_and_transforms
from consisid_eva_clip.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
from facexlib.parsing import init_parsing_model
from facexlib.utils.face_restoration_helper import FaceRestoreHelper
from insightface.app import FaceAnalysis
from models.consisid_utils import (
compute_prompt_embeddings,
prepare_rotary_positional_embeddings,
process_face_embeddings,
resize_numpy_image_long,
tensor_to_pil,
)
from models.pipeline_cogvideox import CogVideoXPipeline
from models.pipeline_consisid import ConsisIDPipeline, draw_kps
from models.transformer_consisid import ConsisIDTransformer3DModel
from peft import LoraConfig, get_peft_model_state_dict, set_peft_model_state_dict
from PIL import Image, ImageOps
from torch.utils.data import DataLoader
from tqdm import tqdm
from transformers import AutoTokenizer, T5EncoderModel
from transformers.utils import ContextManagers
from util.dataloader import ConsisID_Dataset, RandomSampler, SequentialSampler
from util.utils import get_args, pixel_values_to_pil, resize_mask
import diffusers
from diffusers import AutoencoderKLCogVideoX, CogVideoXDPMScheduler
from diffusers.optimization import get_scheduler
from diffusers.training_utils import EMAModel, cast_training_params, free_memory
from diffusers.utils import convert_unet_state_dict_to_peft, deprecate, export_to_video, is_wandb_available, load_image
from diffusers.utils.torch_utils import is_compiled_module
from diffusers.video_processor import VideoProcessor
lock = threading.Lock()
if is_wandb_available():
import wandb
logger = get_logger(__name__)
def log_validation(
pipe,
args,
accelerator,
pipeline_args,
global_step,
is_final_validation: bool = False,
id_vit_hidden=None,
id_cond=None,
kps_cond=None,
):
"""
Run the validation process for generating videos using the provided pipeline.
This function performs a validation step by generating a specified number of videos using
a given prompt and pipeline configuration. The generated videos are then logged to
appropriate trackers (e.g., Weights and Biases).
Args:
pipe: The video generation pipeline object used to generate the videos.
args: Arguments object containing various parameters such as the number of validation videos,
output directory, and seed for reproducibility.
accelerator: The accelerator object used to manage device placement and distributed training utilities.
pipeline_args: Dictionary containing arguments for the video generation pipeline, including the prompt.
is_final_validation (bool, optional): Flag indicating if this is the final validation step. Defaults to False.
id_vit_hidden (optional): Hidden state input for identity preservation during video generation. Defaults to None.
id_cond (optional): Condition input for identity preservation. Defaults to None.
Returns:
list: A list of generated video frames.
"""
# Log the start of the validation process with the given prompt and number of videos
logger.info(
f"Running validation... \n Generating {args.num_validation_videos} videos with prompt: {pipeline_args['prompt']}."
)
# Set up scheduler arguments based on scheduler configuration
scheduler_args = {}
if "variance_type" in pipe.scheduler.config:
variance_type = pipe.scheduler.config.variance_type
# Adjust variance_type if necessary to ensure compatibility with the scheduler
if variance_type in ["learned", "learned_range"]:
variance_type = "fixed_small"
scheduler_args["variance_type"] = variance_type
# Update the pipeline scheduler with the modified configuration
pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config, **scheduler_args)
pipe = pipe.to(accelerator.device)
# Initialize the random generator with a specified seed, if provided
generator = torch.Generator(device=accelerator.device).manual_seed(args.seed) if args.seed else None
# Perform video generation without tracking gradients (inference mode)
videos = []
with torch.no_grad():
for _ in range(args.num_validation_videos):
# Generate video frames using the pipeline and provided conditions
video = pipe(**pipeline_args, generator=generator, output_type="np",
id_vit_hidden=id_vit_hidden,
id_cond=id_cond,
kps_cond=kps_cond,
).frames[0]
videos.append(video)
# Log generated videos to the appropriate tracker(s)
for tracker in accelerator.trackers:
phase_name = "test" if is_final_validation else "validation"
if tracker.name == "wandb":
video_filenames = []
for i, video in enumerate(videos):
# Create a unique filename for each video generated during validation
prompt = (
pipeline_args["prompt"][:25]
.replace(" ", "_")
.replace("'", "_")
.replace('"', "_")
.replace("/", "_")
)
filename = os.path.join(args.output_dir, f"{global_step}_video_{i}_{prompt}.mp4")
# Export the video as an MP4 file
export_to_video(video, filename, fps=8)
video_filenames.append(filename)
# Log the generated videos to Weights and Biases (wandb) tracker
tracker.log(
{
phase_name: [
wandb.Video(filename, caption=f"{i}: {pipeline_args['prompt']}")
for i, filename in enumerate(video_filenames)
]
}
)
# Clean up the pipeline to free memory
del pipe
free_memory()
# Return the list of generated videos
return videos
def get_optimizer(args, params_to_optimize, use_deepspeed: bool = False):
"""
Create and return an optimizer based on the specified arguments.
Parameters:
args : object
An object containing various hyperparameters such as optimizer type, learning rate, betas, etc.
params_to_optimize : iterable
Parameters to be optimized by the optimizer.
use_deepspeed : bool, optional (default=False)
Flag to indicate whether to use the DeepSpeed optimizer.
Returns:
optimizer : Optimizer
The optimizer instance based on the provided configuration.
"""
# Use DeepSpeed optimizer if specified by the use_deepspeed flag
if use_deepspeed:
from accelerate.utils import DummyOptim
return DummyOptim(
params_to_optimize,
lr=args.learning_rate,
betas=(args.adam_beta1, args.adam_beta2),
eps=args.adam_epsilon,
weight_decay=args.adam_weight_decay,
)
# Define the list of supported optimizers
supported_optimizers = ["adam", "adamw", "prodigy"]
# Warn and default to AdamW if the provided optimizer is not supported
if args.optimizer not in supported_optimizers:
logger.warning(
f"Unsupported choice of optimizer: {args.optimizer}. Supported optimizers include {supported_optimizers}. Defaulting to AdamW"
)
args.optimizer = "adamw"
# Check if 8-bit Adam is being used with an unsupported optimizer
if args.use_8bit_adam and args.optimizer.lower() not in ["adam", "adamw"]:
logger.warning(
f"use_8bit_adam is ignored when optimizer is not set to 'Adam' or 'AdamW'. Optimizer was "
f"set to {args.optimizer.lower()}"
)
# Attempt to import bitsandbytes if 8-bit Adam is specified
if args.use_8bit_adam:
try:
import bitsandbytes as bnb
except ImportError:
raise ImportError(
"To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
)
# Create optimizer instance based on the specified type
if args.optimizer.lower() == "adamw":
# Use AdamW from bitsandbytes if using 8-bit precision, otherwise use PyTorch's AdamW
optimizer_class = bnb.optim.AdamW8bit if args.use_8bit_adam else torch.optim.AdamW
optimizer = optimizer_class(
params_to_optimize,
betas=(args.adam_beta1, args.adam_beta2),
eps=args.adam_epsilon,
weight_decay=args.adam_weight_decay,
)
elif args.optimizer.lower() == "adam":
# Use Adam from bitsandbytes if using 8-bit precision, otherwise use PyTorch's Adam
optimizer_class = bnb.optim.Adam8bit if args.use_8bit_adam else torch.optim.Adam
optimizer = optimizer_class(
params_to_optimize,
betas=(args.adam_beta1, args.adam_beta2),
eps=args.adam_epsilon,
weight_decay=args.adam_weight_decay,
)
elif args.optimizer.lower() == "prodigy":
# Attempt to import the Prodigy optimizer library
try:
import prodigyopt
except ImportError:
raise ImportError("To use Prodigy, please install the prodigyopt library: `pip install prodigyopt`")
optimizer_class = prodigyopt.Prodigy
# Warn if learning rate is lower than recommended for Prodigy
if args.learning_rate <= 0.1:
logger.warning(
"Learning rate is too low. When using Prodigy, it's generally better to set learning rate around 1.0"
)
# Create an instance of the Prodigy optimizer with additional specific arguments
optimizer = optimizer_class(
params_to_optimize,
lr=args.learning_rate,
betas=(args.adam_beta1, args.adam_beta2),
beta3=args.prodigy_beta3,
weight_decay=args.adam_weight_decay,
eps=args.adam_epsilon,
decouple=args.prodigy_decouple,
use_bias_correction=args.prodigy_use_bias_correction,
safeguard_warmup=args.prodigy_safeguard_warmup,
)
# Return the created optimizer
return optimizer
def main(args):
if args.report_to == "wandb" and args.hub_token is not None:
raise ValueError(
"You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
" Please use `huggingface-cli login` to authenticate with the Hub."
)
if args.non_ema_revision is not None:
deprecate(
"non_ema_revision!=None",
"0.15.0",
message=(
"Downloading 'non_ema' weights from revision branches of the Hub is deprecated. Please make sure to"
" use `--variant=non_ema` instead."
),
)
if torch.backends.mps.is_available() and args.mixed_precision == "bf16":
# due to pytorch#99272, MPS does not yet support bfloat16.
raise ValueError(
"Mixed precision training with bfloat16 is not supported on MPS. Please use fp16 (recommended) or fp32 instead."
)
logging_dir = Path(args.output_dir, args.logging_dir)
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
ddp_kwargs = DistributedDataParallelKwargs(find_unused_parameters=True)
init_kwargs = InitProcessGroupKwargs(backend="nccl", timeout=timedelta(seconds=args.nccl_timeout))
accelerator = Accelerator(
gradient_accumulation_steps=args.gradient_accumulation_steps,
mixed_precision=args.mixed_precision,
log_with=args.report_to,
project_config=accelerator_project_config,
kwargs_handlers=[ddp_kwargs, init_kwargs],
)
# Disable AMP for MPS.
if torch.backends.mps.is_available():
accelerator.native_amp = False
if args.report_to == "wandb":
if not is_wandb_available():
raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO,
)
logger.info(accelerator.state, main_process_only=False)
if accelerator.is_local_main_process:
transformers.utils.logging.set_verbosity_warning()
diffusers.utils.logging.set_verbosity_info()
else:
transformers.utils.logging.set_verbosity_error()
diffusers.utils.logging.set_verbosity_error()
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
# Handle the repository creation
if accelerator.is_main_process:
if args.output_dir is not None:
os.makedirs(args.output_dir, exist_ok=True)
# Prepare models and scheduler
load_dtype = torch.bfloat16 if "5b" in args.pretrained_model_name_or_path.lower() else torch.float16
transformer_additional_kwargs={
'torch_dtype': load_dtype,
'revision': args.revision,
'variant': args.variant,
'is_train_face': args.is_train_face,
'is_kps': args.is_kps,
'LFE_num_tokens': args.LFE_num_tokens,
'LFE_output_dim': args.LFE_output_dim,
'LFE_heads': args.LFE_heads,
'cross_attn_interval': args.cross_attn_interval,
}
transformer = ConsisIDTransformer3DModel.from_pretrained_cus(
args.pretrained_model_name_or_path if args.pretrained_weight is None else args.pretrained_weight,
subfolder="transformer",
config_path=args.config_path,
transformer_additional_kwargs=transformer_additional_kwargs,
)
def deepspeed_zero_init_disabled_context_manager():
"""
returns either a context list that includes one that will disable zero.Init or an empty context list
"""
deepspeed_plugin = accelerator.state.deepspeed_plugin if accelerate.state.is_initialized() else None
if deepspeed_plugin is None:
return []
return [deepspeed_plugin.zero3_init_context_manager(enable=False)]
scheduler = CogVideoXDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
tokenizer = AutoTokenizer.from_pretrained(
args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision
)
with ContextManagers(deepspeed_zero_init_disabled_context_manager()):
text_encoder = T5EncoderModel.from_pretrained(
args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
)
vae = AutoencoderKLCogVideoX.from_pretrained(
args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision, variant=args.variant
)
if args.enable_slicing:
vae.enable_slicing()
if args.enable_tiling:
vae.enable_tiling()
# detect face in the videos
face_clip_model = None
face_main_model = None
face_helper_1 = None
face_helper_2 = None
if args.is_train_face:
face_helper_1 = FaceRestoreHelper(
upscale_factor=1,
face_size=512,
crop_ratio=(1, 1),
det_model='retinaface_resnet50',
save_ext='png',
device=accelerator.device,
model_rootpath=os.path.join(args.pretrained_model_name_or_path, "face_encoder")
)
face_helper_1.face_parse = None
face_helper_1.face_parse = init_parsing_model(model_name='bisenet', device=accelerator.device, model_rootpath=os.path.join(args.pretrained_model_name_or_path, "face_encoder"))
face_helper_1.face_det.eval()
face_helper_1.face_parse.eval()
model, _, _ = create_model_and_transforms('EVA02-CLIP-L-14-336', os.path.join(args.pretrained_model_name_or_path, "face_encoder", "EVA02_CLIP_L_336_psz14_s6B.pt"), force_custom_clip=True)
face_clip_model = model.visual
face_clip_model.eval()
eva_transform_mean = getattr(face_clip_model, 'image_mean', OPENAI_DATASET_MEAN)
eva_transform_std = getattr(face_clip_model, 'image_std', OPENAI_DATASET_STD)
if not isinstance(eva_transform_mean, (list, tuple)):
eva_transform_mean = (eva_transform_mean,) * 3
if not isinstance(eva_transform_std, (list, tuple)):
eva_transform_std = (eva_transform_std,) * 3
eva_transform_mean = eva_transform_mean
eva_transform_std = eva_transform_std
device_id = accelerator.process_index % torch.cuda.device_count()
face_main_model = FaceAnalysis(name='antelopev2', root=os.path.join(args.pretrained_model_name_or_path, "face_encoder"), providers=['CUDAExecutionProvider'], provider_options=[{"device_id": device_id}])
face_helper_2 = insightface.model_zoo.get_model(f'{args.pretrained_model_name_or_path}/face_encoder/models/antelopev2/glintr100.onnx', providers=['CUDAExecutionProvider'], provider_options=[{"device_id": device_id}])
# Freeze all the components
text_encoder.requires_grad_(False)
transformer.requires_grad_(False)
vae.requires_grad_(False)
if args.is_train_face:
face_clip_model.requires_grad_(False)
face_helper_1.face_det.requires_grad_(False)
face_helper_1.face_parse.requires_grad_(False)
weight_dtype = torch.bfloat16
if torch.backends.mps.is_available() and weight_dtype == torch.bfloat16:
# due to pytorch#99272, MPS does not yet support bfloat16.
raise ValueError(
"Mixed precision training with bfloat16 is not supported on MPS. Please use fp16 (recommended) or fp32 instead."
)
# Move everything to device
transformer.to(accelerator.device, dtype=weight_dtype)
text_encoder.to(accelerator.device, dtype=weight_dtype)
vae.to(accelerator.device, dtype=weight_dtype)
if args.is_train_face:
face_clip_model.to(accelerator.device, dtype=weight_dtype)
face_helper_1.face_det.to(accelerator.device)
face_helper_1.face_parse.to(accelerator.device)
face_main_model.prepare(ctx_id=device_id if device_id is not None else 0, det_size=(640, 640))
face_helper_2.prepare(ctx_id=device_id if device_id is not None else 0)
free_memory()
# enable gradient checkpointing
if args.gradient_checkpointing:
transformer.enable_gradient_checkpointing()
# Enable TF32 for faster training on Ampere GPUs,
# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
if args.allow_tf32 and torch.cuda.is_available():
torch.backends.cuda.matmul.allow_tf32 = True
if args.scale_lr:
args.learning_rate = (
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
)
# Make sure the trainable params are in float32.
if args.mixed_precision == "fp16":
# only upcast trainable parameters (LoRA) into fp32
cast_training_params([transformer], dtype=torch.float32)
# Create EMA for the transformer3d.
if args.use_ema:
ema_transformer3d = ConsisIDTransformer3DModel.from_pretrained_cus(
args.pretrained_model_name_or_path if args.pretrained_weight is None else args.pretrained_weight,
subfolder="transformer",
config_path=args.config_path,
transformer_additional_kwargs=transformer_additional_kwargs,
)
ema_transformer3d = EMAModel(ema_transformer3d.parameters(), model_cls=ConsisIDTransformer3DModel, model_config=ema_transformer3d.config)
def unwrap_model(model):
model = accelerator.unwrap_model(model)
model = model._orig_mod if is_compiled_module(model) else model
return model
# create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
def save_model_hook(models, weights, output_dir):
if accelerator.is_main_process:
transformer_lora_layers_to_save = None
if args.use_ema:
ema_transformer3d.save_pretrained(os.path.join(output_dir, "transformer_ema"))
for i, model in enumerate(models):
if args.is_train_lora:
transformer_lora_layers_to_save = get_peft_model_state_dict(model)
model.save_face_modules(os.path.join(output_dir, "face_modules.pt"))
else:
model.save_pretrained(os.path.join(output_dir, "transformer"))
if weights:
weights.pop()
if args.is_train_lora:
ConsisIDPipeline.save_lora_weights(
output_dir,
transformer_lora_layers=transformer_lora_layers_to_save,
)
with open(os.path.join(output_dir, "sampler_pos_start.pkl"), 'wb') as file:
pickle.dump([sampler._pos_start, first_epoch], file)
def load_model_hook(models, input_dir):
if args.use_ema:
ema_path = os.path.join(input_dir, "transformer_ema")
_, ema_kwargs = ConsisIDTransformer3DModel.load_config(ema_path, return_unused_kwargs=True)
load_model = ConsisIDTransformer3DModel.from_pretrained_cus(
input_dir,
subfolder="transformer_ema",
transformer_additional_kwargs=transformer_additional_kwargs,
)
load_model = EMAModel(load_model.parameters(), model_cls=ConsisIDTransformer3DModel, model_config=load_model.config)
load_model.load_state_dict(ema_kwargs)
ema_transformer3d.load_state_dict(load_model.state_dict())
ema_transformer3d.to(accelerator.device)
del load_model
for i in range(len(models)):
# pop models so that they are not loaded again
model = models.pop()
if args.is_train_lora:
lora_state_dict = ConsisIDPipeline.lora_state_dict(input_dir)
transformer_state_dict = {
f'{k.replace("transformer.", "")}': v for k, v in lora_state_dict.items() if k.startswith("transformer.")
}
transformer_state_dict = convert_unet_state_dict_to_peft(transformer_state_dict)
incompatible_keys = set_peft_model_state_dict(model, transformer_state_dict, adapter_name="default")
if incompatible_keys is not None:
# check only for unexpected keys
unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
if unexpected_keys:
logger.warning(
f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
f" {unexpected_keys}. "
)
model.load_face_modules(os.path.join(input_dir, "face_modules.pt"))
else:
# load diffusers style into model
load_model = ConsisIDTransformer3DModel.from_pretrained_cus(
input_dir,
subfolder="transformer",
transformer_additional_kwargs=transformer_additional_kwargs,
)
model.register_to_config(**load_model.config)
model.load_state_dict(load_model.state_dict())
del load_model
pkl_path = os.path.join(input_dir, "sampler_pos_start.pkl")
if os.path.exists(pkl_path):
with open(pkl_path, 'rb') as file:
loaded_number, _ = pickle.load(file)
sampler._pos_start = max(loaded_number - args.dataloader_num_workers * accelerator.num_processes * 2, 0)
print(f"Load pkl from {pkl_path}. Get loaded_number = {loaded_number}.")
# Make sure the trainable params are in float32. This is again needed since the base models
# are in `weight_dtype`. More details:
# https://github.com/huggingface/diffusers/pull/6514#discussion_r1449796804
if args.mixed_precision == "fp16":
# only upcast trainable parameters (LoRA) into fp32
cast_training_params([model])
accelerator.register_save_state_pre_hook(save_model_hook)
accelerator.register_load_state_pre_hook(load_model_hook)
# set trainable parameter
trainable_modules = ["."]
for name, param in transformer.named_parameters():
for trainable_module_name in trainable_modules:
if trainable_module_name in name:
param.requires_grad = True
break
if args.is_train_face:
unfreeze_modules = ["local_facial_extractor", "perceiver_cross_attention"]
for module_name in unfreeze_modules:
try:
for param in getattr(transformer, module_name).parameters():
param.requires_grad = True
except AttributeError:
continue
if args.is_train_lora:
transformer_lora_config = LoraConfig(
r=args.rank,
lora_alpha=args.lora_alpha,
init_lora_weights=True,
target_modules=["to_k", "to_q", "to_v", "to_out.0"],
exclude_modules=unfreeze_modules,
)
transformer.add_adapter(transformer_lora_config)
# Optimization parameters
if args.is_diff_lr:
fuse_face_ca_params = list(filter(lambda p: p.requires_grad, transformer.perceiver_cross_attention.parameters()))
fuse_face_ca_param_ids = {id(p) for p in fuse_face_ca_params}
transformer_params = [p for p in transformer.parameters() if p.requires_grad and id(p) not in fuse_face_ca_param_ids]
fuse_face_ca_params_with_lr = {"params": fuse_face_ca_params, "lr": args.learning_rate * 10}
transformer_params_with_lr = {"params": transformer_params, "lr": args.learning_rate * 0.1}
params_to_optimize = [fuse_face_ca_params_with_lr, transformer_params_with_lr]
else:
trainable_params = list(filter(lambda p: p.requires_grad, transformer.parameters()))
transformer_parameters_with_lr = {"params": trainable_params, "lr": args.learning_rate}
params_to_optimize = [transformer_parameters_with_lr]
use_deepspeed_optimizer = (
accelerator.state.deepspeed_plugin is not None
and "optimizer" in accelerator.state.deepspeed_plugin.deepspeed_config
)
use_deepspeed_scheduler = (
accelerator.state.deepspeed_plugin is not None
and "scheduler" in accelerator.state.deepspeed_plugin.deepspeed_config
)
args.use_deepspeed = accelerator.state.deepspeed_plugin is not None
optimizer = get_optimizer(args, params_to_optimize, use_deepspeed=use_deepspeed_optimizer)
# Dataset and DataLoader
train_dataset = ConsisID_Dataset(
instance_data_root=args.instance_data_root,
height=args.height,
width=args.width,
max_num_frames=args.max_num_frames,
id_token=args.id_token,
sample_stride=args.sample_stride,
skip_frames_start_percent=args.skip_frames_start_percent,
skip_frames_end_percent=args.skip_frames_end_percent,
skip_frames_start=args.skip_frames_start,
skip_frames_end=args.skip_frames_end,
is_train_face=args.is_train_face,
is_single_face=args.is_single_face,
miss_tolerance=args.miss_tolerance,
min_distance=args.min_distance,
min_frames=args.min_frames,
max_frames=args.max_frames,
is_cross_face=args.is_cross_face,
is_reserve_face=args.is_reserve_face
)
batch_sampler_generator = torch.Generator().manual_seed(args.seed)
if args.is_shuffle_data:
sampler = RandomSampler(train_dataset, generator=batch_sampler_generator)
else:
sampler = SequentialSampler(train_dataset, generator=batch_sampler_generator)
train_dataloader = DataLoader(
train_dataset,
batch_size=args.train_batch_size,
sampler=sampler,
num_workers=args.dataloader_num_workers,
pin_memory=True,
prefetch_factor=2 if args.dataloader_num_workers != 0 else None,
persistent_workers=True if args.dataloader_num_workers != 0 else False,
)
# Scheduler and math around the number of training steps.
overrode_max_train_steps = False
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
if args.max_train_steps is None:
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
overrode_max_train_steps = True
if use_deepspeed_scheduler:
from accelerate.utils import DummyScheduler
lr_scheduler = DummyScheduler(
name=args.lr_scheduler,
optimizer=optimizer,
total_num_steps=args.max_train_steps * accelerator.num_processes,
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
)
else:
lr_scheduler = get_scheduler(
args.lr_scheduler,
optimizer=optimizer,
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
num_training_steps=args.max_train_steps * accelerator.num_processes,
num_cycles=args.lr_num_cycles,
power=args.lr_power,
)
# Prepare everything with our `accelerator`.
transformer, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
transformer, optimizer, train_dataloader, lr_scheduler
)
if args.use_ema:
ema_transformer3d.to(accelerator.device)
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
if overrode_max_train_steps:
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
# Afterwards we recalculate our number of training epochs
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
# We need to initialize the trackers we use, and also store our configuration.
# The trackers initializes automatically on the main process.
if accelerator.is_main_process:
tracker_name = args.tracker_name or "consisid-ipt2v"
accelerator.init_trackers(tracker_name, config=vars(args))
# Train!
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
num_trainable_parameters = sum(param.numel() for model in params_to_optimize for param in model["params"])
logger.info("***** Running training *****")
logger.info(f" Num trainable parameters = {num_trainable_parameters}")
logger.info(f" Num examples = {len(train_dataset)}")
logger.info(f" Num batches each epoch = {len(train_dataloader)}")
logger.info(f" Num epochs = {args.num_train_epochs}")
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
logger.info(f" Gradient accumulation steps = {args.gradient_accumulation_steps}")
logger.info(f" Total optimization steps = {args.max_train_steps}")
global_step = 0
first_epoch = 0
# Potentially load in the weights and states from a previous save
if not args.resume_from_checkpoint:
initial_global_step = 0
else:
if args.resume_from_checkpoint != "latest":
path = os.path.basename(args.resume_from_checkpoint)
else:
# Get the mos recent checkpoint
dirs = os.listdir(args.output_dir)
dirs = [d for d in dirs if d.startswith("checkpoint")]
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
path = dirs[-1] if len(dirs) > 0 else None
if path is None:
accelerator.print(
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
)
args.resume_from_checkpoint = None
initial_global_step = 0
else:
accelerator.print(f"Resuming from checkpoint {path}")
if args.is_accelerator_state_dict:
# way_1
accelerator.load_state(os.path.join(args.output_dir, path))
else:
# way_2
pretrained_model_path = os.path.join(args.output_dir, path)
if args.use_ema:
ema_path = os.path.join(pretrained_model_path, "transformer_ema")
_, ema_kwargs = ConsisIDTransformer3DModel.load_config(ema_path, return_unused_kwargs=True)
load_model = ConsisIDTransformer3DModel.from_pretrained_cus(
pretrained_model_path,
subfolder="transformer_ema",
transformer_additional_kwargs=transformer_additional_kwargs,
)
load_model = EMAModel(load_model.parameters(), model_cls=ConsisIDTransformer3DModel, model_config=load_model.config)
load_model.load_state_dict(ema_kwargs)
ema_transformer3d.load_state_dict(load_model.state_dict())
ema_transformer3d.to(accelerator.device)
del load_model
load_model = ConsisIDTransformer3DModel.from_pretrained_cus(
pretrained_model_path,
subfolder="transformer",
transformer_additional_kwargs=transformer_additional_kwargs,
)
transformer.register_to_config(**load_model.config)
m, u = accelerator.unwrap_model(transformer).load_state_dict(load_model.state_dict(), strict=False)
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
del load_model
global_step = int(path.split("-")[1])
initial_global_step = global_step
pkl_path = os.path.join(os.path.join(args.output_dir, path), "sampler_pos_start.pkl")
if os.path.exists(pkl_path):
with open(pkl_path, 'rb') as file:
_, first_epoch = pickle.load(file)
else:
first_epoch = global_step // num_update_steps_per_epoch
print(f"Load pkl from {pkl_path}. Get first_epoch = {first_epoch}.")
progress_bar = tqdm(
range(0, args.max_train_steps),
initial=initial_global_step,
desc="Steps",
# Only show the progress bar once on each machine.
disable=not accelerator.is_local_main_process,
)
vae_scale_factor_spatial = 2 ** (len(vae.config.block_out_channels) - 1)
# For DeepSpeed training
model_config = transformer.module.config if hasattr(transformer, "module") else transformer.config
def process_image(image, vae):
image_noise_sigma = torch.normal(mean=-3.0, std=0.5, size=(1,), device=image.device)
image_noise_sigma = torch.exp(image_noise_sigma).to(dtype=image.dtype)
noisy_image = torch.randn_like(image) * image_noise_sigma[:, None, None, None, None]
input_image = image + noisy_image
image_latent_dist = vae.encode(input_image).latent_dist
return image_latent_dist
def encode_video(video, get_image_latent=True):
video = video.to(accelerator.device, dtype=vae.dtype).unsqueeze(0) # [F, C, H, W] -> [B, F, C, H, W]
video = video.permute(0, 2, 1, 3, 4) # [B, C, F, H, W]
image = video[:, :, :1].clone()
latent_dist = vae.encode(video).latent_dist
if get_image_latent:
image_latent_dist = process_image(image, vae)
else:
image_latent_dist = None
return latent_dist, image_latent_dist
def compute_prompt_embeddings_for_batch(prompts):
return [
compute_prompt_embeddings(
tokenizer,
text_encoder,
[prompt],
model_config.max_text_seq_length,
accelerator.device,
weight_dtype,
requires_grad=False,
)
for prompt in prompts
]
for epoch in range(first_epoch, args.num_train_epochs):
transformer.train()
sampler.generator = torch.Generator().manual_seed(args.seed + epoch)
for step, batch in enumerate(train_dataloader):
free_memory()
models_to_accumulate = [transformer]
with accelerator.accumulate(models_to_accumulate):
if args.low_vram:
free_memory()
vae.to(accelerator.device)
text_encoder.to(accelerator.device)
if args.is_train_face:
face_clip_model.to(accelerator.device)
face_helper_1.face_det.to(accelerator.device)
face_helper_1.face_parse.to(accelerator.device)
with torch.no_grad():
id_cond = None
id_vit_hidden = None
dense_masks = None
face_kps_latents = None
batch_instance_video = batch["instance_video"]
batch_instance_prompt = batch["instance_prompt"]
if args.is_train_face and args.enable_mask_loss and random.random() < 0.5:
enable_mask_loss_flag = True
else:
enable_mask_loss_flag = False
if args.is_train_face:
expand_face_imgs = batch['expand_face_imgs'] if batch['expand_face_imgs'] is not None else None # [B, self.max_frames, C=3, H=112, W=112]
original_face_imgs = batch['original_face_imgs'] if batch['original_face_imgs'] is not None else None # [B, self.max_frames, C=3, H=112, W=112]
if args.is_reserve_face:
reserve_face_imgs = batch["reserve_face_imgs"] # torch.Size([2, 5, 3, 480, 480])
if args.enable_mask_loss and enable_mask_loss_flag:
dense_masks = batch['dense_masks_tensor'].to(memory_format=torch.contiguous_format).to(dtype=weight_dtype) if batch['dense_masks_tensor'] is not None else None # B 1 T H W
if face_clip_model is not None and face_main_model is not None:
B, T = expand_face_imgs.shape[:2]
expand_valid_face_imgs = []
original_valid_face_imgs = []
B_valid_num = torch.zeros(B, dtype=torch.int32)
for i in range(B):
valid_mask = torch.any(torch.any(torch.any(expand_face_imgs[i] != 0, dim=1), dim=1), dim=1)
B_valid_num[i] = valid_mask.sum()
expand_valid_face_imgs.extend(expand_face_imgs[i][valid_mask])
original_valid_face_imgs.extend(original_face_imgs[i][valid_mask])
B_valid_num.to(accelerator.device)
expand_face_imgs = torch.stack(expand_valid_face_imgs) # torch.Size([2, 3, 480, 480])
original_face_imgs = torch.stack(original_valid_face_imgs) # torch.Size([2, 3, 480, 480])
align_crop_face_imgs = []
valid_id_conds = []
valid_id_vit_hiddens = []
valid_indices = []
face_kps_list = []
for idx, id_image in enumerate(expand_face_imgs): # id_image: torch.Size([3, 480, 480])
align_crop_face_image = None
id_cond = None
id_vit_hidden = None
try:
id_image = np.array(tensor_to_pil(id_image).convert("RGB"))
id_image = resize_numpy_image_long(id_image, 1024)
original_id_image = None
if not args.is_align_face:
original_id_image = np.array(tensor_to_pil(original_face_imgs[idx]).convert("RGB"))
original_id_image = resize_numpy_image_long(original_id_image, 1024)
id_cond, id_vit_hidden, align_crop_face_image, face_kps = process_face_embeddings(face_helper_1, face_clip_model, face_helper_2, eva_transform_mean, eva_transform_std, face_main_model, accelerator.device, weight_dtype, id_image, original_id_image=original_id_image, is_align_face=args.is_align_face)
except Exception as e:
processed = False
if args.is_reserve_face:
print(f"Initial processing failed for image {idx}, attempting to process reserve images. Error: {e}")
original_id_image = None
if not args.is_align_face:
original_id_image = np.array(tensor_to_pil(original_face_imgs[idx]).convert("RGB"))
original_id_image = resize_numpy_image_long(original_id_image, 1024)
for reserve_idx, reserve_id_image in enumerate(reserve_face_imgs[idx]):
id_image = np.array(tensor_to_pil(reserve_id_image).convert("RGB"))
id_image = resize_numpy_image_long(id_image, 1024)
try:
id_cond, id_vit_hidden, align_crop_face_image, face_kps = process_face_embeddings(
face_helper_1, face_clip_model, face_helper_2, eva_transform_mean, eva_transform_std,
face_main_model, accelerator.device, weight_dtype, id_image, original_id_image=original_id_image,
is_align_face=args.is_align_face
)
processed = True
break
except Exception as inner_e:
print(f"Reserve image {reserve_idx} processing failed, trying next reserve image. Error: {inner_e}")
continue
if not processed:
print(f"All reserve images failed, attempting to process frames from video. Error: {e}")
Len_frame = batch_instance_video.shape[1]
original_id_image = None
if not args.is_align_face:
original_id_image = np.array(tensor_to_pil(original_face_imgs[idx]).convert("RGB"))
original_id_image = resize_numpy_image_long(original_id_image, 1024)
for frame_idx in range(0, Len_frame, 5):
try:
temp_image = pixel_values_to_pil(batch_instance_video[idx].clone().cpu(), frame_index=frame_idx)
id_image = np.array(temp_image.convert("RGB"))
id_image = resize_numpy_image_long(id_image, 1024)
id_cond, id_vit_hidden, align_crop_face_image, face_kps = process_face_embeddings(
face_helper_1, face_clip_model, face_helper_2, eva_transform_mean, eva_transform_std,
face_main_model, accelerator.device, weight_dtype, id_image, original_id_image=original_id_image,
is_align_face=args.is_align_face
)
processed = True
break
except Exception as inner_e:
print(f"Frame {frame_idx} processing failed, trying next frame. Error: {inner_e}")
continue
if not processed:
print(f"All attempts failed for image {idx}. No valid embeddings could be generated.")
if id_cond is not None:
valid_id_conds.append(id_cond)
valid_id_vit_hiddens.append(id_vit_hidden)
align_crop_face_imgs.append(align_crop_face_image)
valid_indices.append(idx)
if args.is_kps:
face_kps_list.append(face_kps)