Stable Diffusion:使用自己的数据集微调 Stable Diffusion 3.5 LoRA 文生图模型

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

前言

环境要求

Package                  Version
------------------------ ------------
absl-py                  2.3.1
accelerate               1.11.0
aiohappyeyeballs         2.6.1
aiohttp                  3.13.1
aiosignal                1.4.0
annotated-types          0.7.0
anyio                    4.11.0
attrs                    25.4.0
bitsandbytes             0.48.1
certifi                  2025.10.5
charset-normalizer       3.4.4
click                    8.3.0
datasets                 4.2.0
diffusers                0.35.2
dill                     0.4.0
filelock                 3.20.0
frozenlist               1.8.0
fsspec                   2025.9.0
gitdb                    4.0.12
GitPython                3.1.45
grpcio                   1.75.1
h11                      0.16.0
hf-xet                   1.1.10
httpcore                 1.0.9
httpx                    0.28.1
huggingface-hub          0.35.3
idna                     3.11
importlib_metadata       8.7.0
Jinja2                   3.1.6
Markdown                 3.9
MarkupSafe               3.0.3
modelscope               1.31.0
mpmath                   1.3.0
multidict                6.7.0
multiprocess             0.70.16
networkx                 3.5
numpy                    2.3.4
nvidia-cublas-cu11       11.11.3.6
nvidia-cuda-cupti-cu11   11.8.87
nvidia-cuda-nvrtc-cu11   11.8.89
nvidia-cuda-runtime-cu11 11.8.89
nvidia-cudnn-cu11        9.1.0.70
nvidia-cufft-cu11        10.9.0.58
nvidia-curand-cu11       10.3.0.86
nvidia-cusolver-cu11     11.4.1.48
nvidia-cusparse-cu11     11.7.5.86
nvidia-nccl-cu11         2.20.5
nvidia-nvtx-cu11         11.8.86
packaging                25.0
pandas                   2.3.3
peft                     0.17.1
Pillow                   9.5.0
pip                      24.0
platformdirs             4.5.0
propcache                0.4.1
protobuf                 6.33.0
psutil                   7.1.1
pyarrow                  21.0.0
pydantic                 2.12.3
pydantic_core            2.41.4
python-dateutil          2.9.0.post0
pytz                     2025.2
PyYAML                   6.0.3
regex                    2025.10.22
requests                 2.32.5
safetensors              0.6.2
sentencepiece            0.2.1
sentry-sdk               2.42.1
setuptools               65.5.0
six                      1.17.0
smmap                    5.0.2
sniffio                  1.3.1
sympy                    1.14.0
tensorboard              2.20.0
tensorboard-data-server  0.7.2
tokenizers               0.22.1
torch                    2.4.1+cu118
torchaudio               2.4.1+cu118
torchvision              0.19.1+cu118
tqdm                     4.67.1
transformers             4.57.1
triton                   3.0.0
typing_extensions        4.15.0
typing-inspection        0.4.2
tzdata                   2025.2
urllib3                  2.5.0
wandb                    0.22.2
Werkzeug                 3.1.3
xxhash                   3.6.0
yarl                     1.22.0
zipp                     3.23.0

相关介绍

  • Python是一种跨平台的计算机程序设计语言。是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言。最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能的添加,越多被用于独立的、大型项目的开发。
  • PyTorch 是一个深度学习框架,封装好了很多网络和深度学习相关的工具方便我们调用,而不用我们一个个去单独写了。它分为 CPU 和 GPU 版本,其他框架还有 TensorFlow、Caffe 等。PyTorch 是由 Facebook 人工智能研究院(FAIR)基于 Torch 推出的,它是一个基于 Python 的可续计算包,提供两个高级功能:1、具有强大的 GPU 加速的张量计算(如 NumPy);2、构建深度神经网络时的自动微分机制。
  • Stable Diffusion 3.5 简介
    • 核心特点
      Stable Diffusion 3.5 是 Stability AI 于 2024 年 10 月 22 日正式发布的最新图像生成模型,是 Stable Diffusion 3.0 系列的升级版本,旨在回应社区对 SD3 Medium 版本的不满。
    • 主要版本:
      • Stable Diffusion 3.5 Large:80亿参数,支持100万像素分辨率的高清图像生成
      • Stable Diffusion 3.5 Large Turbo:80亿参数,仅需4步即可生成高质量图像,速度比 Large 版本快5-10倍
      • Stable Diffusion 3.5 Medium(10月29日发布):25亿参数,适合消费级硬件,支持0.25-200万像素图像生成
    • 技术核心:
      • 采用 MM-DiT(Modified Multimodal Diffusion Transformer)作为核心
      • 基于改进的 MMDiT-X 架构和训练方法
      • 集成 Query-Key Normalization,简化微调过程,提升可定制性
    • 优势
      • 图像质量提升:生成图像更清晰,画质优于前代版本
      • 提示词遵循能力:在提示词精确度方面领先市场,能更准确地理解用户指令
      • 多样化输出:能生成代表不同肤色、特征和背景的图像,无需复杂提示词
      • 广泛风格支持:可生成3D渲染、摄影作品、传统绘画、线条艺术等多种风格
      • 商业友好:年收入不超过100万美元的组织或个人可免费商用
      • 修复重大Bug:修复了 SD3 中"无法生成躺在草地上的女孩"的重大问题
    • 局限性
      • 结构稳定性:与 Flux 模型相比,在手指、文字等结构细节上略逊一筹
      • 提示词要求:当提示词缺乏具体性时,输出结果的不确定性可能增加
      • 硬件需求:虽然比前代优化,但 Large 版本仍需要10G以上显卡和32G以上内存
    • 应用场景
      • 艺术创作:艺术家和设计师生成独特艺术作品或设计概念图
      • 游戏开发:快速生成游戏角色、场景和道具的概念图
      • 广告营销:设计广告图像和营销材料,快速迭代创意
      • 媒体娱乐:在电影和视频制作中生成特效背景或场景
      • 教育研究:创建教学材料或模拟科学现象
      • 商业应用:中小企业和个人可免费商用,用于产品设计和营销
    • 与竞品对比
      • 与 Flux.1 DEV 相比:SD3.5 Large 推理速度略快(1分50秒 vs 2分10秒),画质更清晰
      • SD3.5 在提示词遵循能力上更优,但 Flux 在结构稳定性(如手指、文字)上略胜一筹
      • SD3.5 Large 支持100万像素,Flux 支持200万像素
  • 官方源代码: https://huggingface.co/stabilityai/stable-diffusion-3.5-large
  • Patrick Esser, Sumith Kulal, Andreas Blattmann, Rahim Entezari, Jonas Muller, Harry Saini, Yam Levi, Dominik Lorenz, Axel Sauer, Frederic Boesel, Dustin Podell, Tim Dockhorn, Zion English,
    Kyle Lacey, Alex Goodwin, Yannik Marek, Robin Rombach, Stability AI. Scaling Rectified Flow Transformers for High-Resolution Image Synthesis. 2024

