Tutorial9: Stable_diffusion¶
本节旨在展示使用 stable-diffusion-3-medium-diffusers 模型进行文生图任务。
分以下几步来实现:
- 环境安装与应用创建
- 下载模型
- 文生图
Stable Diffusion 是由 Stability AI 开发的一个开源的深度学习模型,用于生成高质量图像。
1. 环境安装与应用创建¶
首先在联网的命令行中创建conda环境:
conda create -n tutorial9 python=3.9
conda activate tutorial9
conda install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia
pip install notebook jupyterlab sentencepiece protobuf numpy==1.26.4 matplotlib==3.8.4 transformers==4.42.4
pip install -U diffusers
( pytorch 版本需与 cuda 版本对应,请查看版本对应网站:https://pytorch.org/get-started/previous-versions ,通过 nvidia-smi 命令可查看 cuda 版本)
然后创建JupyterLab应用, Conda环境名请填写tutorial9, 硬件资源为 1 张 A100 显卡。创建应用后, 进入应用并打开本文件。
CUDA Version: 12.1; Torch Version: 2.3.1
2. 下载模型¶
在联网的命令行中执行,命令执行位置在当前文件所在的文件夹。
# 如果以下目录存在, 可以直接复制:
cp -r /lustre/public/tutorial/models/stable-diffusion-3-medium-diffusers/ ./
# 否则请下载, 其中 "hf_***" 是 huggingface 官网为每个用户提供的 token 序列
export HF_ENDPOINT=https://hf-mirror.com
huggingface-cli download --token hf_*** --resume-download stabilityai/stable-diffusion-3-medium-diffusers --local-dir stable-diffusion-3-medium-diffusers
(建议使用 tmux 工具进行数据下载。tmux(Terminal Multiplexer)是一个终端复用器,它允许用户在一个单一终端会话中运行多个终端会话,并且它的会话可以在不同的时间和地点断开和重新连接,非常适合远程工作和需要长时间运行的任务。关于 tmux 的安装和介绍参考:https://tmuxcheatsheet.com/how-to-install-tmux ; 使用参考: https://tmuxcheatsheet.com)
3. 文生图¶
运行以下代码,从文字生成图像:
In [ ]:
import torch
from diffusers import StableDiffusion3Pipeline
# 加载模型
pipe = StableDiffusion3Pipeline.from_pretrained(
"stable-diffusion-3-medium-diffusers", torch_dtype=torch.float16)
# 使用 GPU
pipe = pipe.to("cuda")
# promt 内容,可以使用多个 prompt
# prompt2 = "Photorealistic"
prompt = "Albert Einstein leans forward, holds a Qing dynasty fan." +\
" A butterfly lands on the blooming peonies in the garden." +\
" The fan is positioned above the butterfly. "
# 根据 prompt 生成多张图片
for i in range(10):
image = pipe(
prompt=prompt,
# prompt_2=prompt2,
negative_prompt=\
"ugly, deformed, disfigured, poor details, bad anatomy",
num_inference_steps=70,
guidance_scale=7,
height=1024,
width=1024,
).images[0]
image.save(f"{i}.png")
生成的图像在本地目录下,可点击或下载查看。
作者: 黎颖; 龙汀汀
联系方式: yingliclaire@pku.edu.cn; l.tingting@pku.edu.cn