Diffusers documentation

文本到图像

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.43.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

文本到图像

当你想到扩散模型时,文生图通常是首先浮现在脑海的应用之一。文生图根据文本描述(例如,“丛林中的宇航员,冷色调,柔和的色彩,细节丰富,8k”)生成图像,这种文本描述也被称为提示词。

从宏观层面来看,扩散模型接收一个提示词和随机初始噪声,并通过迭代去噪来构建图像。去噪过程由提示词引导,在预定的时间步数结束后,图像表示会被解码为最终图像。

阅读 Stable Diffusion 是如何工作的? 博客文章,以了解潜在扩散模型的工作原理。

您可以在 🤗 Diffusers 中通过两个步骤根据提示词生成图像:

  1. 将检查点加载到 AutoPipelineForText2Image 类中,该类会根据检查点自动检测应使用的合适 pipeline 类:
from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
	"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16"
).to("cuda")  # or "mps", "xpu", "cpu"
  1. 将提示词传递给 pipeline 以生成图像:
image = pipeline(
	"stained glass of darth vader, backlight, centered composition, masterpiece, photorealistic, 8k"
).images[0]
image

热门模型

最常用的文本生成图像模型包括 Stable Diffusion v1.5、Stable Diffusion XL (SDXL) 和 Kandinsky 2.2。此外,还有 ControlNet 模型或适配器,可与文本生成图像模型配合使用,从而在生成图像时实现更直接的操控。由于架构和训练流程的差异,各模型的输出结果略有不同,但无论选择哪个模型,其用法基本一致。下面我们将使用相同的提示词(prompt)分别运行各模型,并对比它们的生成结果。

Stable Diffusion v1.5

Stable Diffusion v1.5 是一个从 Stable Diffusion v1-4 初始化的潜在扩散模型,并在 LAION-Aesthetics V2 数据集的 512x512 图像上微调了 595K 步。您可以像这样使用该模型:

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
	"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16"
).to("cuda")  # or "mps", "xpu", "cpu"
generator = torch.Generator("cuda").manual_seed(31)
image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", generator=generator).images[0]
image

Stable Diffusion XL

SDXL 是此前 Stable Diffusion 模型的更大版本,采用两阶段模型流程,为图像添加更多细节。它还包含一些额外的 微条件,以生成以主体为中心的高质量图像。请参阅更全面的 SDXL 指南,了解如何使用它。通常,您可以像这样使用 SDXL:

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16, variant="fp16"
).to("cuda")  # or "mps", "xpu", "cpu"
generator = torch.Generator("cuda").manual_seed(31)
image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", generator=generator).images[0]
image

Kandinsky 2.2

Kandinsky 模型与 Stable Diffusion 模型略有不同,因为它还使用了一个图像先验模型来生成嵌入,以便在扩散模型中更好地对齐文本和图像。

使用 Kandinsky 2.2 最简单的方法是:

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
	"kandinsky-community/kandinsky-2-2-decoder", dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"
generator = torch.Generator("cuda").manual_seed(31)
image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", generator=generator).images[0]
image

ControlNet

ControlNet 模型是在文本到图像模型(例如 Stable Diffusion v1.5)之上进行微调的辅助模型或适配器。将 ControlNet 模型与文本到图像模型结合使用,为更明确地控制图像生成方式提供了多种选择。使用 ControlNet 时,您需要向模型添加一个额外的条件输入图像。例如,如果您提供一张人体姿态图像(通常表示为连接成骨架的多个关键点)作为条件输入,模型将生成一张遵循该图像姿态的图片。请查阅更深入的 ControlNet 指南,以了解其他条件输入及其使用方法。

在此示例中,我们将使用人体姿态估计图像作为 ControlNet 的条件输入。加载在人体姿态估计上预训练的 ControlNet 模型:

from diffusers import ControlNetModel, AutoPipelineForText2Image
from diffusers.utils import load_image
import torch

controlnet = ControlNetModel.from_pretrained(
	"lllyasviel/control_v11p_sd15_openpose", dtype=torch.float16, variant="fp16"
).to("cuda")  # or "mps", "xpu", "cpu"
pose_image = load_image("https://huggingface.co/lllyasviel/control_v11p_sd15_openpose/resolve/main/images/control.png")

将 controlnet 传递给 AutoPipelineForText2Image,并提供提示词和姿态估计图像:

pipeline = AutoPipelineForText2Image.from_pretrained(
	"stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, dtype=torch.float16, variant="fp16"
).to("cuda")  # or "mps", "xpu", "cpu"
generator = torch.Generator("cuda").manual_seed(31)
image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", image=pose_image, generator=generator).images[0]
image
Stable Diffusion v1.5
Stable Diffusion XL
Kandinsky 2.2
ControlNet(姿态条件)

配置流水线参数

在 pipeline 中,有多个可配置的参数会影响图像的生成方式。您可以更改图像的输出尺寸、指定负面提示词以提升图像质量,等等。本节将深入介绍如何使用这些参数。

