@@ -684,17 +684,22 @@ def collate_fn(examples):
684684 )
685685
686686 # Scheduler and math around the number of training steps.
687- overrode_max_train_steps = False
688- num_update_steps_per_epoch = math . ceil ( len ( train_dataloader ) / args . gradient_accumulation_steps )
687+ # Check the PR https://github.com/huggingface/diffusers/pull/8312 for detailed explanation.
688+ num_warmup_steps_for_scheduler = args . lr_warmup_steps * accelerator . num_processes
689689 if args .max_train_steps is None :
690- args .max_train_steps = args .num_train_epochs * num_update_steps_per_epoch
691- overrode_max_train_steps = True
690+ len_train_dataloader_after_sharding = math .ceil (len (train_dataloader ) / accelerator .num_processes )
691+ num_update_steps_per_epoch = math .ceil (len_train_dataloader_after_sharding / args .gradient_accumulation_steps )
692+ num_training_steps_for_scheduler = (
693+ args .num_train_epochs * accelerator .num_processes * num_update_steps_per_epoch
694+ )
695+ else :
696+ num_training_steps_for_scheduler = args .max_train_steps * accelerator .num_processes
692697
693698 lr_scheduler = get_scheduler (
694699 args .lr_scheduler ,
695700 optimizer = optimizer ,
696- num_warmup_steps = args . lr_warmup_steps * args . gradient_accumulation_steps ,
697- num_training_steps = args . max_train_steps * args . gradient_accumulation_steps ,
701+ num_warmup_steps = num_warmup_steps_for_scheduler ,
702+ num_training_steps = num_training_steps_for_scheduler ,
698703 )
699704 unet , optimizer , train_dataloader , lr_scheduler = accelerator .prepare (
700705 unet , optimizer , train_dataloader , lr_scheduler
@@ -704,8 +709,14 @@ def collate_fn(examples):
704709 vae .to (accelerator .device , dtype = weight_dtype )
705710 # We need to recalculate our total training steps as the size of the training dataloader may have changed.
706711 num_update_steps_per_epoch = math .ceil (len (train_dataloader ) / args .gradient_accumulation_steps )
707- if overrode_max_train_steps :
712+ if args . max_train_steps is None :
708713 args .max_train_steps = args .num_train_epochs * num_update_steps_per_epoch
714+ if num_training_steps_for_scheduler != args .max_train_steps * accelerator .num_processes :
715+ logger .warning (
716+ f"The length of the 'train_dataloader' after 'accelerator.prepare' ({ len (train_dataloader )} ) does not match "
717+ f"the expected length ({ len_train_dataloader_after_sharding } ) when the learning rate scheduler was created. "
718+ f"This inconsistency may result in the learning rate scheduler not functioning properly."
719+ )
709720 # Afterwards we recalculate our number of training epochs
710721 args .num_train_epochs = math .ceil (args .max_train_steps / num_update_steps_per_epoch )
711722
0 commit comments