forked from bghira/SimpleTuner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_sdxl.py
2210 lines (2051 loc) · 96.4 KB
/
train_sdxl.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
#!/usr/bin/env python
# coding=utf-8
# Copyright 2023 pseudoterminalX, CaptnSeraph and The HuggingFace Inc. 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.
from helpers import log_format
import shutil, hashlib, json, copy, random, logging, math, os, sys
# Quiet down, you.
os.environ["ACCELERATE_LOG_LEVEL"] = "WARNING"
from pathlib import Path
from helpers.arguments import parse_args
from helpers.caching.memory import reclaim_memory
from helpers.legacy.validation import prepare_validation_prompt_list
from helpers.training.validation import Validation
from helpers.training.state_tracker import StateTracker
from helpers.training.deepspeed import deepspeed_zero_init_disabled_context_manager
from helpers.training.wrappers import unwrap_model
from helpers.data_backend.factory import configure_multi_databackend
from helpers.data_backend.factory import random_dataloader_iterator
from helpers.training.custom_schedule import (
get_polynomial_decay_schedule_with_warmup,
generate_timestep_weights,
segmented_timestep_selection,
)
from helpers.training.min_snr_gamma import compute_snr
from helpers.prompts import PromptHandler
from accelerate.logging import get_logger
logger = get_logger(__name__, log_level=os.environ.get("SIMPLETUNER_LOG_LEVEL", "INFO"))
filelock_logger = get_logger("filelock")
connection_logger = get_logger("urllib3.connectionpool")
training_logger = get_logger("training-loop")
# More important logs.
target_level = os.environ.get("SIMPLETUNER_LOG_LEVEL", "INFO")
logger.setLevel(target_level)
training_logger_level = os.environ.get("SIMPLETUNER_TRAINING_LOOP_LOG_LEVEL", "INFO")
training_logger.setLevel(training_logger_level)
# Less important logs.
filelock_logger.setLevel("WARNING")
connection_logger.setLevel("WARNING")
import numpy as np
import torch, diffusers, accelerate, transformers
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint
from accelerate import Accelerator
from accelerate.utils import ProjectConfiguration, set_seed
from huggingface_hub import create_repo, upload_folder
from packaging import version
from tqdm.auto import tqdm
from helpers.training.custom_schedule import get_sd3_sigmas
from transformers import AutoTokenizer, PretrainedConfig, CLIPTokenizer
from helpers.sdxl.pipeline import StableDiffusionXLPipeline
from diffusers import StableDiffusion3Pipeline
from diffusers import (
AutoencoderKL,
ControlNetModel,
DDIMScheduler,
DDPMScheduler,
DPMSolverMultistepScheduler,
UNet2DConditionModel,
EulerDiscreteScheduler,
EulerAncestralDiscreteScheduler,
UniPCMultistepScheduler,
)
from peft import LoraConfig
from peft.utils import get_peft_model_state_dict
from diffusers.optimization import get_scheduler
from diffusers.training_utils import EMAModel
from diffusers.utils import (
check_min_version,
convert_state_dict_to_diffusers,
is_wandb_available,
)
from diffusers.utils.import_utils import is_xformers_available
from transformers.utils import ContextManagers
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
check_min_version("0.27.0.dev0")
SCHEDULER_NAME_MAP = {
"euler": EulerDiscreteScheduler,
"euler-a": EulerAncestralDiscreteScheduler,
"unipc": UniPCMultistepScheduler,
"ddim": DDIMScheduler,
"ddpm": DDPMScheduler,
}
def import_model_class_from_model_name_or_path(
pretrained_model_name_or_path: str, revision: str, subfolder: str = "text_encoder"
):
text_encoder_config = PretrainedConfig.from_pretrained(
pretrained_model_name_or_path, subfolder=subfolder, revision=revision
)
model_class = text_encoder_config.architectures[0]
if model_class == "CLIPTextModel":
from transformers import CLIPTextModel
return CLIPTextModel
elif model_class == "CLIPTextModelWithProjection":
from transformers import CLIPTextModelWithProjection
return CLIPTextModelWithProjection
elif model_class == "T5EncoderModel":
from transformers import T5EncoderModel
return T5EncoderModel
else:
raise ValueError(f"{model_class} is not supported.")
def get_tokenizers(args):
tokenizer_1, tokenizer_2, tokenizer_3 = None, None, None
try:
tokenizer_kwargs = {
"pretrained_model_name_or_path": args.pretrained_model_name_or_path,
"subfolder": "tokenizer",
"revision": args.revision,
}
if not args.pixart_sigma:
tokenizer_1 = CLIPTokenizer.from_pretrained(**tokenizer_kwargs)
else:
from transformers import T5Tokenizer
text_encoder_path = (
args.pretrained_t5_model_name_or_path
if args.pretrained_t5_model_name_or_path is not None
else args.pretrained_model_name_or_path
)
logger.info(
f"Tokenizer path: {text_encoder_path}, custom T5 model path: {args.pretrained_t5_model_name_or_path} revision: {args.revision}"
)
try:
tokenizer_1 = T5Tokenizer.from_pretrained(
text_encoder_path,
subfolder="tokenizer",
revision=args.revision,
use_fast=False,
)
except Exception as e:
logger.warning(
f"Failed to load tokenizer 1: {e}, attempting no subfolder"
)
tokenizer_1 = T5Tokenizer.from_pretrained(
text_encoder_path,
subfolder=None,
revision=args.revision,
use_fast=False,
)
except Exception as e:
import traceback
logger.warning(
"Primary tokenizer (CLIP-L/14) failed to load. Continuing to test whether we have just the secondary tokenizer.."
f"\nError: -> {e}"
f"\nTraceback: {traceback.format_exc()}"
)
if args.sd3:
raise e
if not args.pixart_sigma:
try:
tokenizer_2 = CLIPTokenizer.from_pretrained(
args.pretrained_model_name_or_path,
subfolder="tokenizer_2",
revision=args.revision,
use_fast=False,
)
if tokenizer_1 is None:
logger.info("Seems that we are training an SDXL refiner model.")
StateTracker.is_sdxl_refiner(True)
if args.validation_using_datasets is None:
logger.warning(
f"Since we are training the SDXL refiner and --validation_using_datasets was not specified, it is now being enabled."
)
args.validation_using_datasets = True
except:
logger.warning(
"Could not load secondary tokenizer (OpenCLIP-G/14). Cannot continue."
)
if not tokenizer_1 and not tokenizer_2:
raise Exception("Failed to load tokenizer")
else:
if not tokenizer_1:
raise Exception("Failed to load tokenizer")
if args.sd3:
try:
from transformers import T5TokenizerFast
tokenizer_3 = T5TokenizerFast.from_pretrained(
args.pretrained_model_name_or_path,
subfolder="tokenizer_3",
revision=args.revision,
use_fast=True,
)
except:
raise ValueError(
"Could not load tertiary tokenizer (T5-XXL v1.1). Cannot continue."
)
return tokenizer_1, tokenizer_2, tokenizer_3
def main():
StateTracker.set_model_type("sdxl")
args = parse_args()
if args.sd3:
StateTracker.set_model_type("sd3")
if args.pixart_sigma:
StateTracker.set_model_type("pixart_sigma")
StateTracker.set_args(args)
if not args.preserve_data_backend_cache:
StateTracker.delete_cache_files(
preserve_data_backend_cache=args.preserve_data_backend_cache
)
logging_dir = os.path.join(args.output_dir, args.logging_dir)
accelerator_project_config = ProjectConfiguration(
project_dir=args.output_dir, logging_dir=logging_dir
)
from accelerate import InitProcessGroupKwargs
from datetime import timedelta
# Create the custom configuration
process_group_kwargs = InitProcessGroupKwargs(
timeout=timedelta(seconds=5400)
) # 1.5 hours
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=[process_group_kwargs],
)
StateTracker.set_accelerator(accelerator)
webhook_handler = None
if args.webhook_config is not None:
from helpers.webhooks.handler import WebhookHandler
webhook_handler = WebhookHandler(
args.webhook_config,
accelerator,
f"{args.tracker_project_name} {args.tracker_run_name}",
)
StateTracker.set_webhook_handler(webhook_handler)
webhook_handler.send(
message="SimpleTuner has launched. Hold onto your butts!",
store_response=True,
)
# Make one log on every process with the configuration for debugging.
# logger.info(accelerator.state, main_process_only=True)
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()
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO,
)
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."
)
import wandb
if (
hasattr(accelerator.state, "deepspeed_plugin")
and accelerator.state.deepspeed_plugin is not None
):
if "lora" in args.model_type:
logger.error(
"LoRA can not be trained with DeepSpeed. Please disable DeepSpeed via 'accelerate config' before reattempting."
)
sys.exit(1)
if (
"gradient_accumulation_steps"
in accelerator.state.deepspeed_plugin.deepspeed_config
):
args.gradient_accumulation_steps = (
accelerator.state.deepspeed_plugin.deepspeed_config[
"gradient_accumulation_steps"
]
)
logger.info(
f"Updated gradient_accumulation_steps to the value provided by DeepSpeed: {args.gradient_accumulation_steps}"
)
# If passed along, set the training seed now.
if args.seed is not None and args.seed != 0:
set_seed(args.seed, args.seed_for_each_device)
# Handle the repository creation
if accelerator.is_main_process:
if args.output_dir is not None:
os.makedirs(args.output_dir, exist_ok=True)
if args.push_to_hub:
from helpers.publishing.huggingface import HubManager
hub_manager = HubManager(config=args)
vae_path = (
args.pretrained_model_name_or_path
if args.pretrained_vae_model_name_or_path is None
else args.pretrained_vae_model_name_or_path
)
# 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():
logger.info(
"Enabling tf32 precision boost for NVIDIA devices due to --allow_tf32."
)
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
elif torch.cuda.is_available():
logger.warning(
"If using an Ada or Ampere NVIDIA device, --allow_tf32 could add a bit more performance."
)
if args.lr_scale:
logger.info(f"Scaling learning rate ({args.learning_rate}), due to --lr_scale")
args.learning_rate = (
args.learning_rate
* args.gradient_accumulation_steps
* args.train_batch_size
* accelerator.num_processes
)
# For mixed precision training we cast the text_encoder and vae weights to half-precision
# as these models are only used for inference, keeping weights in full precision is not required.
weight_dtype = torch.bfloat16
StateTracker.set_weight_dtype(weight_dtype)
# Load scheduler, tokenizer and models.
logger.info("Load tokenizers")
# SDXL style models use text encoder and tokenizer 1 and 2, while SD3 will use all three.
# Pixart Sigma just uses one T5 XXL model.
# If --disable_text_encoder is provided, we will skip loading entirely.
tokenizer_1, tokenizer_2, tokenizer_3 = get_tokenizers(args)
text_encoder_1, text_encoder_2, text_encoder_3 = None, None, None
text_encoders = []
tokenizers = []
if not args.pixart_sigma:
# sdxl and sd3 use the sd 1.5 encoder as number one.
logger.info("Load OpenAI CLIP-L/14 text encoder..")
text_encoder_path = args.pretrained_model_name_or_path
text_encoder_subfolder = "text_encoder"
else:
text_encoder_path = (
args.pretrained_t5_model_name_or_path
if args.pretrained_t5_model_name_or_path is not None
else args.pretrained_model_name_or_path
)
# Google's version of the T5 XXL model doesn't have a subfolder :()
text_encoder_subfolder = "text_encoder"
if tokenizer_1 is not None:
text_encoder_cls_1 = import_model_class_from_model_name_or_path(
text_encoder_path, args.revision, subfolder=text_encoder_subfolder
)
if tokenizer_2 is not None:
text_encoder_cls_2 = import_model_class_from_model_name_or_path(
args.pretrained_model_name_or_path,
args.revision,
subfolder="text_encoder_2",
)
if tokenizer_3 is not None and args.sd3:
text_encoder_cls_3 = import_model_class_from_model_name_or_path(
args.pretrained_model_name_or_path,
args.revision,
subfolder="text_encoder_3",
)
# Load scheduler and models
if args.sd3 and not args.sd3_uses_diffusion:
# Stable Diffusion 3 uses rectified flow.
from diffusers import FlowMatchEulerDiscreteScheduler
noise_scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
args.pretrained_model_name_or_path, subfolder="scheduler"
)
noise_scheduler_copy = copy.deepcopy(noise_scheduler)
else:
if args.sd3 and args.sd3_uses_diffusion:
logger.warning(
"Since --sd3_uses_diffusion is provided, we will be reparameterising the model to v-prediction diffusion objective. This will break things for a while."
)
# SDXL uses the old style noise scheduler.
noise_scheduler = DDPMScheduler.from_pretrained(
args.pretrained_model_name_or_path,
subfolder="scheduler",
prediction_type=args.prediction_type,
rescale_betas_zero_snr=args.rescale_betas_zero_snr,
timestep_spacing=args.training_scheduler_timestep_spacing,
)
if args.sd3 and args.sd3_uses_diffusion:
logger.info(
f"Stable Diffusion 3 noise scheduler config: {noise_scheduler.config}"
)
# Currently Accelerate doesn't know how to handle multiple models under Deepspeed ZeRO stage 3.
# For this to work properly all models must be run through `accelerate.prepare`. But accelerate
# will try to assign the same optimizer with the same weights to all models during
# `deepspeed.initialize`, which of course doesn't work.
#
# For now the following workaround will partially support Deepspeed ZeRO-3, by excluding the 2
# frozen models from being partitioned during `zero.Init` which gets called during
# `from_pretrained` So CLIPTextModel and AutoencoderKL will not enjoy the parameter sharding
# across multiple gpus and only UNet2DConditionModel will get ZeRO sharded.
with ContextManagers(deepspeed_zero_init_disabled_context_manager()):
if tokenizer_1 is not None:
logger.info(
f"Loading T5-XXL v1.1 text encoder from {text_encoder_path}/{text_encoder_subfolder}.."
)
text_encoder_1 = text_encoder_cls_1.from_pretrained(
text_encoder_path,
subfolder=text_encoder_subfolder,
revision=args.revision,
variant=args.variant,
)
if tokenizer_2 is not None:
logger.info("Loading LAION OpenCLIP-G/14 text encoder..")
text_encoder_2 = text_encoder_cls_2.from_pretrained(
args.pretrained_model_name_or_path,
subfolder="text_encoder_2",
revision=args.revision,
variant=args.variant,
)
if tokenizer_3 is not None and args.sd3:
logger.info("Loading T5-XXL v1.1 text encoder..")
text_encoder_3 = text_encoder_cls_3.from_pretrained(
args.pretrained_model_name_or_path,
subfolder="text_encoder_3",
revision=args.revision,
variant=args.variant,
)
logger.info("Load VAE..")
vae = AutoencoderKL.from_pretrained(
vae_path,
subfolder="vae" if args.pretrained_vae_model_name_or_path is None else None,
revision=args.revision,
force_upcast=False,
variant=args.variant,
)
logger.info("Moving models to GPU. Almost there.")
if tokenizer_1 is not None:
text_encoder_1.to(accelerator.device, dtype=weight_dtype)
if tokenizer_2 is not None:
text_encoder_2.to(accelerator.device, dtype=weight_dtype)
if tokenizer_1 is not None or tokenizer_2 is not None:
tokenizers = [tokenizer_1, tokenizer_2]
text_encoders = [text_encoder_1, text_encoder_2]
if tokenizer_3 is not None:
text_encoder_3.to(accelerator.device, dtype=weight_dtype)
tokenizers = [tokenizer_1, tokenizer_2, tokenizer_3]
text_encoders = [text_encoder_1, text_encoder_2, text_encoder_3]
# Freeze vae and text_encoders
if vae is not None:
vae.requires_grad_(False)
if text_encoder_1 is not None:
text_encoder_1.requires_grad_(False)
if text_encoder_2 is not None:
text_encoder_2.requires_grad_(False)
if text_encoder_3 is not None:
text_encoder_3.requires_grad_(False)
if webhook_handler is not None:
webhook_handler.send(
message=f"Loading model: `{args.pretrained_model_name_or_path}`..."
)
pretrained_load_args = {
"revision": args.revision,
"variant": args.variant,
}
if args.sd3:
# Stable Diffusion 3 uses a Diffusion transformer.
logger.info(f"Loading Stable Diffusion 3 diffusion transformer..")
unet = None
try:
from diffusers import SD3Transformer2DModel
except Exception as e:
logger.error(
f"Can not load SD3 model class. This release requires the latest version of Diffusers: {e}"
)
transformer = SD3Transformer2DModel.from_pretrained(
args.pretrained_model_name_or_path,
subfolder="transformer",
**pretrained_load_args,
)
elif args.pixart_sigma:
from diffusers.models import PixArtTransformer2DModel
unet = None
transformer = PixArtTransformer2DModel.from_pretrained(
args.pretrained_model_name_or_path,
subfolder="transformer",
**pretrained_load_args,
)
else:
logger.info(f"Loading SDXL U-net..")
transformer = None
unet = UNet2DConditionModel.from_pretrained(
args.pretrained_model_name_or_path, subfolder="unet", **pretrained_load_args
)
model_type_label = "SDXL"
if StateTracker.is_sdxl_refiner():
model_type_label = "SDXL Refiner"
if args.sd3:
model_type_label = "Stable Diffusion 3"
if args.pixart_sigma:
model_type_label = "PixArt Sigma"
if args.controlnet:
if args.pixart_sigma:
raise ValueError(
f"ControlNet is not yet supported with {model_type_label} models. Please disable --controlnet, or switch model types."
)
if (
"deepfloyd" in StateTracker.get_args().model_type
or StateTracker.is_sdxl_refiner()
or args.sd3
):
raise ValueError(
f"ControlNet is not yet supported with {model_type_label} models. Please disable --controlnet, or switch model types."
)
logger.info("Creating the controlnet..")
if args.controlnet_model_name_or_path:
logger.info("Loading existing controlnet weights")
controlnet = ControlNetModel.from_pretrained(
args.controlnet_model_name_or_path
)
else:
logger.info("Initializing controlnet weights from unet")
controlnet = ControlNetModel.from_unet(unet)
elif "lora" in args.model_type:
if args.pixart_sigma:
raise Exception("PixArt does not support LoRA model training.")
logger.info("Using LoRA training mode.")
if webhook_handler is not None:
webhook_handler.send(message="Using LoRA training mode.")
# now we will add new LoRA weights to the attention layers
# Set correct lora layers
if transformer is not None:
transformer.requires_grad_(False)
if unet is not None:
unet.requires_grad_(False)
lora_initialisation_style = True
if hasattr(args, "lora_init_method") and args.lora_init_method is not None:
lora_initialisation_style = args.lora_init_method
lora_weight_init_type = (
"gaussian"
if torch.backends.mps.is_available()
else lora_initialisation_style
)
if args.use_dora:
logger.warning(
"DoRA support is experimental and not very thoroughly tested."
)
lora_weight_init_type = "gaussian"
if unet is not None:
unet_lora_config = LoraConfig(
r=args.lora_rank,
lora_alpha=args.lora_alpha,
lora_dropout=args.lora_dropout,
init_lora_weights=lora_weight_init_type,
target_modules=["to_k", "to_q", "to_v", "to_out.0"],
use_dora=args.use_dora,
)
logger.info("Adding LoRA adapter to the unet model..")
unet.add_adapter(unet_lora_config)
if transformer is not None:
transformer_lora_config = LoraConfig(
r=args.lora_rank,
lora_alpha=args.lora_alpha,
init_lora_weights=lora_weight_init_type,
target_modules=["to_k", "to_q", "to_v", "to_out.0"],
use_dora=args.use_dora,
)
transformer.add_adapter(transformer_lora_config)
logger.info(
f"Moving the {'U-net' if unet is not None else 'diffusion transformer'} to GPU in {weight_dtype} precision."
)
if unet is not None:
unet.to(accelerator.device, dtype=weight_dtype)
if transformer is not None:
transformer.to(accelerator.device, dtype=weight_dtype)
if (
args.enable_xformers_memory_efficient_attention
and not args.sd3
and not args.pixart_sigma
):
logger.info("Enabling xformers memory-efficient attention.")
if is_xformers_available():
import xformers # type: ignore
if unet is not None:
unet.enable_xformers_memory_efficient_attention()
if transformer is not None:
transformer.enable_xformers_memory_efficient_attention()
if args.controlnet:
controlnet.enable_xformers_memory_efficient_attention()
else:
raise ValueError(
"xformers is not available. Make sure it is installed correctly"
)
if args.controlnet:
# We freeze the base u-net for controlnet training.
if unet is not None:
unet.requires_grad_(False)
if transformer is not None:
transformer.requires_grad_(False)
controlnet.train()
controlnet.to(device=accelerator.device, dtype=weight_dtype)
if args.train_text_encoder:
logger.warning(
"Unknown results will occur when finetuning the text encoder alongside ControlNet."
)
# Move vae, unet and text_encoder to device and cast to weight_dtype
# The VAE is in bfloat16 to avoid NaN losses.
vae_dtype = torch.bfloat16
if hasattr(args, "vae_dtype"):
logger.info(
f"Initialising VAE in {args.vae_dtype} precision, you may specify a different value if preferred: bf16, fp32, default"
)
# Let's use a case-switch for convenience: bf16, fp16, fp32, none/default
if args.vae_dtype == "bf16":
vae_dtype = torch.bfloat16
elif args.vae_dtype == "fp16":
raise ValueError(
"fp16 is not supported for SDXL's VAE. Please use bf16 or fp32."
)
elif args.vae_dtype == "fp32":
vae_dtype = torch.float32
elif args.vae_dtype == "none" or args.vae_dtype == "default":
vae_dtype = torch.bfloat16
if args.pretrained_vae_model_name_or_path is not None:
logger.debug(f"Initialising VAE with weight dtype {vae_dtype}")
vae.to(accelerator.device, dtype=vae_dtype)
else:
logger.debug(f"Initialising VAE with custom dtype {vae_dtype}")
vae.to(accelerator.device, dtype=vae_dtype)
StateTracker.set_vae_dtype(vae_dtype)
StateTracker.set_vae(vae)
logger.info(f"Loaded VAE into VRAM.")
# Create a DataBackend, so that we can access our dataset.
prompt_handler = None
if not args.disable_compel and not args.sd3 and not args.pixart_sigma:
# SD3 and PixArt don't really work with prompt weighting.
prompt_handler = PromptHandler(
args=args,
text_encoders=[text_encoder_1, text_encoder_2],
tokenizers=[tokenizer_1, tokenizer_2],
accelerator=accelerator,
model_type="sdxl",
)
try:
if webhook_handler is not None:
webhook_handler.send(
message="Configuring data backends... (this may take a while!)"
)
configure_multi_databackend(
args,
accelerator=accelerator,
text_encoders=text_encoders,
tokenizers=tokenizers,
prompt_handler=prompt_handler,
)
except Exception as e:
import traceback
logger.error(f"{e}, traceback: {traceback.format_exc()}")
if webhook_handler is not None:
webhook_handler.send(
message=f"Failed to load data backends: {e}", message_level="critical"
)
sys.exit(0)
with accelerator.main_process_first():
(
validation_prompts,
validation_shortnames,
validation_negative_prompt_embeds,
validation_negative_pooled_embeds,
) = prepare_validation_prompt_list(
args=args, embed_cache=StateTracker.get_default_text_embed_cache()
)
accelerator.wait_for_everyone()
# Grab GPU memory used:
if args.model_type == "full" or not args.train_text_encoder:
memory_before_unload = torch.cuda.memory_allocated() / 1024**3
if accelerator.is_main_process:
logger.info(f"Unloading text encoders, as they are not being trained.")
del text_encoder_1, text_encoder_2, text_encoder_3
text_encoder_1 = None
text_encoder_2 = None
text_encoder_3 = None
text_encoders = []
reclaim_memory()
memory_after_unload = torch.cuda.memory_allocated() / 1024**3
memory_saved = memory_after_unload - memory_before_unload
logger.info(
f"After nuking text encoders from orbit, we freed {abs(round(memory_saved, 2))} GB of VRAM."
" The real memories were the friends we trained a model on along the way."
)
# Scheduler and math around the number of training steps.
overrode_max_train_steps = False
# Check if we have a valid gradient accumulation steps.
if args.gradient_accumulation_steps < 1:
raise ValueError(
f"Invalid gradient_accumulation_steps parameter: {args.gradient_accumulation_steps}, should be >= 1"
)
# We calculate the number of steps per epoch by dividing the number of images by the effective batch divisor.
# Gradient accumulation steps mean that we only update the model weights every /n/ steps.
collected_data_backend_str = list(StateTracker.get_data_backends().keys())
if args.push_to_hub and accelerator.is_main_process:
hub_manager.collected_data_backend_str = collected_data_backend_str
hub_manager.set_validation_prompts(validation_prompts, validation_shortnames)
logger.debug(f"Collected validation prompts: {validation_prompts}")
logger.info(f"Collected the following data backends: {collected_data_backend_str}")
if webhook_handler is not None:
webhook_handler.send(
message=f"Collected the following data backends: {collected_data_backend_str}"
)
total_num_batches = sum(
[
len(backend["metadata_backend"] if "metadata_backend" in backend else [])
for _, backend in StateTracker.get_data_backends().items()
]
)
num_update_steps_per_epoch = math.ceil(
total_num_batches / args.gradient_accumulation_steps
)
if args.max_train_steps is None or args.max_train_steps == 0:
if args.num_train_epochs is None or args.num_train_epochs == 0:
raise ValueError(
"You must specify either --max_train_steps or --num_train_epochs with a value > 0"
)
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
logger.info(
f"Calculated our maximum training steps at {args.max_train_steps} because we have"
f" {args.num_train_epochs} epochs and {num_update_steps_per_epoch} steps per epoch."
)
overrode_max_train_steps = True
logger.info(
f"Loading {args.lr_scheduler} learning rate scheduler with {args.lr_warmup_steps} warmup steps"
)
if args.freeze_unet_strategy == "bitfit":
from helpers.training.model_freeze import apply_bitfit_freezing
if unet is not None:
logger.info(f"Applying BitFit freezing strategy to the U-net.")
unet = apply_bitfit_freezing(unet, args)
if transformer is not None:
logger.warning(
f"Training Diffusion transformer models with BitFit is not yet tested, and unexpected results may occur."
)
transformer = apply_bitfit_freezing(transformer, args)
if args.gradient_checkpointing:
if unet is not None:
unet.enable_gradient_checkpointing()
if transformer is not None:
transformer.enable_gradient_checkpointing()
if args.controlnet:
controlnet.enable_gradient_checkpointing()
if hasattr(args, "train_text_encoder") and args.train_text_encoder:
text_encoder_1.gradient_checkpointing_enable()
text_encoder_2.gradient_checkpointing_enable()
if text_encoder_3:
text_encoder_3.gradient_checkpointing_enable()
logger.info(f"Learning rate: {args.learning_rate}")
extra_optimizer_args = {
"weight_decay": args.adam_weight_decay,
"eps": args.adam_epsilon,
}
use_deepspeed_optimizer = False
use_deepspeed_scheduler = False
if (
hasattr(accelerator.state, "deepspeed_plugin")
and accelerator.state.deepspeed_plugin is not None
):
offload_param = accelerator.state.deepspeed_plugin.deepspeed_config[
"zero_optimization"
]["offload_param"]
accelerator.state.deepspeed_plugin.deepspeed_config["zero_optimization"][
"offload_param"
]["pin_memory"] = False
if offload_param["device"] == "nvme":
if offload_param["nvme_path"] == "none":
if args.offload_param_path is None:
raise ValueError(
f"DeepSpeed is using {offload_param['device']} but nvme_path is not specified."
)
else:
accelerator.state.deepspeed_plugin.deepspeed_config[
"zero_optimization"
]["offload_param"]["nvme_path"] = args.offload_param_path
logger.info(
f"Using DeepSpeed NVMe offload at {accelerator.state.deepspeed_plugin.deepspeed_config['zero_optimization']['offload_param']['nvme_path']}."
)
use_deepspeed_optimizer = True
if "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config:
accelerator.state.deepspeed_plugin.deepspeed_config["optimizer"] = {
"type": "AdamW",
"params": {
"lr": args.learning_rate,
"betas": [args.adam_beta1, args.adam_beta2],
"eps": args.adam_epsilon,
"weight_decay": args.adam_weight_decay,
},
}
use_deepspeed_scheduler = True
if "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config:
accelerator.state.deepspeed_plugin.deepspeed_config["scheduler"] = {
"type": "WarmupLR",
"params": {
"warmup_min_lr": 0,
"warmup_max_lr": args.learning_rate,
"warmup_num_steps": args.lr_warmup_steps,
},
}
# Initialize the optimizer
if use_deepspeed_optimizer:
logger.info("Using DeepSpeed optimizer.")
optimizer_class = accelerate.utils.DummyOptim
extra_optimizer_args["lr"] = args.learning_rate
extra_optimizer_args["betas"] = (args.adam_beta1, args.adam_beta2)
extra_optimizer_args["eps"] = args.adam_epsilon
extra_optimizer_args["weight_decay"] = args.adam_weight_decay
elif args.use_prodigy_optimizer:
logger.info("Using Prodigy optimizer. Experimental.")
try:
import prodigyopt
except ImportError:
raise ImportError(
"To use Prodigy, please install the prodigyopt library: `pip install prodigyopt`"
)
optimizer_class = prodigyopt.Prodigy
if args.learning_rate <= 0.1:
logger.warn(
"Learning rate is too low. When using prodigy, it's generally better to set learning rate around 1.0"
)
extra_optimizer_args["lr"] = args.learning_rate
extra_optimizer_args["betas"] = (args.adam_beta1, args.adam_beta2)
extra_optimizer_args["beta3"] = args.prodigy_beta3
extra_optimizer_args["weight_decay"] = args.prodigy_weight_decay
extra_optimizer_args["eps"] = args.prodigy_epsilon
extra_optimizer_args["decouple"] = args.prodigy_decouple
extra_optimizer_args["use_bias_correction"] = args.prodigy_use_bias_correction
extra_optimizer_args["safeguard_warmup"] = args.prodigy_safeguard_warmup
extra_optimizer_args["d_coef"] = args.prodigy_learning_rate
elif args.adam_bfloat16:
logger.info("Using bf16 AdamW optimizer with stochastic rounding.")
from helpers.training import adam_bfloat16
optimizer_class = adam_bfloat16.AdamWBF16
extra_optimizer_args["betas"] = (args.adam_beta1, args.adam_beta2)
extra_optimizer_args["lr"] = args.learning_rate
elif args.use_8bit_adam:
logger.info("Using 8bit AdamW optimizer.")
try:
import bitsandbytes as bnb # type: ignore
except ImportError:
raise ImportError(
"Please install bitsandbytes to use 8-bit Adam. You can do so by running `pip install bitsandbytes`"
)
optimizer_class = bnb.optim.AdamW8bit
extra_optimizer_args["betas"] = (args.adam_beta1, args.adam_beta2)
extra_optimizer_args["lr"] = args.learning_rate
elif hasattr(args, "use_dadapt_optimizer") and args.use_dadapt_optimizer:
logger.info("Using D-Adaptation optimizer.")
try:
from dadaptation import DAdaptAdam
except ImportError:
raise ImportError(
"Please install the dadaptation library to make use of DaDapt optimizer."
"You can do so by running `pip install dadaptation`"
)
optimizer_class = DAdaptAdam
if (
hasattr(args, "dadaptation_learning_rate")
and args.dadaptation_learning_rate is not None
):
logger.debug(
f"Overriding learning rate {args.learning_rate} with {args.dadaptation_learning_rate} for D-Adaptation optimizer."
)
args.learning_rate = args.dadaptation_learning_rate
extra_optimizer_args["decouple"] = True
extra_optimizer_args["betas"] = (args.adam_beta1, args.adam_beta2)
extra_optimizer_args["lr"] = args.learning_rate
elif hasattr(args, "use_adafactor_optimizer") and args.use_adafactor_optimizer:
logger.info("Using Adafactor optimizer.")
try:
from transformers.optimization import Adafactor, AdafactorSchedule
except ImportError:
raise ImportError(
"Please install the latest transformers library to make use of Adafactor optimizer."
"You can do so by running `pip install transformers`, or, `poetry install` from the SimpleTuner directory."
)
optimizer_class = Adafactor
extra_optimizer_args = {}
if args.adafactor_relative_step:
extra_optimizer_args["lr"] = None
extra_optimizer_args["relative_step"] = True
extra_optimizer_args["scale_parameter"] = False
extra_optimizer_args["warmup_init"] = True
else:
extra_optimizer_args["lr"] = args.learning_rate
extra_optimizer_args["relative_step"] = False
extra_optimizer_args["scale_parameter"] = False
extra_optimizer_args["warmup_init"] = False
else:
logger.info("Using AdamW optimizer.")
optimizer_class = torch.optim.AdamW
extra_optimizer_args["betas"] = (args.adam_beta1, args.adam_beta2)
extra_optimizer_args["lr"] = args.learning_rate
if args.model_type == "full":
if args.controlnet:
params_to_optimize = controlnet.parameters()
elif unet is not None:
params_to_optimize = list(
filter(lambda p: p.requires_grad, unet.parameters())
)
elif transformer is not None:
params_to_optimize = list(
filter(lambda p: p.requires_grad, transformer.parameters())
)
if args.train_text_encoder:
raise ValueError(
"Full model tuning does not currently support text encoder training."
)
elif "lora" in args.model_type:
if args.controlnet:
raise ValueError(
"SimpleTuner does not currently support training a ControlNet LoRA."
)
if unet is not None:
params_to_optimize = list(
filter(lambda p: p.requires_grad, unet.parameters())
)
if transformer is not None:
params_to_optimize = list(
filter(lambda p: p.requires_grad, transformer.parameters())
)
if args.train_text_encoder:
if args.sd3:
raise ValueError(
"Stable Diffusion 3 does not support finetuning the text encoders, as it is a multimodal transformer model that does not benefit from it."
)