高度和宽度

height 和 width 参数用于控制生成图像的高度和宽度(以像素为单位)。默认情况下,Stable Diffusion v1.5 模型输出 512x512 的图像,但您可以将其更改为任何 8 的倍数尺寸。例如,要创建矩形图像:

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
	"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16"
).to("cuda")  # or "mps", "xpu", "cpu"
image = pipeline(
	"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", height=768, width=512
).images[0]
image

其他模型可能根据训练数据集中的图像尺寸而具有不同的默认图像尺寸。例如,SDXL 的默认图像尺寸为 1024x1024,使用更低的 height 和 width 值可能会导致生成的图像质量较低。请务必先查阅该模型的 API 参考文档!

引导比例

guidance_scale 参数决定了提示词对图像生成的影响程度。较低的数值会赋予模型一定的“创造性”,使其生成的图像与提示词的关联更为宽松。较高的 guidance_scale 值会促使模型更严格地遵循提示词,但如果该值过高,生成的图像中可能会出现一些伪影。

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
	"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"
image = pipeline(
	"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", guidance_scale=3.5
).images[0]
image
guidance_scale = 2.5
guidance_scale = 7.5
guidance_scale = 10.5

负面提示

正如提示词引导生成过程一样,负面提示词会引导模型避开你不希望其生成的内容。这通常用于通过去除“低分辨率”或“细节不佳”等不良图像特征来提升整体图像质量。你还可以使用负面提示词来移除或修改图像的内容和风格。

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
	"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"
image = pipeline(
	prompt="Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
	negative_prompt="ugly, deformed, disfigured, poor details, bad anatomy",
).images[0]
image
negative_prompt = "ugly, deformed, disfigured, poor details, bad anatomy"
negative_prompt = "astronaut"

生成器

torch.Generator 对象通过设置手动种子来实现流水线中的可复现性。您可以使用 Generator 生成图像批次,并基于种子生成的图像进行迭代优化,具体方法详见 使用确定性生成提升图像质量 指南。

您可以设置种子和 Generator,如下所示。使用 Generator 生成图像时,每次都应返回相同的结果,而不是随机生成新图像。

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
	"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"
generator = torch.Generator(device="cuda").manual_seed(30)
image = pipeline(
	"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
	generator=generator,
).images[0]
image

控制图像生成

除了配置流水线参数(例如提示词权重和 ControlNet 模型)之外,还有几种方法可以更精细地控制图像的生成过程。

提示词加权

提示词加权是一种用于增加或降低提示词中概念重要性的技术,以强调或弱化图像中的某些特征。我们建议使用 Compel 库来帮助你生成加权提示词嵌入。

请参阅 Prompt weighting 指南,了解如何创建 prompt embeddings。本示例重点介绍如何在 pipeline 中使用 prompt embeddings。

创建嵌入后,您可以将其传入管道中的 prompt_embeds 参数(如果使用负面提示,则还需传入 negative_prompt_embeds 参数)。

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
	"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"
image = pipeline(
	prompt_embeds=prompt_embeds, # generated from Compel
	negative_prompt_embeds=negative_prompt_embeds, # generated from Compel
).images[0]

ControlNet

如您在 ControlNet 部分所见,这些模型通过引入额外的条件图像输入,提供了一种更灵活、更精确的图像生成方式。每个 ControlNet 模型都针对特定类型的条件图像进行了预训练,以生成与之相似的新图像。例如,如果您使用一个在深度图上预训练的 ControlNet 模型,可以将深度图作为条件输入提供给该模型,它将生成一张保留其中空间信息的图像。这比在提示词中指定深度信息更快、更简单。您甚至可以使用 Multi-ControlNet 来组合多个条件输入!

您可以使用多种类型的条件输入,🤗 Diffusers 支持 Stable Diffusion 和 SDXL 模型的 ControlNet。请参阅更全面的 ControlNet 指南,了解如何使用这些模型。

优化

扩散模型体积庞大,且对图像进行去噪的迭代过程在计算上开销巨大、资源消耗密集。但这并不意味着你必须拥有强大的——甚至大量的——GPU 才能使用它们。有许多优化技术可以在消费级硬件和免费层资源上运行扩散模型。例如,你可以以半精度加载模型权重,以节省 GPU 显存并提升速度,或者将整个模型卸载到 GPU 上,以进一步节省显存。

PyTorch 2.0 还支持一种更节省内存的注意力机制,称为 缩放点积注意力,如果您使用的是 PyTorch 2.0,该机制会自动启用。您可以将其与 torch.compile 结合使用,以进一步加快代码运行速度:

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16").to("cuda")  # or "mps", "xpu", "cpu"
pipeline.unet = torch.compile(pipeline.unet, mode="reduce-overhead", fullgraph=True)

有关如何优化代码以节省内存并加快推理速度的更多提示,请参阅优化与扩展。

Update on GitHub