微调 Stable Diffusion 3.5 LoRA 文生图模型

下载Stable Diffusion 3.5 LoRA Fine-Tuning项目

  • 官方源代码: https://github.com/seochan99/stable-diffusion-3.5-text2image-lora.git

Windows

在这里插入图片描述

Linux

git clone https://github.com/seochan99/stable-diffusion-3.5-text2image-lora.git

准备数据集

准备一个用于模型微调数据集。

dataset/
├── images/
│   ├── landscape_001.jpg
│   ├── portrait_001.jpg
│   └── ...
└── metadata.jsonl

在这里插入图片描述
在这里插入图片描述

metadata.jsonl,内容如下。

{"image": "images/landscape_001.jpg", "caption": "a breathtaking mountain landscape with snow-capped peaks, a crystal clear lake reflecting the sky, and pine trees in the foreground"}
{"image": "images/portrait_001.jpg", "caption": "a professional portrait of a young woman with curly brown hair, wearing a blue denim jacket, smiling softly, natural lighting"}
{"image": "images/cityscape_001.jpg", "caption": "a bustling cyberpunk cityscape at night, neon signs glowing in pink and blue, flying cars, futuristic skyscrapers reaching into the clouds"}
{"image": "images/nature_001.jpg", "caption": "a peaceful forest scene with tall oak trees, sunlight filtering through the leaves, a small stream flowing over rocks"}
{"image": "images/abstract_001.jpg", "caption": "an abstract digital art piece with flowing geometric shapes in vibrant colors, purple and gold gradients, modern minimalist style"}
{"image": "images/animal_001.jpg", "caption": "a majestic golden retriever dog sitting in a flower field, tongue out, happy expression, wildflowers in the background"}

下载预训练模型

Hugging Face

import os
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com' # 如果没有科学上网,可以设置国内镜像。

from huggingface_hub import snapshot_download
snapshot_download(repo_id="stabilityai/stable-diffusion-3.5-large", local_dir="stabilityai/stable-diffusion-3.5-large")

Model Scope

from modelscope import snapshot_download
model_dir = snapshot_download('AI-ModelScope/stable-diffusion-3.5-medium', local_dir="stabilityai/stable-diffusion-3.5-medium")

进行训练

python stable-diffusion-3.5-text2image-lora-main/train_text_to_image_lora_sd35.py --pretrained_model_name_or_path stabilityai/stable-diffusion-3.5-medium --train_data_dir sd3_test/stable-diffusion-3.5-text2image-lora-main/examples/dataset/ --output_dir sd3_test/stable-diffusion-3.5-text2image-lora-main/outputs/sd35-lora --resolution 1024 --train_batch_size 1 --gradient_accumulation_steps 4 --num_train_epochs 50 --rank 64 --learning_rate 0.0001 --text_encoder_lr 1e-05 --lr_scheduler cosine --lr_warmup_steps 500 --lr_num_cycles 1 --mixed_precision fp16 --validation_epochs 2 --num_validation_images 2 --checkpointing_steps 500 --report_to tensorboard --dataloader_num_workers 2 --seed 42 --precondition_outputs 1 --random_flip --gradient_checkpointing --train_text_encoder

输出结果

在这里插入图片描述

进行预测

python stable-diffusion-3.5-text2image-lora-main/inference.py --model_path stabilityai/stable-diffusion-3.5-medium --lora_path stable-diffusion-3.5-text2image-lora-main/outputs/sd35-lora/pytorch_lora_weights.safetensors --prompt "a professional portrait of a young woman with curly brown hair, wearing a blue denim jacket, smiling softly, natural lighting" --num_images 4 --seed 42

输出结果

在这里插入图片描述

参考

[1] Patrick Esser, Sumith Kulal, Andreas Blattmann, Rahim Entezari, Jonas Muller, Harry Saini, Yam Levi, Dominik Lorenz, Axel Sauer, Frederic Boesel, Dustin Podell, Tim Dockhorn, Zion English,
Kyle Lacey, Alex Goodwin, Yannik Marek, Robin Rombach, Stability AI. Scaling Rectified Flow Transformers for High-Resolution Image Synthesis. 2024

[2] https://huggingface.co/stabilityai/stable-diffusion-3.5-large
[3] https://huggingface.co/stabilityai/stable-diffusion-3.5-medium

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

FriendshipT

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

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

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

打赏作者

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

抵扣说明:

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

余额充值