Fine-Tuning Stable Diffusion with LoRA (Workaround for ‘Unscale FP16 Gradients’ Error)

我是在 2024 年 3 月底写这篇文章的,距离这篇文章在 Hugging Face 上发表已经一年多了,距离 Julien Simon 发布视频解释如何使用 AWS EC2 spot instances 以不到 1 美元的价格微调 Stable Diffusion 也有几个月了。 首先,这里是你应该参考的官方页面。 不幸的是,你很可能会遇到 "Attempting to unscale FP16 gradients. "错误。 这里有多个用户报告过这个错误。 如果你也遇到了这种情况,下面是解决问题的方法。

下面是开始微调的 accelerate 命令:

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"

Resuming from checkpoint checkpoint-35
01/03/2024 21:55:36 - INFO - accelerate.accelerator - Loading states from sd-model-finetuned-lora/checkpoint-35
Loading unet.
01/03/2024 21:55:36 - INFO - peft.tuners.tuners_utils - Already found a peft_config attribute in the model. This will lead to having multiple adapters in the model. Make sure to know what you are doing!
01/03/2024 21:55:38 - INFO - accelerate.checkpointing - All model weights loaded successfully
01/03/2024 21:55:38 - INFO - accelerate.checkpointing - All optimizer states loaded successfully
01/03/2024 21:55:38 - INFO - accelerate.checkpointing - All scheduler states loaded successfully
01/03/2024 21:55:38 - INFO - accelerate.checkpointing - All dataloader sampler states loaded successfully
01/03/2024 21:55:38 - INFO - accelerate.checkpointing - GradScaler state loaded successfully
01/03/2024 21:55:38 - INFO - accelerate.checkpointing - All random states loaded successfully
01/03/2024 21:55:38 - INFO - accelerate.accelerator - Loading in 0 custom states
Steps: 70% 35/50 [00:00<?, ?it/s]Traceback (most recent call last):
File “/content/train_text_to_image_lora_sdxl.py”, line 1261, in
main(args)
File “/content/train_text_to_image_lora_sdxl.py”, line 1077, in main
accelerator.clip_grad_norm_(params_to_optimize, args.max_grad_norm)
File “/usr/local/lib/python3.10/dist-packages/accelerate/accelerator.py”, line 2040, in clip_grad_norm_
self.unscale_gradients()
File “/usr/local/lib/python3.10/dist-packages/accelerate/accelerator.py”, line 2003, in unscale_gradients
self.scaler.unscale_(opt)
File “/usr/local/lib/python3.10/dist-packages/torch/cuda/amp/grad_scaler.py”, line 307, in unscale_
optimizer_state[“found_inf_per_device”] = self.unscale_grads(
File “/usr/local/lib/python3.10/dist-packages/torch/cuda/amp/grad_scaler.py”, line 229, in unscale_grads
raise ValueError(“Attempting to unscale FP16 gradients.”)
ValueError: Attempting to unscale FP16 gradients.

train_text_to_image_lora.py 脚本中缺少参数 --mixed_precision="fp16",因此无法正常工作。 下面是正在运行的 accelerate 命令:

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"
### 解决FP16梯度Unscale问题 当遇到`ValueError: Attempting to unscale FP16 gradients.`错误时,这通常意味着混合精度训练期间出现了不兼容的操作。对于使用Kornia库的情况,可以采取以下措施来解决问题。 #### 调整环境配置 确保在训练过程中正确设置了浮点数精度选项。如果将`fp16`设为True并启用INT8量化,则能够避免此异常情况的发生[^2]。因此,在初始化模型之前,应该确认已经启用了这些参数: ```python import torch torch.cuda.set_per_process_memory_fraction(0.9, device='cuda') model = ModelClass().to('cuda').half() # 使用半精度浮点数(half precision floating point numbers) ``` #### 更新依赖包版本 有时特定版本之间的差异也会引发此类问题。建议安装指定版本的PEFT和其他相关组件以获得更好的稳定性: ```bash pip install peft==0.4.0 pip install kornia==latest_version # 安装最新稳定版Kornia ``` #### 修改训练脚本中的加速器设置 通过调整Accelerate工具启动命令里的参数,也可以有效缓解这一难题。具体来说就是利用`--mixed_precision="fp16"`选项来进行混合精度计算[^3]: ```bash accelerate launch --mixed_precision="fp16" your_training_script.py ... ``` 另外需要注意的是,某些情况下可能是由于CUDA缓存管理不当所引起的。此时可以通过清理设备上的临时数据来释放内存空间,从而绕过潜在冲突: ```python with torch.no_grad(): model.eval() for param in model.parameters(): if hasattr(param.grad, 'data'): del param.grad.data torch.cuda.empty_cache() ``` 以上方法可以帮助解决与Kornia库相关的FP16梯度unscale问题。不过值得注意的是,不同场景下最优解可能会有所区别,所以最好根据实际情况灵活运用上述策略组合。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值