引言
Stable Diffusion 4(简称SD4)是2026年发布的图像生成模型,在画质、风格多样性和提示词理解上有了质的飞跃。结合LoRA(Low-Rank Adaptation)微调,你可以用少量图片训练出特定风格或角色的模型。本文将从零开始,带你完成环境搭建、模型使用和LoRA训练。
环境准备
硬件要求
- 显卡:NVIDIA RTX 3060 12GB及以上(推荐RTX 4090)
- 内存:16GB以上
- 硬盘:50GB空闲空间
软件安装
- 安装Python 3.10:推荐使用Miniconda管理环境。
- 创建虚拟环境:
conda create -n sd4 python=3.10 conda activate sd4 - 安装PyTorch:根据CUDA版本选择命令,例如:
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121 - 克隆SD4仓库:
git clone https://github.com/Stability-AI/stable-diffusion-4.git cd stable-diffusion-4 pip install -r requirements.txt
下载模型
SD4模型权重可从Hugging Face下载,推荐使用stabilityai/stable-diffusion-4-base。
huggingface-cli download stabilityai/stable-diffusion-4-base --local-dir ./models/sd4-base
基础推理
编写一个简单的Python脚本生成图片:
from diffusers import StableDiffusion4Pipeline
import torch
pipe = StableDiffusion4Pipeline.from_pretrained("./models/sd4-base", torch_dtype=torch.float16)
pipe = pipe.to("cuda")
prompt = "a beautiful landscape, sunset, mountains, lake, highly detailed, 8k"
image = pipe(prompt, num_inference_steps=50, guidance_scale=7.5).images[0]
image.save("output.png")
LoRA微调训练
准备数据集
收集20-30张目标风格的图片(例如“水彩风格”),统一裁剪为512x512像素,放入./data/style文件夹。
安装LoRA训练脚本
SD4仓库中自带了LoRA训练脚本,位于scripts/train_lora.py。
训练命令
accelerate launch scripts/train_lora.py \
--pretrained_model_name_or_path ./models/sd4-base \
--train_data_dir ./data/style \
--output_dir ./lora-models \
--resolution 512 \
--train_batch_size 4 \
--learning_rate 1e-4 \
--num_train_epochs 100 \
--checkpointing_steps 500
参数说明
--train_batch_size:根据显存调整,12GB显存建议设为2。--learning_rate:1e-4是通用值,可尝试1e-5到5e-4。--num_train_epochs:100轮通常足够,观察loss曲线。
使用LoRA模型
训练完成后,会在./lora-models下生成pytorch_lora_weights.safetensors。推理时加载LoRA:
from diffusers import StableDiffusion4Pipeline
import torch
pipe = StableDiffusion4Pipeline.from_pretrained("./models/sd4-base", torch_dtype=torch.float16)
pipe.load_lora_weights("./lora-models", weight_name="pytorch_lora_weights.safetensors")
pipe = pipe.to("cuda")
prompt = "a cat in watercolor style"
image = pipe(prompt, num_inference_steps=50).images[0]
image.save("watercolor_cat.png")
高级技巧
1. 多LoRA融合
你可以同时加载多个LoRA,例如风格LoRA和角色LoRA,通过调整权重比例获得混合效果。
pipe.load_lora_weights("./lora-models/style", weight_name="style.safetensors", adapter_name="style")
pipe.load_lora_weights("./lora-models/character", weight_name="character.safetensors", adapter_name="character")
pipe.set_adapters(["style", "character"], adapter_weights=[0.7, 0.5])
2. 控制网(ControlNet)
SD4支持ControlNet,可以用姿态、深度图等控制生成。安装ControlNet后,添加条件输入:
from diffusers import ControlNetModel, StableDiffusion4ControlNetPipeline
controlnet = ControlNetModel.from_pretrained("lllyasviel/control_v11p_sd15_openpose")
pipe = StableDiffusion4ControlNetPipeline.from_pretrained("./models/sd4-base", controlnet=controlnet, torch_dtype=torch.float16)
总结
通过本教程,你应该已经掌握了SD4的本地部署和LoRA微调方法。AI图片生成的门槛正在降低,但创意和审美仍然是关键。尝试训练自己的LoRA模型,创造出独一无二的艺术作品吧!