ComfyUI - 自定义数据集 使用 LoRA 微调 图像生成 Flux 模型 (AI Toolkit)

欢迎关注我的CSDN:https://spike.blog.csdn.net/
本文地址:https://spike.blog.csdn.net/article/details/141638928

免责声明:本文来源于个人知识与公开资料,仅用于学术交流,欢迎讨论,不支持转载。


LoRA

在 Diffusion 图像生成框架中,使用 LoRA(Low-Rank Adaptation)微调,难点在于,需要精确控制模型参数的更新以避免破坏预训练模型的知识,同时保持生成图像的多样性和质量,这涉及到复杂的优化策略和计算资源的高效利用,以及在保持模型泛化能力的同时实现特定任务的微调,这通常需要大量的实验和调参来找到最佳的低秩矩阵和学习率,以确保模型在特定数据集上的性能提升。

LoRA 训练框架,参考 AI Toolkit by Ostris,配置开发环境:

git clone https://github.com/ostris/ai-toolkit
cd ai-toolkit
git submodule update --init --recursive
conda create -n ai-toolkit python=3.9
conda activate ai-toolkit
pip3 install torch==2.4.0 torchvision torchaudio -i https://pypi.tuna.tsinghua.edu.cn/simple

测试 PyTorch 是否安装成功,即:

python

import torch
print(torch.__version__)  # 2.4.0
print(torch.cuda.is_available())  # True
exit()

再安装其他依赖的 Python 库:

pip install -r requirements.txt

配置训练文件:

cd ai-toolkit/config/examples/
cp train_lora_flux_24gb.yaml ../.

重要参数包括 LoRA 相关参数、batch_sizelr (learning rate)、精度使用float16,即:

network:
  type: "lora"
  linear: 16
  linear_alpha: 16
train:
  batch_size: 1
  steps: 2000  # total number of steps to train 500 - 4000 is a good range
  gradient_accumulation_steps: 1
  lr: 1e-4
save:
  dtype: float16 # precision to save

修改配置文件 train_lora_flux_24gb.yaml 的相关路径:

  • folder_path:图像数据集,包括图像,以及同名的描述 (caption),数据集准备使用 Joy Caption 模型,参考
  • name_or_path:基础的 Diffusion 模型,使用 FLUX.1-dev
folder_path: "joy-caption-pre-alpha/image_datasets/yky_ori_dataset"
name_or_path: "FLUX.1-dev"

在图像数据集的描述中,第一行,加入,This is a photo of a girl named [xxx]. 强化关键词,大约 40 张图像,以及描述。

单卡运行训练脚本:

CUDA_VISIBLE_DEVICES=1 nohup python -u run.py config/train_lora_flux_24gb.yaml > nohup.out &

关于显存占用:batch_size=1 是 22892M、batch_size=4 是 32076M。如果运行错误,参考 Bug1 的解决方案。

输出文件夹,my_first_flux_lora_v1.safetensors 即最终的模型,训练 2000 steps,即:

├── [1.8K]  config.yaml
├── [164M]  my_first_flux_lora_v1.safetensors
├── [164M]  my_first_flux_lora_v1_000001000.safetensors
├── [164M]  my_first_flux_lora_v1_000001250.safetensors
├── [164M]  my_first_flux_lora_v1_000001500.safetensors
├── [164M]  my_first_flux_lora_v1_000001750.safetensors
├── [165M]  optimizer.pt
└── [4.0K]  samples

samples 是模型在训练过程中的图像变化,提示词来源于配置中的 sample/prompts 字段:

Img

在 ComfyUI 中,调用 Flux + LoRA 的效果,使用不同的 LoRA 模型权重,效果如下:
LoRA

参考:在 ComfyUI 中配置 Flux + LoRA 的组合流程优化图像属性

Bug1:

TypeError: unsupported operand type(s) for |: 'torch._C._TensorMeta' and 'NoneType'

解决:修改 ai-toolkit/toolkit/config_modules.py 文件,需要修改 2 处,即:

