TodayAI

GuidesModels

用 Diffusers 跑通第一次图像生成

按 Diffusers Quickstart:用 DiffusionPipeline.from_pretrained 加载模型,输入 prompt,取出 images[0] 完成第一次文生图。

基于 Hugging Face Docs 整理 · 官方资料 ↗

Diffusers 把扩散模型的文本编码器、调度器、UNet/DiT、VAE 收进 DiffusionPipeline,让你用一行推理 API 生成图像、视频或音频。

这篇只把文生图跑通。官方示例模型是 Qwen/Qwen-Image;部分 gated 模型需要 Hugging Face 账号与授权。

DiffusionPipeline 打包了什么

  • 文本编码器:把 prompt 变成引导去噪的向量
  • Scheduler:控制噪声逐步去掉的算法细节
  • UNet 或 DiT:反复预测如何去噪
  • VAE:在压缩 latent 与像素之间编解码

你通常不需要手装这些零件;from_pretrained 会按模型卡组装好。

第一次文生图

按官方 Installation 装好 Diffusers 与 PyTorch,并准备好 CUDA 设备(示例使用 device_map="cuda")。

官方 text-to-image 示例

python
import torch
from diffusers import DiffusionPipeline

pipeline = DiffusionPipeline.from_pretrained(
    "Qwen/Qwen-Image", dtype=torch.bfloat16, device_map="cuda"
)

prompt = """
cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
"""
image = pipeline(prompt).images[0]
image.save("qwen-image.png")

用 .images[0] 取第一张图。num_inference_steps 等参数会影响速度与质量,可按文档再调。

可选:加载 LoRA

LoRA 只训练少量附加参数,常用来切换风格。官方示例:

官方 load_lora_weights

python
pipeline.load_lora_weights("flymy-ai/qwen-image-realism-lora")

prompt = """
super Realism cinematic film still of a cat sipping a margarita in a pool in Palm Springs in the style of umempart, California
highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
"""
pipeline(prompt).images[0]

有的 LoRA 需要触发词(如 Realism);以该 LoRA 的模型卡为准。

显存不够时怎么办

官方 Quickstart 后续讲量化与 offload。最小记忆点:可用 bitsandbytes 4bit 量化,或 enable_model_cpu_offload() 把暂不用的组件放回 CPU。

先保证默认 pipeline 能在你的硬件上跑通,再叠加优化;不要一上来同时改量化、编译和调度器。

容易踩的坑

gated 模型下载失败

登录 Hugging Face 账号,在模型页申请访问,并完成 hf auth login。

CUDA OOM

换更小模型、降低精度、启用 offload/量化;先去掉同时加载的多个 pipeline。

输出不是 PIL 图像

文生图结果在 .images;视频在 .frames,不要混用字段。

官方资料

Hugging Face Docs

Quickstart