Diffusers 文档
PixArt-α
并获得增强的文档体验
开始使用
PixArt-α
PixArt-α:用于逼真文本到图像合成的扩散 Transformer 的快速训练 的作者是 Junsong Chen、Jincheng Yu、Chongjian Ge、Lewei Yao、Enze Xie、Yue Wu、Zhongdao Wang、James Kwok、Ping Luo、Huchuan Lu 和 Zhenguo Li。
论文摘要如下
最先进的文本到图像 (T2I) 模型需要大量的训练成本(例如,数百万 GPU 小时),这严重阻碍了 AIGC 社区的根本创新,同时增加了二氧化碳排放。本文介绍了 PIXART-α,这是一种基于 Transformer 的 T2I 扩散模型,其图像生成质量与最先进的图像生成器(例如,Imagen、SDXL,甚至 Midjourney)相媲美,达到了接近商业应用的标准。此外,如图 1 和图 2 所示,它支持高达 1024px 分辨率的高分辨率图像合成,且训练成本较低。为了实现这一目标,我们提出了三个核心设计:(1)训练策略分解:我们设计了三个不同的训练步骤,分别优化像素依赖性、文本-图像对齐和图像美学质量;(2)高效的 T2I Transformer:我们将交叉注意力模块融入扩散 Transformer (DiT) 中,以注入文本条件并简化计算密集型的类别条件分支;(3)高信息量数据:我们强调文本-图像对中概念密度的重要性,并利用大型视觉-语言模型自动标注密集伪标题,以辅助文本-图像对齐学习。结果表明,PIXART-α 的训练速度明显超过现有的大型 T2I 模型,例如,PIXART-α 仅需 Stable Diffusion v1.5 训练时间的 10.8%(675 vs. 6,250 A100 GPU 天),节省了近 30 万美元(2.6 万美元 vs. 32 万美元),并减少了 90% 的二氧化碳排放。此外,与更大的 SOTA 模型 RAPHAEL 相比,我们的训练成本仅为 1%。 广泛的实验表明,PIXART-α 在图像质量、艺术性和语义控制方面表现出色。我们希望 PIXART-α 将为 AIGC 社区和初创公司提供新的见解,以加速从头开始构建他们自己的高质量且低成本的生成模型。
你可以在 PixArt-alpha/PixArt-alpha 找到原始代码库,并在 PixArt-alpha 找到所有可用的检查点。
关于此 pipeline 的一些注意事项
- 它使用 Transformer 主干(而不是 UNet)进行去噪。因此,它具有与 DiT 类似的架构。
- 它使用从 T5 计算的文本条件进行训练。 这使得该 pipeline 更擅长遵循具有复杂细节的复杂文本提示。
- 它擅长生成不同宽高比的高分辨率图像。 为了获得最佳效果,作者推荐了一些尺寸范围,可以在 这里 找到。
- 它在质量上可以媲美(截至撰写本文时)最先进的文本到图像生成系统,如 Stable Diffusion XL、Imagen 和 DALL-E 2,同时效率更高。
请务必查阅调度器指南,了解如何探索调度器速度和质量之间的权衡,并查看跨 pipelines 重用组件部分,了解如何有效地将相同组件加载到多个 pipelines 中。
在低于 8GB GPU 显存的情况下进行推理
通过以 8 位精度加载文本编码器,在低于 8GB GPU 显存的情况下运行 PixArtAlphaPipeline。让我们来看一个完整的示例。
首先,安装 bitsandbytes 库
pip install -U bitsandbytes
然后以 8 位加载文本编码器
from transformers import T5EncoderModel
from diffusers import PixArtAlphaPipeline
import torch
text_encoder = T5EncoderModel.from_pretrained(
"PixArt-alpha/PixArt-XL-2-1024-MS",
subfolder="text_encoder",
load_in_8bit=True,
device_map="auto",
)
pipe = PixArtAlphaPipeline.from_pretrained(
"PixArt-alpha/PixArt-XL-2-1024-MS",
text_encoder=text_encoder,
transformer=None,
device_map="auto"
)
现在,使用 pipe
来编码 prompt
with torch.no_grad():
prompt = "cute cat"
prompt_embeds, prompt_attention_mask, negative_embeds, negative_prompt_attention_mask = pipe.encode_prompt(prompt)
由于已计算出文本嵌入,请从内存中移除 text_encoder
和 pipe
,并释放一些 GPU 显存
import gc
def flush():
gc.collect()
torch.cuda.empty_cache()
del text_encoder
del pipe
flush()
然后使用 prompt 嵌入作为输入来计算 latents
pipe = PixArtAlphaPipeline.from_pretrained(
"PixArt-alpha/PixArt-XL-2-1024-MS",
text_encoder=None,
torch_dtype=torch.float16,
).to("cuda")
latents = pipe(
negative_prompt=None,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
prompt_attention_mask=prompt_attention_mask,
negative_prompt_attention_mask=negative_prompt_attention_mask,
num_images_per_prompt=1,
output_type="latent",
).images
del pipe.transformer
flush()
请注意,在初始化 pipe
时,您将 text_encoder
设置为 None
,以便不加载它。
一旦计算出 latents,将其传递给 VAE 以解码为真实图像
with torch.no_grad():
image = pipe.vae.decode(latents / pipe.vae.config.scaling_factor, return_dict=False)[0]
image = pipe.image_processor.postprocess(image, output_type="pil")[0]
image.save("cat.png")
通过删除您不使用的组件并清理 GPU 显存,您应该能够在低于 8GB GPU 显存的情况下运行 PixArtAlphaPipeline。
如果您想要内存使用情况报告,请运行此脚本。
以 8 位计算的文本嵌入会影响生成图像的质量,因为降低的精度会导致表示空间中的信息丢失。建议比较使用和不使用 8 位的输出。
在加载 text_encoder
时,您将 load_in_8bit
设置为 True
。您还可以指定 load_in_4bit
,以进一步将内存需求降低到 7GB 以下。
PixArtAlphaPipeline
class diffusers.PixArtAlphaPipeline
< source >( tokenizer: T5Tokenizer text_encoder: T5EncoderModel vae: AutoencoderKL transformer: PixArtTransformer2DModel scheduler: DPMSolverMultistepScheduler )
参数
- vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为 latent 表示。
- text_encoder (
T5EncoderModel
) — 冻结的文本编码器。PixArt-Alpha 使用 T5,特别是 t5-v1_1-xxl 变体。 - tokenizer (
T5Tokenizer
) — T5Tokenizer 类的分词器。 - transformer (PixArtTransformer2DModel) — 文本条件
PixArtTransformer2DModel
,用于对编码的图像 latents 进行去噪。 - scheduler (SchedulerMixin) — 调度器,与
transformer
结合使用,以对编码的图像 latents 进行去噪。
使用 PixArt-Alpha 进行文本到图像生成的 Pipeline。
此模型继承自 DiffusionPipeline。查看超类文档,了解库为所有 pipelines 实现的通用方法(例如,下载或保存、在特定设备上运行等)。
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None negative_prompt: str = '' num_inference_steps: int = 20 timesteps: typing.List[int] = None sigmas: typing.List[float] = None guidance_scale: float = 4.5 num_images_per_prompt: typing.Optional[int] = 1 height: typing.Optional[int] = None width: typing.Optional[int] = None eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None prompt_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: int = 1 clean_caption: bool = True use_resolution_binning: bool = True max_sequence_length: int = 120 **kwargs ) → ImagePipelineOutput 或 tuple
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的 prompt 或 prompts。如果未定义,则必须传递prompt_embeds
代替。 - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的 prompt 或 prompts。如果未定义,则必须传递negative_prompt_embeds
代替。不使用 guidance 时忽略(即,如果guidance_scale
小于1
则忽略)。 - num_inference_steps (
int
, 可选, 默认为 100) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但会牺牲更慢的推理速度。 - timesteps (
List[int]
, 可选) — 自定义 timesteps,用于支持在其set_timesteps
方法中使用timesteps
参数的调度器的去噪过程。如果未定义,则将使用传递num_inference_steps
时的默认行为。必须按降序排列。 - sigmas (
List[float]
, 可选) — 自定义 sigmas,用于支持在其set_timesteps
方法中使用sigmas
参数的调度器的去噪过程。如果未定义,则将使用传递num_inference_steps
时的默认行为。 - guidance_scale (
float
, 可选, 默认为 4.5) — Guidance scale,如无分类器扩散引导中所定义。guidance_scale
定义为 Imagen Paper 的公式 2 中的w
。通过设置guidance_scale > 1
启用 Guidance scale。更高的 guidance scale 鼓励生成与文本prompt
紧密相关的图像,但通常以降低图像质量为代价。 - num_images_per_prompt (
int
, 可选, 默认为 1) — 每个 prompt 要生成的图像数量。 - height (
int
, 可选, 默认为 self.unet.config.sample_size) — 生成图像的像素高度。 - width (
int
, 可选, 默认为 self.unet.config.sample_size) — 生成图像的像素宽度。 - eta (
float
, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η):https://arxiv.org/abs/2010.02502。仅适用于 schedulers.DDIMScheduler,将被其他调度器忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 一个或多个 torch 生成器,用于使生成具有确定性。 - latents (
torch.Tensor
, 可选) — 预生成的噪声 latents,从高斯分布中采样,用作图像生成的输入。可用于使用不同的 prompts 调整相同的生成。如果未提供,将通过使用提供的随机generator
进行采样来生成 latents 张量。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 prompt 加权。如果未提供,将从prompt
输入参数生成文本嵌入。 - prompt_attention_mask (
torch.Tensor
, 可选) — 预生成的文本嵌入的 attention mask。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本嵌入 (negative text embeddings)。对于 PixArt-Alpha,此负面提示 (negative prompt) 应为 “”。如果未提供,则 `negative_prompt_embeds` 将从 `negative_prompt` 输入参数生成。 - negative_prompt_attention_mask (
torch.Tensor
, 可选) — 负面文本嵌入 (negative text embeddings) 的预生成注意力掩码 (attention mask)。 - output_type (
str
, 可选, 默认为"pil"
) — 生成图像的输出格式。 从 PIL:PIL.Image.Image
或np.array
中选择。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回~pipelines.stable_diffusion.IFPipelineOutput
而不是普通元组 (tuple)。 - callback (
Callable
, 可选) — 一个函数,它将在推理 (inference) 期间每callback_steps
步被调用。该函数将被以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
。 - callback_steps (
int
, 可选, 默认为 1) — 调用callback
函数的频率。 如果未指定,则将在每一步调用回调。 - clean_caption (
bool
, 可选, 默认为True
) — 是否在创建嵌入 (embeddings) 之前清理标题 (caption)。 需要安装beautifulsoup4
和ftfy
。 如果未安装依赖项,则将从原始提示 (raw prompt) 创建嵌入。 - use_resolution_binning (
bool
默认为True
) — 如果设置为True
,则请求的高度和宽度将首先使用ASPECT_RATIO_1024_BIN
映射到最接近的分辨率。 在生成的潜在变量 (latents) 被解码为图像后,它们将被调整大小回到请求的分辨率。 用于生成非正方形图像非常有用。 - max_sequence_length (
int
默认为 120) — 与prompt
一起使用的最大序列长度。
返回值
ImagePipelineOutput 或 tuple
如果 return_dict
为 True
,则返回 ImagePipelineOutput,否则返回 tuple
,其中第一个元素是包含生成图像的列表
调用 pipeline 进行生成时调用的函数。
示例
>>> import torch
>>> from diffusers import PixArtAlphaPipeline
>>> # You can replace the checkpoint id with "PixArt-alpha/PixArt-XL-2-512x512" too.
>>> pipe = PixArtAlphaPipeline.from_pretrained("PixArt-alpha/PixArt-XL-2-1024-MS", torch_dtype=torch.float16)
>>> # Enable memory optimizations.
>>> pipe.enable_model_cpu_offload()
>>> prompt = "A small cactus with a happy face in the Sahara desert."
>>> image = pipe(prompt).images[0]
encode_prompt
< source >( prompt: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True negative_prompt: str = '' num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None prompt_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None clean_caption: bool = False max_sequence_length: int = 120 **kwargs )
参数
- prompt (
str
或List[str]
, 可选) — 要编码的提示 (prompt) - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的提示 (prompt)。 如果未定义,则必须传递negative_prompt_embeds
。 当不使用引导时忽略(即,如果guidance_scale
小于1
则忽略)。 对于 PixArt-Alpha,这应该为 “”。 - do_classifier_free_guidance (
bool
, 可选, 默认为True
) — 是否使用无分类器引导 (classifier free guidance)。 - num_images_per_prompt (
int
, 可选, 默认为 1) — 每个提示 (prompt) 应生成的图像数量。 - device — (
torch.device
, 可选): 用于放置结果嵌入 (embeddings) 的 torch 设备。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入 (text embeddings)。 可用于轻松调整文本输入,例如 提示权重 (prompt weighting)。 如果未提供,则将从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本嵌入 (negative text embeddings)。 对于 PixArt-Alpha,它应该是 “ ” 字符串的嵌入。 - clean_caption (
bool
, 默认为False
) — 如果为True
,该函数将在编码之前预处理和清理提供的标题 (caption)。 - max_sequence_length (
int
, 默认为 120) — 用于提示 (prompt) 的最大序列长度。
将提示 (prompt) 编码为文本编码器隐藏状态 (text encoder hidden states)。