Fine-Tuning Stable Diffusion with LoRA (Workaround for ‘Unscale FP16 Gradients’ Error)
I am writing this article at the end of March 2024, more than a year since this article was published on Hugging Face and several months since Julien Simon released this video explaining how to fine-tune Stable Diffusion for less than $1 using AWS EC2 spot instances.
First of all, here is the official page that you should refer to.
Unfortunately, it is very likely that you will encounter the “Attempting to unscale FP16 gradients.” error. This error has been reported by multiple users here. If it’s your case, here’s how to fix your problem.
Here is the accelerate command to start the fine-tuning:
export MODEL_NAME="CompVis/stable-diffusion-v1-4"
export DATASET_NAME="lambdalabs/pokemon-blip-captions"
accelerate launch --mixed_precision="fp16" --multi_gpu train_text_to_image.py \
--pretrained_model_name_or_path=$MODEL_NAME \
--dataset_name=$DATASET_NAME \
--use_ema \
--resolution=512 --center_crop --random_flip \
--train_batch_size=1 \
--gradient_accumulation_steps=4 \
--gradient_checkpointing \
--max_train_steps=15000 \
--learning_rate=1e-05 \
--max_grad_norm=1 \
--lr_scheduler="constant" --lr_warmup_steps=0 \
--output_dir="sd-pokemon-model"The argument --mixed_precision="fp16" is missing in the train_text_to_image_lora.py script for it to work properly. This will also solve the error with the sdxl script.
Here is the working accelerate command:
export MODEL_NAME="CompVis/stable-diffusion-v1-4"
export DATASET_NAME="lambdalabs/pokemon-blip-captions"
accelerate launch --mixed_precision="fp16" --multi_gpu train_text_to_image.py \
--mixed_precision="fp16" \
--pretrained_model_name_or_path=$MODEL_NAME \
--dataset_name=$DATASET_NAME \
--use_ema \
--resolution=512 --center_crop --random_flip \
--train_batch_size=1 \
--gradient_accumulation_steps=4 \
--gradient_checkpointing \
--max_train_steps=15000 \
--learning_rate=1e-05 \
--max_grad_norm=1 \
--lr_scheduler="constant" --lr_warmup_steps=0 \
--output_dir="sd-pokemon-model"This solution was mentioned initially in this comment.





