-
Notifications
You must be signed in to change notification settings - Fork 188
/
trainer.py
2743 lines (2577 loc) · 129 KB
/
trainer.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
import huggingface_hub
from helpers.training.default_settings.safety_check import safety_check
from helpers.publishing.huggingface import HubManager
from configure import model_labels
import shutil
import hashlib
import json
import copy
import random
import logging
import math
import os
import sys
import glob
import wandb
# Quiet down, you.
os.environ["ACCELERATE_LOG_LEVEL"] = "WARNING"
from helpers import log_format # noqa
from helpers.configuration.loader import load_config
from helpers.caching.memory import reclaim_memory
from helpers.training.validation import Validation, prepare_validation_prompt_list
from helpers.training.state_tracker import StateTracker
from helpers.training.schedulers import load_scheduler_from_args
from helpers.training.custom_schedule import get_lr_scheduler
from helpers.training.optimizer_param import is_lr_scheduler_disabled
from helpers.training.adapter import determine_adapter_target_modules, load_lora_weights
from helpers.training.diffusion_model import load_diffusion_model
from helpers.training.text_encoding import (
load_tes,
determine_te_path_subfolder,
import_model_class_from_model_name_or_path,
get_tokenizers,
)
from helpers.training.optimizer_param import (
determine_optimizer_class_with_config,
determine_params_to_optimize,
)
from helpers.data_backend.factory import BatchFetcher
from helpers.training.deepspeed import (
deepspeed_zero_init_disabled_context_manager,
prepare_model_for_deepspeed,
)
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 import steps_remaining_in_epoch
from helpers.training.custom_schedule import (
generate_timestep_weights,
segmented_timestep_selection,
)
from helpers.training.min_snr_gamma import compute_snr
from accelerate.logging import get_logger
from diffusers.models.embeddings import get_2d_rotary_pos_embed
from helpers.models.smoldit import get_resize_crop_region_for_grid
logger = get_logger(
"SimpleTuner", 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 torch
import diffusers
import accelerate
import transformers
import torch.nn.functional as F
import torch.utils.checkpoint
from accelerate import Accelerator
from accelerate.utils import set_seed
from configure import model_classes
try:
from lycoris import LycorisNetwork
except:
print("[ERROR] Lycoris not available. Please install ")
from tqdm.auto import tqdm
from transformers import PretrainedConfig, CLIPTokenizer
from helpers.sdxl.pipeline import StableDiffusionXLPipeline
from diffusers import StableDiffusion3Pipeline
from diffusers import (
AutoencoderKL,
ControlNetModel,
DDIMScheduler,
DDPMScheduler,
UNet2DConditionModel,
FluxTransformer2DModel,
PixArtTransformer2DModel,
EulerDiscreteScheduler,
EulerAncestralDiscreteScheduler,
UniPCMultistepScheduler,
)
from peft import LoraConfig
from peft.utils import get_peft_model_state_dict
from helpers.training.ema 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
from helpers.models.flux import (
prepare_latent_image_ids,
pack_latents,
unpack_latents,
get_mobius_guidance,
apply_flux_schedule_shift,
)
is_optimi_available = False
try:
from optimi import prepare_for_gradient_release
is_optimi_available = True
except:
pass
# 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,
}
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO,
)
transformers.utils.logging.set_verbosity_warning()
diffusers.utils.logging.set_verbosity_warning()
class Trainer:
def __init__(self, config: dict = None):
self.parse_arguments(args=config)
self._misc_init()
self.controlnet = None
self.lycoris_wrapped_network = None
self.lycoris_config = None
self.lr_scheduler = None
def _config_to_obj(self, config):
if not config:
return None
return type("Config", (object,), config)
def parse_arguments(self, args=None):
self.config = load_config(args)
report_to = (
None if self.config.report_to.lower() == "none" else self.config.report_to
)
self.accelerator = Accelerator(
gradient_accumulation_steps=self.config.gradient_accumulation_steps,
mixed_precision=(
self.config.mixed_precision
if not torch.backends.mps.is_available()
else None
),
log_with=report_to,
project_config=self.config.accelerator_project_config,
kwargs_handlers=[self.config.process_group_kwargs],
)
safety_check(args=self.config, accelerator=self.accelerator)
if self.config.lr_scale:
logger.info(
f"Scaling learning rate ({self.config.learning_rate}), due to --lr_scale"
)
self.config.learning_rate = (
self.config.learning_rate
* self.config.gradient_accumulation_steps
* self.config.train_batch_size
* self.accelerator.num_processes
)
StateTracker.set_accelerator(self.accelerator)
StateTracker.set_args(self.config)
StateTracker.set_weight_dtype(self.config.weight_dtype)
self.set_model_family()
# this updates self.config further, so we will run it here.
self.init_noise_schedule()
def init_noise_schedule(self):
self.config, _flow_matching, self.noise_scheduler = load_scheduler_from_args(
self.config
)
self.config.flow_matching = _flow_matching
self.lr = 0.0
def configure_webhook(self, send_startup_message: bool = True):
self.webhook_handler = None
if self.config.webhook_config is None:
return
from helpers.webhooks.handler import WebhookHandler
self.webhook_handler = WebhookHandler(
self.config.webhook_config,
self.accelerator,
f"{self.config.tracker_project_name} {self.config.tracker_run_name}",
)
StateTracker.set_webhook_handler(self.webhook_handler)
if send_startup_message:
self.webhook_handler.send(
message="SimpleTuner has launched. Hold onto your butts!",
store_response=True,
)
def _misc_init(self):
"""things that do not really need an order."""
torch.set_num_threads(self.config.torch_num_threads)
self.state = {}
self.state["lr"] = 0.0
# Global step represents the most recently *completed* optimization step, which means it
# takes into account the number of gradient_accumulation_steps. If we use 1 gradient_accumulation_step,
# then global_step and step will be the same throughout training. However, if we use
# 2 gradient_accumulation_steps, then global_step will be twice as large as step, and so on.
self.state["global_step"] = 0
self.state["global_resume_step"] = 0
self.state["first_epoch"] = 1
self.timesteps_buffer = []
self.guidance_values_list = []
self.train_loss = 0.0
self.bf = None
self.grad_norm = None
self.extra_lr_scheduler_kwargs = {}
StateTracker.set_global_step(self.state["global_step"])
self.config.use_deepspeed_optimizer, self.config.use_deepspeed_scheduler = (
prepare_model_for_deepspeed(self.accelerator, self.config)
)
def set_model_family(self, model_family: str = None):
model_family = getattr(self.config, "model_family", model_family)
if not model_family:
logger.warning(
"Using --model_family (or MODEL_FAMILY) to specify which model you are training will be required in a future release."
)
if self.config.model_family == "sd3":
model_family = "sd3"
logger.warning(
"Using --sd3 is deprecated. Please use --model_family=sd3."
)
if self.config.model_family == "flux":
model_family = "flux"
logger.warning(
"Using --flux is deprecated. Please use --model_family=flux."
)
if self.config.model_family == "pixart_sigma":
model_family = "pixart_sigma"
logger.warning(
"Using --pixart_sigma is deprecated. Please use --model_family=pixart_sigma."
)
if self.config.model_family == "legacy":
model_family = "legacy"
logger.warning(
"Using --legacy is deprecated. Please use --model_family=legacy."
)
if self.config.model_family == "kolors":
model_family = "kolors"
logger.warning(
"Using --kolors is deprecated. Please use --model_family=kolors."
)
if self.config.model_family == "smoldit":
model_family = "smoldit"
if model_family is None:
model_family = "sdxl"
logger.warning(
"Training SDXL without specifying --model_family is deprecated. Please use --model_family=sdxl."
)
elif model_family not in model_classes["full"]:
raise ValueError(f"Invalid model family specified: {model_family}")
print(f"Model family: {model_family}")
self._set_model_paths()
StateTracker.set_model_family(model_family)
self.config.model_type_label = model_labels[model_family.lower()]
if StateTracker.is_sdxl_refiner():
self.config.model_type_label = "SDXL Refiner"
def init_clear_backend_cache(self):
if self.config.output_dir is not None:
os.makedirs(self.config.output_dir, exist_ok=True)
if self.config.preserve_data_backend_cache:
return
StateTracker.delete_cache_files(
preserve_data_backend_cache=self.config.preserve_data_backend_cache
)
def init_seed(self):
if self.config.seed is not None and self.config.seed != 0:
set_seed(self.config.seed, self.config.seed_for_each_device)
def init_huggingface_hub(self, access_token: str = None):
# Handle the repository creation
self.hub_manager = None
if not self.accelerator.is_main_process or not self.config.push_to_hub:
return
if access_token:
huggingface_hub.login(token=access_token)
self.hub_manager = HubManager(config=self.config)
try:
StateTracker.set_hf_user(huggingface_hub.whoami())
logger.info(
f"Logged into Hugging Face Hub as '{StateTracker.get_hf_username()}'"
)
except Exception as e:
logger.error(f"Failed to log into Hugging Face Hub: {e}")
raise e
def _set_model_paths(self):
self.config.vae_path = (
self.config.pretrained_model_name_or_path
if self.config.pretrained_vae_model_name_or_path is None
else self.config.pretrained_vae_model_name_or_path
)
self.config.text_encoder_path, self.config.text_encoder_subfolder = (
determine_te_path_subfolder(self.config)
)
def init_preprocessing_models(self):
# image embeddings
self.init_vae()
# text embeds
self.init_text_encoder()
def init_vae(self):
logger.info(f"Load VAE: {self.config.vae_path}")
self.config.vae_kwargs = {
"pretrained_model_name_or_path": self.config.vae_path,
"subfolder": "vae",
"revision": self.config.revision,
"force_upcast": False,
"variant": self.config.variant,
}
try:
self.vae = AutoencoderKL.from_pretrained(**self.config.vae_kwargs)
except:
logger.warning(
"Couldn't load VAE with default path. Trying without a subfolder.."
)
self.config.vae_kwargs["subfolder"] = None
self.vae = AutoencoderKL.from_pretrained(**self.config.vae_kwargs)
if self.vae is not None:
# The VAE is in bfloat16 to avoid NaN losses.
_vae_dtype = torch.bfloat16
if hasattr(self.config, "vae_dtype"):
# Let's use a case-switch for convenience: bf16, fp16, fp32, none/default
if self.config.vae_dtype == "bf16":
_vae_dtype = torch.bfloat16
elif self.config.vae_dtype == "fp16":
raise ValueError(
"fp16 is not supported for SDXL's VAE. Please use bf16 or fp32."
)
elif self.config.vae_dtype == "fp32":
_vae_dtype = torch.float32
elif (
self.config.vae_dtype == "none"
or self.config.vae_dtype == "default"
):
_vae_dtype = torch.bfloat16
logger.info(
f"Loading VAE onto accelerator, converting from {self.vae.dtype} to {_vae_dtype}"
)
self.vae.to(self.accelerator.device, dtype=_vae_dtype)
StateTracker.set_vae_dtype(_vae_dtype)
StateTracker.set_vae(self.vae)
def init_text_tokenizer(self):
logger.info("Load tokenizers")
self.tokenizer_1, self.tokenizer_2, self.tokenizer_3 = get_tokenizers(
self.config
)
self.tokenizers = [self.tokenizer_1, self.tokenizer_2, self.tokenizer_3]
def init_text_encoder(self):
self.init_text_tokenizer()
self.text_encoder_1, self.text_encoder_2, self.text_encoder_3 = None, None, None
self.text_encoder_cls_1, self.text_encoder_cls_2, self.text_encoder_cls_3 = (
None,
None,
None,
)
if self.tokenizer_1 is not None:
self.text_encoder_cls_1 = import_model_class_from_model_name_or_path(
self.config.text_encoder_path,
self.config.revision,
self.config,
subfolder=self.config.text_encoder_subfolder,
)
if self.tokenizer_2 is not None:
self.text_encoder_cls_2 = import_model_class_from_model_name_or_path(
self.config.pretrained_model_name_or_path,
self.config.revision,
self.config,
subfolder="text_encoder_2",
)
if self.tokenizer_3 is not None and self.config.model_family == "sd3":
self.text_encoder_cls_3 = import_model_class_from_model_name_or_path(
self.config.pretrained_model_name_or_path,
self.config.revision,
self.config,
subfolder="text_encoder_3",
)
with ContextManagers(deepspeed_zero_init_disabled_context_manager()):
tokenizers = [self.tokenizer_1, self.tokenizer_2, self.tokenizer_3]
text_encoder_classes = [
self.text_encoder_cls_1,
self.text_encoder_cls_2,
self.text_encoder_cls_3,
]
(
text_encoder_variant,
self.text_encoder_1,
self.text_encoder_2,
self.text_encoder_3,
) = load_tes(
args=self.config,
text_encoder_classes=text_encoder_classes,
weight_dtype=self.config.weight_dtype,
tokenizers=tokenizers,
text_encoder_path=self.config.text_encoder_path,
text_encoder_subfolder=self.config.text_encoder_subfolder,
)
self.text_encoders = []
self.tokenizers = []
if self.tokenizer_1 is not None:
logger.info("Moving text encoder to GPU.")
self.text_encoder_1.to(
self.accelerator.device, dtype=self.config.weight_dtype
)
self.tokenizers.append(self.tokenizer_1)
self.text_encoders.append(self.text_encoder_1)
if self.tokenizer_2 is not None:
logger.info("Moving text encoder 2 to GPU.")
self.text_encoder_2.to(
self.accelerator.device, dtype=self.config.weight_dtype
)
self.tokenizers.append(self.tokenizer_2)
self.text_encoders.append(self.text_encoder_2)
if self.tokenizer_3 is not None:
logger.info("Moving text encoder 3 to GPU.")
self.text_encoder_3.to(
self.accelerator.device, dtype=self.config.weight_dtype
)
self.tokenizers.append(self.tokenizer_3)
self.text_encoders.append(self.text_encoder_3)
def init_freeze_models(self):
# Freeze vae and text_encoders
if self.vae is not None:
self.vae.requires_grad_(False)
if self.text_encoder_1 is not None:
self.text_encoder_1.requires_grad_(False)
if self.text_encoder_2 is not None:
self.text_encoder_2.requires_grad_(False)
if self.text_encoder_3 is not None:
self.text_encoder_3.requires_grad_(False)
if "lora" in self.config.model_type or self.config.controlnet:
if self.transformer is not None:
self.transformer.requires_grad_(False)
if self.unet is not None:
self.unet.requires_grad_(False)
self.accelerator.wait_for_everyone()
def init_load_base_model(self):
if self.webhook_handler is not None:
self.webhook_handler.send(
message=f"Loading model: `{self.config.pretrained_model_name_or_path}`..."
)
self.unet, self.transformer = load_diffusion_model(
self.config, self.config.weight_dtype
)
self.accelerator.wait_for_everyone()
def init_data_backend(self):
try:
self.init_clear_backend_cache()
if self.webhook_handler is not None:
self.webhook_handler.send(
message="Configuring data backends... (this may take a while!)"
)
configure_multi_databackend(
self.config,
accelerator=self.accelerator,
text_encoders=self.text_encoders,
tokenizers=self.tokenizers,
)
except Exception as e:
import traceback
logger.error(f"{e}, traceback: {traceback.format_exc()}")
if self.webhook_handler is not None:
self.webhook_handler.send(
message=f"Failed to load data backends: {e}",
message_level="critical",
)
return False
self.init_validation_prompts()
# 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 self.config.push_to_hub and self.accelerator.is_main_process:
self.hub_manager.collected_data_backend_str = collected_data_backend_str
self.hub_manager.set_validation_prompts(
self.validation_prompts, self.validation_shortnames
)
logger.debug(f"Collected validation prompts: {self.validation_prompts}")
self._recalculate_training_steps()
logger.info(
f"Collected the following data backends: {collected_data_backend_str}"
)
if self.webhook_handler is not None:
self.webhook_handler.send(
message=f"Collected the following data backends: {collected_data_backend_str}"
)
self.accelerator.wait_for_everyone()
def init_validation_prompts(self):
if self.accelerator.is_main_process:
if self.config.model_family == "flux":
(
self.validation_prompts,
self.validation_shortnames,
self.validation_negative_prompt_embeds,
self.validation_negative_pooled_embeds,
self.validation_negative_time_ids,
) = prepare_validation_prompt_list(
args=self.config,
embed_cache=StateTracker.get_default_text_embed_cache(),
)
else:
(
self.validation_prompts,
self.validation_shortnames,
self.validation_negative_prompt_embeds,
self.validation_negative_pooled_embeds,
) = prepare_validation_prompt_list(
args=self.config,
embed_cache=StateTracker.get_default_text_embed_cache(),
)
else:
self.validation_prompts = None
self.validation_shortnames = None
self.validation_negative_prompt_embeds = None
self.validation_negative_pooled_embeds = None
self.accelerator.wait_for_everyone()
def stats_memory_used(self):
# Grab GPU memory used:
if torch.cuda.is_available():
curent_memory_allocated = torch.cuda.memory_allocated() / 1024**3
elif torch.backends.mps.is_available():
curent_memory_allocated = torch.mps.current_allocated_memory() / 1024**3
else:
logger.warning(
"CUDA, ROCm, or Apple MPS not detected here. We cannot report VRAM reductions."
)
curent_memory_allocated = 0
return curent_memory_allocated
def init_unload_text_encoder(self):
if self.config.model_type != "full" and self.config.train_text_encoder:
return
memory_before_unload = self.stats_memory_used()
if self.accelerator.is_main_process:
logger.info("Unloading text encoders, as they are not being trained.")
if self.text_encoder_1 is not None:
self.text_encoder_1 = self.text_encoder_1.to("cpu")
if self.text_encoder_2 is not None:
self.text_encoder_2 = self.text_encoder_2.to("cpu")
if self.text_encoder_3 is not None:
self.text_encoder_3 = self.text_encoder_3.to("cpu")
del self.text_encoder_1, self.text_encoder_2, self.text_encoder_3
self.text_encoder_1, self.text_encoder_2, self.text_encoder_3 = None, None, None
self.text_encoders = []
for backend_id, backend in StateTracker.get_data_backends().items():
if "text_embed_cache" in backend:
backend["text_embed_cache"].text_encoders = None
backend["text_embed_cache"].pipeline = None
reclaim_memory()
memory_after_unload = self.stats_memory_used()
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."
)
def init_precision(self):
self.config.enable_adamw_bf16 = (
True if self.config.weight_dtype == torch.bfloat16 else False
)
self.config.base_weight_dtype = self.config.weight_dtype
self.config.is_quanto = False
if not self.config.disable_accelerator and self.config.is_quantized:
if self.config.base_model_default_dtype == "fp32":
self.config.base_weight_dtype = torch.float32
self.config.enable_adamw_bf16 = False
elif self.config.base_model_default_dtype == "bf16":
self.config.base_weight_dtype = torch.bfloat16
self.config.enable_adamw_bf16 = True
if (
self.unet is not None
and self.unet.dtype != self.config.base_weight_dtype
):
logger.info(
f"Moving U-net from {self.unet.dtype} to {self.config.base_weight_dtype} precision"
)
self.unet.to("cpu", dtype=self.config.base_weight_dtype)
elif (
self.transformer is not None
and self.transformer.dtype != self.config.base_weight_dtype
):
logger.info(
f"Moving transformer from {self.transformer.dtype} to {self.config.base_weight_dtype} precision"
)
self.transformer.to("cpu", dtype=self.config.base_weight_dtype)
else:
logger.info(
f"Keeping some base model weights in {self.config.base_weight_dtype}."
)
if (
"quanto" in self.config.base_model_precision
and "lora" in self.config.model_type
):
self.config.is_quanto = True
from helpers.training.quantisation import quantoise
self.quantoise = quantoise
# we'll quantise pretty much everything but the adapter, if we execute this here.
if not self.config.controlnet:
with self.accelerator.local_main_process_first():
quantoise(
unet=self.unet,
transformer=self.transformer,
text_encoder_1=self.text_encoder_1,
text_encoder_2=self.text_encoder_2,
text_encoder_3=self.text_encoder_3,
controlnet=None,
args=self.config,
)
def init_controlnet_model(self):
if not self.config.controlnet:
return
logger.info("Creating the controlnet..")
if self.config.controlnet_model_name_or_path:
logger.info("Loading existing controlnet weights")
controlnet = ControlNetModel.from_pretrained(
self.config.controlnet_model_name_or_path
)
else:
logger.info("Initializing controlnet weights from unet")
controlnet = ControlNetModel.from_unet(self.unet)
if "quanto" in self.config.base_model_precision:
# since controlnet training uses no adapter currently, we just quantise the base transformer here.
with self.accelerator.local_main_process_first():
self.quantoise(
unet=self.unet,
transformer=self.transformer,
text_encoder_1=self.text_encoder_1,
text_encoder_2=self.text_encoder_2,
text_encoder_3=self.text_encoder_3,
controlnet=None,
args=self.config,
)
self.accelerator.wait_for_everyone()
def init_trainable_peft_adapter(self):
if "lora" not in self.config.model_type:
return
if self.config.controlnet:
raise ValueError("Cannot train LoRA with ControlNet.")
if "standard" == self.config.lora_type.lower():
logger.info(f"Using LoRA training mode (rank={self.config.lora_rank})")
if self.webhook_handler is not None:
self.webhook_handler.send(message="Using LoRA training mode.")
target_modules = determine_adapter_target_modules(
self.config, self.unet, self.transformer
)
addkeys, misskeys = [], []
if self.unet is not None:
unet_lora_config = LoraConfig(
r=self.config.lora_rank,
lora_alpha=(
self.config.lora_alpha
if self.config.lora_alpha is not None
else self.config.lora_rank
),
lora_dropout=self.config.lora_dropout,
init_lora_weights=self.config.lora_initialisation_style,
target_modules=target_modules,
use_dora=self.config.use_dora,
)
logger.info("Adding LoRA adapter to the unet model..")
self.unet.add_adapter(unet_lora_config)
if self.config.init_lora:
addkeys, misskeys = load_lora_weights(
{"unet": self.unet},
self.config.init_lora,
use_dora=self.config.use_dora,
)
elif self.transformer is not None:
transformer_lora_config = LoraConfig(
r=self.config.lora_rank,
lora_alpha=(
self.config.lora_alpha
if self.config.lora_alpha is not None
else self.config.lora_rank
),
init_lora_weights=self.config.lora_initialisation_style,
target_modules=target_modules,
use_dora=self.config.use_dora,
)
self.transformer.add_adapter(transformer_lora_config)
if self.config.init_lora:
addkeys, misskeys = load_lora_weights(
{"transformer": self.transformer},
self.config.init_lora,
use_dora=self.config.use_dora,
)
if addkeys:
logger.warning(
"The following keys were found in %s, but are not part of the model and are ignored:\n %s.\nThis is most likely an error"
% (self.config.init_lora, str(addkeys))
)
if misskeys:
logger.warning(
"The following keys were part of the model but not found in %s:\n %s.\nThese keys will be initialized according to the lora weight initialisation. This could be an error, or intended behaviour in case a lora is finetuned with additional keys."
% (self.config.init_lora, str(misskeys))
)
elif "lycoris" == self.config.lora_type.lower():
from lycoris import create_lycoris
with open(self.config.lycoris_config, "r") as f:
self.lycoris_config = json.load(f)
multiplier = int(self.lycoris_config["multiplier"])
linear_dim = int(self.lycoris_config["linear_dim"])
linear_alpha = int(self.lycoris_config["linear_alpha"])
apply_preset = self.lycoris_config.get("apply_preset", None)
if apply_preset is not None and apply_preset != {}:
LycorisNetwork.apply_preset(apply_preset)
# Remove the positional arguments we extracted.
del self.lycoris_config["multiplier"]
del self.lycoris_config["linear_dim"]
del self.lycoris_config["linear_alpha"]
logger.info(f"Using lycoris training mode")
if self.webhook_handler is not None:
self.webhook_handler.send(message="Using lycoris training mode.")
model_for_lycoris_wrap = None
if self.transformer is not None:
model_for_lycoris_wrap = self.transformer
if self.unet is not None:
model_for_lycoris_wrap = self.unet
if self.config.init_lora is not None:
from lycoris import create_lycoris_from_weights
self.lycoris_wrapped_network = create_lycoris_from_weights(
multiplier,
self.config.init_lora,
model_for_lycoris_wrap,
weights_sd=None,
**self.lycoris_config,
)[0]
else:
self.lycoris_wrapped_network = create_lycoris(
model_for_lycoris_wrap,
multiplier,
linear_dim,
linear_alpha,
**self.lycoris_config,
)
self.lycoris_wrapped_network.apply_to()
setattr(
self.accelerator,
"_lycoris_wrapped_network",
self.lycoris_wrapped_network,
)
lycoris_num_params = sum(
p.numel() for p in self.lycoris_wrapped_network.parameters()
)
logger.info(
f"LyCORIS network has been initialized with {lycoris_num_params:,} parameters"
)
self.accelerator.wait_for_everyone()
def init_post_load_freeze(self):
if self.config.layer_freeze_strategy == "bitfit":
from helpers.training.model_freeze import apply_bitfit_freezing
if self.unet is not None:
logger.info("Applying BitFit freezing strategy to the U-net.")
self.unet = apply_bitfit_freezing(self.unet, self.config)
if self.transformer is not None:
logger.warning(
"Training DiT models with BitFit is not yet tested, and unexpected results may occur."
)
self.transformer = apply_bitfit_freezing(self.transformer, self.config)
if self.config.gradient_checkpointing:
if self.unet is not None:
self.unet.enable_gradient_checkpointing()
if self.transformer is not None and self.config.model_family != "smoldit":
self.transformer.enable_gradient_checkpointing()
if self.config.controlnet:
self.controlnet.enable_gradient_checkpointing()
if (
hasattr(self.config, "train_text_encoder")
and self.config.train_text_encoder
):
self.text_encoder_1.gradient_checkpointing_enable()
self.text_encoder_2.gradient_checkpointing_enable()
def _recalculate_training_steps(self):
# Scheduler and math around the number of training steps.
if not hasattr(self.config, "overrode_max_train_steps"):
self.config.overrode_max_train_steps = False
self.config.total_num_batches = sum(
[
len(
backend["metadata_backend"] if "metadata_backend" in backend else []
)
for _, backend in StateTracker.get_data_backends().items()
]
)
self.config.num_update_steps_per_epoch = math.ceil(
self.config.total_num_batches / self.config.gradient_accumulation_steps
)
if getattr(self.config, "overrode_max_train_steps", False):
self.config.max_train_steps = (
self.config.num_train_epochs * self.config.num_update_steps_per_epoch
)
# Afterwards we recalculate our number of training epochs
self.config.num_train_epochs = math.ceil(
self.config.max_train_steps / self.config.num_update_steps_per_epoch
)
logger.info(
"After removing any undesired samples and updating cache entries, we have settled on"
f" {self.config.num_train_epochs} epochs and {self.config.num_update_steps_per_epoch} steps per epoch."
)
if self.config.max_train_steps is None or self.config.max_train_steps == 0:
if (
self.config.num_train_epochs is None
or self.config.num_train_epochs == 0
):
raise ValueError(
"You must specify either --max_train_steps or --num_train_epochs with a value > 0"
)
self.config.max_train_steps = (
self.config.num_train_epochs * self.config.num_update_steps_per_epoch
)
logger.info(
f"Calculated our maximum training steps at {self.config.max_train_steps} because we have"
f" {self.config.num_train_epochs} epochs and {self.config.num_update_steps_per_epoch} steps per epoch."
)
self.config.overrode_max_train_steps = True
elif self.config.num_train_epochs is None or self.config.num_train_epochs == 0:
if self.config.max_train_steps is None or self.config.max_train_steps == 0:
raise ValueError(
"You must specify either --max_train_steps or --num_train_epochs with a value > 0"
)
self.config.num_train_epochs = math.ceil(
self.config.max_train_steps / self.config.num_update_steps_per_epoch
)
logger.info(
f"Calculated our maximum training steps at {self.config.max_train_steps} because we have"
f" {self.config.num_train_epochs} epochs and {self.config.num_update_steps_per_epoch} steps per epoch."
)
if self.lr_scheduler is not None and hasattr(
self.lr_scheduler, "num_update_steps_per_epoch"
):
self.lr_scheduler.num_update_steps_per_epoch = (
self.config.num_update_steps_per_epoch
)
self.config.total_batch_size = (
self.config.train_batch_size
* self.accelerator.num_processes
* self.config.gradient_accumulation_steps
)
def init_optimizer(self):
logger.info(f"Learning rate: {self.config.learning_rate}")
extra_optimizer_args = {"lr": self.config.learning_rate}
# Initialize the optimizer
optimizer_args_from_config, optimizer_class = (
determine_optimizer_class_with_config(
args=self.config,
use_deepspeed_optimizer=self.config.use_deepspeed_optimizer,
is_quantized=self.config.is_quantized,
enable_adamw_bf16=self.config.enable_adamw_bf16,
)
)
extra_optimizer_args.update(optimizer_args_from_config)
self.params_to_optimize = determine_params_to_optimize(
args=self.config,
controlnet=self.controlnet,
unet=self.unet,
transformer=self.transformer,
text_encoder_1=self.text_encoder_1,
text_encoder_2=self.text_encoder_2,
model_type_label=self.config.model_type_label,
lycoris_wrapped_network=self.lycoris_wrapped_network,
)
if self.config.use_deepspeed_optimizer:
optimizer = optimizer_class(self.params_to_optimize)
else:
logger.info(
f"Optimizer arguments, weight_decay={self.config.adam_weight_decay} eps={self.config.adam_epsilon}, extra_arguments={extra_optimizer_args}"
)
if self.config.train_text_encoder and self.config.text_encoder_lr:
# changes the learning rate of text_encoder_parameters_one and text_encoder_parameters_two to be
# --learning_rate
self.params_to_optimize[1]["lr"] = float(self.config.learning_rate)
if self.text_encoder_2 is not None:
self.params_to_optimize[2]["lr"] = float(self.config.learning_rate)
self.optimizer = optimizer_class(
self.params_to_optimize,
**extra_optimizer_args,
)
if (
is_optimi_available
and self.config.optimizer_release_gradients
and "optimi" in self.config.optimizer
):
logger.warning(
"Marking model for gradient release. This feature is experimental, and may use more VRAM or not work."
)
prepare_for_gradient_release(
(
self.controlnet
if self.config.controlnet
else self.transformer if self.transformer is not None else self.unet
),
self.optimizer,
)
def init_lr_scheduler(self):
self.config.is_schedulefree = is_lr_scheduler_disabled(self.config.optimizer)
if self.config.is_schedulefree:
logger.info(
"Using experimental AdamW ScheduleFree optimiser from Facebook. Experimental due to newly added Kahan summation."
)
# we don't use LR schedulers with schedulefree optimisers
lr_scheduler = None
if not self.config.use_deepspeed_scheduler and not self.config.is_schedulefree:
logger.info(
f"Loading {self.config.lr_scheduler} learning rate scheduler with {self.config.lr_warmup_steps} warmup steps"
)
lr_scheduler = get_lr_scheduler(
self.config,
self.optimizer,
self.accelerator,
logger,
use_deepspeed_scheduler=False,
)
else:
logger.info(f"Using dummy learning rate scheduler")
if torch.backends.mps.is_available():
lr_scheduler = None
else:
lr_scheduler = accelerate.utils.DummyScheduler(
self.optimizer,
total_num_steps=self.config.max_train_steps,
warmup_num_steps=self.config.lr_warmup_steps,
)
if lr_scheduler is not None:
if hasattr(lr_scheduler, "num_update_steps_per_epoch"):
lr_scheduler.num_update_steps_per_epoch = (
self.config.num_update_steps_per_epoch
)
if hasattr(lr_scheduler, "last_step"):
lr_scheduler.last_step = self.state.get("global_resume_step", 0)