本地部署 Stable Diffusion AI 模型实战指南
本文介绍了在本地 Python 环境中使用 diffusers 库部署 Stable Diffusion 模型的完整流程。内容涵盖环境搭建、模型下载与加载、GPU 设备配置、调度器选择、提示词工程及图像生成参数调优。提供了从零开始的代码示例和常见问题排查指南,帮助开发者快速实现文生图功能并进行本地化 AI 应用开发。

本文介绍了在本地 Python 环境中使用 diffusers 库部署 Stable Diffusion 模型的完整流程。内容涵盖环境搭建、模型下载与加载、GPU 设备配置、调度器选择、提示词工程及图像生成参数调优。提供了从零开始的代码示例和常见问题排查指南,帮助开发者快速实现文生图功能并进行本地化 AI 应用开发。

本文介绍如何在本地 Python 环境中使用 diffusers 库运行 Stable Diffusion 模型,实现文生图(Text-to-Image)功能。我们将涵盖环境搭建、模型加载、推理配置及完整代码示例。
diffusers 目前对 Python 3.12 的支持尚不完善,建议使用 Python 3.10 或 3.11 版本创建虚拟环境以避免依赖冲突。
# 使用 3.10 版本的 python 创建 venv
/opt/homebrew/opt/[email protected]/libexec/bin/python3 -m venv .venv
# 激活 venv (Mac/Linux)
source .venv/bin/activate
# Windows 用户请使用:.venv\Scripts\activate
安装核心库及其依赖项:
pip install diffusers accelerate transformers torch torchvision torchaudio
注意:如果是在 NVIDIA GPU 环境下,请确保已安装对应版本的 CUDA Toolkit 和 cuDNN,以便 PyTorch 能调用 GPU 加速。
模型文件通常存储在 Hugging Face 或 Civitai 等社区平台。diffusers 支持多种格式的模型文件。
runwayml/stable-diffusion-v1-5。推荐使用 Git LFS 克隆模型仓库:
git lfs install
git clone [email protected]:<MODEL_ID>
# 例如:git clone [email protected]:stabilityai/stable-diffusion-xl-base-1.0
或者直接从网页下载 .safetensors 格式的单文件模型。
选择模型时需关注以下属性:
根据模型文件格式不同,加载方式有所区别。
如果是下载的 .safetensors 单文件模型:
from diffusers import StableDiffusionXLPipeline
pipe = StableDiffusionXLPipeline.from_single_file("path/to/dreamshaperXL_v21TurboDPMSDE.safetensors")
如果是从 Hugging Face 下载的完整目录结构:
from diffusers import StableDiffusionPipeline
pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
根据硬件环境设置推理设备,以利用 GPU 加速。
import torch
device = "cuda" if torch.cuda.is_available() else "cpu"
pipe = pipe.to(device)
Apple Silicon 支持 MPS (Metal Performance Shaders) 后端:
device = 'mps'
pipe = pipe.to(device)
调度器(Scheduler)决定了图像生成的采样过程,直接影响画质和速度。它对应 AUTOMATIC1111 WebUI 中的 Sampling method。
from diffusers import DPMSolverSinglestepScheduler
pipe.scheduler = DPMSolverSinglestepScheduler.from_config(
pipe.scheduler.config,
use_karras_sigmas=True
)
提示词(Prompt)的质量直接决定生成效果。默认 Token 限制通常为 77 个,如需更长描述可使用 compel 库进行向量化处理。
prompt = "masterpiece, cat wizard, gandalf, lord of the rings, detailed, fantasy, cute, adorable, Pixar, Disney"
negative_prompt = "worst quality, low quality, normal quality, lowres, low details, oversaturated, undersaturated, overexposed, underexposed"
安装 compel 库:
pip install compel
使用 Compel 处理提示词嵌入:
from compel import Compel, ReturnedEmbeddingsType
compel = Compel(
tokenizer=[pipe.tokenizer, pipe.tokenizer_2],
text_encoder=[pipe.text_encoder, pipe.text_encoder_2],
returned_embeddings_type=ReturnedEmbeddingsType.PENULTIMATE_HIDDEN_STATES_NON_NORMALIZED,
requires_pooled=[False, True]
)
conditioning, pooled = compel(prompt)
negative_prompt_embeds, negative_pooled = compel(negative_prompt)
调用 Pipeline 进行推理,调整关键参数以获得最佳效果。
num_inference_steps: 推理步数,越多越精细但越慢(建议 20-50)。guidance_scale: 引导系数,控制提示词遵循程度(建议 5-9)。strength: 用于图生图时的强度。image = pipe(
prompt_embeds=conditioning,
pooled_prompt_embeds=pooled,
negative_prompt_embeds=negative_prompt_embeds,
negative_pooled_prompt_embeds=negative_pooled,
height=1024,
width=1024,
num_inference_steps=6,
guidance_scale=2,
).images[0]
image.save("output.jpg")
将上述步骤整合为一个完整的可运行脚本:
import torch
from diffusers import StableDiffusionXLPipeline, DPMSolverSinglestepScheduler
from compel import Compel, ReturnedEmbeddingsType
# 1. 初始化设备
device = "cuda" if torch.cuda.is_available() else "cpu"
# 2. 加载模型
model_path = "path/to/your/model.safetensors"
pipe = StableDiffusionXLPipeline.from_single_file(model_path)
pipe = pipe.to(device)
# 3. 配置调度器
pipe.scheduler = DPMSolverSinglestepScheduler.from_config(
pipe.scheduler.config, use_karras_sigmas=True
)
# 4. 配置提示词处理器
compel = Compel(
tokenizer=[pipe.tokenizer, pipe.tokenizer_2],
text_encoder=[pipe.text_encoder, pipe.text_encoder_2],
returned_embeddings_type=ReturnedEmbeddingsType.PENULTIMATE_HIDDEN_STATES_NON_NORMALIZED,
requires_pooled=[False, True]
)
# 5. 定义提示词
prompt = "a beautiful landscape with mountains and lakes, realistic, 8k resolution"
negative_prompt = "blurry, low quality, distorted"
conditioning, pooled = compel(prompt)
negative_prompt_embeds, negative_pooled = compel(negative_prompt)
# 6. 执行生成
image = pipe(
prompt_embeds=conditioning,
pooled_prompt_embeds=pooled,
negative_prompt_embeds=negative_prompt_embeds,
negative_pooled_prompt_embeds=negative_pooled,
num_inference_steps=20,
guidance_scale=7.5,
).images[0]
image.save("result.png")
print("Generation completed.")
--lowvram 启动选项,或启用 enable_model_cpu_offload()。.safetensors 或 .ckpt,并检查路径是否正确。本文详细讲解了在本地使用 diffusers 库运行 Stable Diffusion 的完整流程,包括环境配置、模型加载、调度器优化及提示词控制。通过本教程,开发者可以快速搭建自己的 AI 绘图工作流,并根据实际需求调整参数以获得高质量输出。后续可进一步探索 LoRA 微调、ControlNet 姿态控制等高级功能。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online