一、准备工作
首先更新系统软件包并安装必要工具,确保后续步骤顺利进行:
sudo yum update -y
sudo yum install -y git python3 python3-pip python3-devel gcc cmake
Stable Diffusion对硬件配置有明确要求,需提前检查是否符合:
二、安装Python环境
为避免依赖冲突,建议使用虚拟环境隔离项目:
python3 -m pip install --upgrade pip
python3 -m venv stable-diffusion-env # 创建虚拟环境
source stable-diffusion-env/bin/activate # 激活虚拟环境
安装Stable Diffusion运行所需的Python包:
pip install torch torchvision torchaudio # PyTorch核心库(需匹配CUDA版本)
pip install transformers opencv-python-headless pillow # 图像处理与模型支持库
三、部署Stable Diffusion WebUI(推荐方式)
使用AUTOMATIC1111团队的WebUI项目(功能最完善,支持Web交互):
git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git
cd stable-diffusion-webui
运行webui.sh
脚本自动完成依赖安装与环境配置:
bash webui.sh
MODEL_PATH
参数。脚本运行完成后,在浏览器中访问http://localhost:7860
(默认端口),即可看到Stable Diffusion的WebUI界面,通过文本提示词生成图像。
四、可选:手动部署(非WebUI方式)
若无需Web界面,可直接通过命令行生成图像:
从Hugging Face或其他来源下载模型文件(如stable-diffusion-v1-5
):
git clone https://huggingface.co/stable-diffusion-v1-5
cd stable-diffusion-v1-5
使用Stable Diffusion的Python API生成图像:
from diffusers import StableDiffusionPipeline
import torch
# 加载模型(需替换为实际模型路径)
model_path = "/path/to/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_path, torch_dtype=torch.float16)
pipe = pipe.to("cuda") # 使用GPU加速
# 生成图像(提示词示例:"a beautiful sunset over the ocean")
image = pipe("a beautiful sunset over the ocean", num_inference_steps=50).images[0]
image.save("output.png") # 保存结果
五、常见问题排查
确保PyTorch版本与CUDA/cuDNN版本兼容(如PyTorch 2.0需搭配CUDA 11.8+)。可通过nvcc --version
查看CUDA版本,cat /usr/local/cuda/include/cudnn_version.h | grep CUDNN_MAJOR
查看cuDNN版本。
若出现CUDA out of memory
错误,可尝试:
image_width
/image_height
从512调整为256);num_samples
);确保模型文件路径正确且未损坏。若从第三方来源下载,建议验证文件哈希值(如SHA256)。
若git clone
或pip install
速度慢,可设置代理或使用国内镜像(如清华源):
git config --global http.proxy http://your_proxy:port
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple torch