Union[torch.Tensor, None]  # Union[torch.Tensor | None]

参考:Error for Flux Dev Lora => TypeError: unsupported operand type(s) for |: ‘torch._C._TensorMeta’ and ‘NoneType’

Bug2:

ai-toolkit/lib/python3.9/site-packages/controlnet_aux/mediapipe_face/mediapipe_face_common.py:7: UserWarning: The module 'mediapipe' is not installed. The package will have limited functionality. Please install it using the command: pip install 'mediapipe'

解决:安装 mediapipe 包,即可。

pip install mediapipe -i https://pypi.tuna.tsinghua.edu.cn/simple

Bug3:

ontrolnet_aux/segment_anything/modeling/tiny_vit_sam.py:654: UserWarning: Overwriting tiny_vit_5m_224 in registry with controlnet_aux.segment_anything.modeling.tiny_vit_sam.tiny_vit_5m_224. This is because the name being registered conflicts with an existing name. Please check if this is not expected.
  return register_model(fn_wrapper)

解决:降低 timm 包的版本,即可。

pip show timm
pip install timm==0.9.10

其他 Flux 的 LoRA,参考 XLabs AI: https://huggingface.co/XLabs-AI

XLabs AI is a part of an international company, a product laboratory where we strive to become leaders in machine learning and neural networks. The company develops and implements revolutionary solutions, setting new standards and inspiring to achieve the impossible in the field of information technology. Our team is an open, energized, and young collective that welcomes innovative ideas and supports the initiative and creativity of our employees.

XLabs AI 是一家国际公司的一部分,也是一个产品实验室,我们努力成为机器学习和神经网络领域的领导者。公司开发并实施革命性的解决方案,树立新的标准,并且激励人们在信息技术领域实现不可能。

LoRA: https://huggingface.co/XLabs-AI/flux-lora-collection/tree/main,LoRA 模型大小是 22.4M、44.8M,最大是 359 M,主要是 Rank (置) 相关。

参考:

### 使用 FluxLoRA 进行机器学习模型训练 #### 准备环境与工具 为了能够顺利地使用 FluxLoRA 来进行模型训练,首先需要准备好相应的开发环境。这通常意味着要安装 Python 及其必要的库文件,比如 PyTorch 或 TensorFlow 等深度学习框架。对于特定于 Flux 的情况,则需按照官方文档指导完成 Julia 编程语言及其依赖项的设置。 #### 加载预训练模型并应用LoRA微调 当准备就绪之后,可以从 Hugging Face Hub 下载预先训练好的基础模型作为起点[^2]。接着利用 LoRA 技术对该模型实施低秩适配(low-rank adaptation),即只更新部分参数而非整个网络结构中的所有权重值。这种方法不仅提高了效率而且减少了过拟合的风险。 ```python from peft import LoraConfig, get_peft_model import torch.nn as nn model = ... # Load your base model here. config = LoraConfig( r=8, lora_alpha=32, target_modules=["q", "v"], lora_dropout=0.05, ) peft_model = get_peft_model(model, config) ``` #### 构建数据集用于训练过程 构建适合当前任务的数据集至关重要。如果目标是创建像“黑神话悟空”这样的角色图像生成器,则应收集大量与此主题相关的高质量图片样本,并将其整理成可用于训练的形式。这些数据应当被划分为训练集、验证集以及测试集三大部分以便后续评估模型性能[^3]。 #### 开始训练流程 一旦上述准备工作全部完成后就可以启动实际的训练环节了。此阶段涉及到定义损失函数(loss function)、优化算法(optimizer algorithm)以及其他超参的选择。值得注意的是,在每次迭代过程中都要保存好最佳版本的模型副本至指定路径下以供将来部署或进一步改进之用[^1]。 ```python output_dir = "./ai-toolkit/output" for epoch in range(num_epochs): ... if best_loss > current_loss: best_loss = current_loss checkpoint_path = f"{output_dir}/best_model.pth" torch.save(peft_model.state_dict(), checkpoint_path) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ManonLegrand

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值