前几天跑 Stable Diffusion 生成了些插画,把过程整理了一下,方便以后复现。扩散模型听起来玄乎,本质上就像'给一张图逐步加噪声,再让神经网络学着从噪声里还原'。加上文本引导,就能控制生成内容。
环境准备
先搭一个虚拟环境,装好 PyTorch 和 HuggingFace 的 diffusers 库。记得选对 CUDA 版本,我用的 cu118。
python -m venv aigc_env
source aigc_env/bin/activate # Linux/Mac
# Windows: aigc_env\Scripts\activate
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
pip install diffusers transformers accelerate Pillow scipy tqdm
加载模型,写提示词
用 StableDiffusionPipeline 加载 runwayml/stable-diffusion-v1-5,半精度扔到 GPU 上。提示词可以写得很细,风格、色彩、细节都塞进去,负面提示词用来剔除不想要的元素。
from diffusers import StableDiffusionPipeline
import torch
model_id = "runwayml/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
pipe = pipe.to("cuda")
prompt = """ A dreamy forest at twilight, illuminated by bioluminescent plants, painted in the style of Alphonse Mucha with intricate Art Nouveau details, using a palette of deep purples and emerald greens """
negative_prompt = "ugly, deformed, blurry, bad anatomy"
生成第一张图
几个关键参数:宽度高度、去噪步数、guidance_scale、seed。guidance_scale 越高,图片越贴合提示词,但太高容易显得生硬,我一般用 7.5。seed 固定能复现结果,放开则每次不同。
parameters = {
"prompt": prompt,
"negative_prompt": negative_prompt,
"width": 768,
"height": 768,
"num_inference_steps": 50,
"guidance_scale": 7.5,
"seed": 42
}
with torch.autocast("cuda"):
image = pipe(**parameters).images[0]
image.save("aigc_artwork.png")


