Diffusers 文档
PixArt-Σ
并获得增强的文档体验
开始使用
PixArt-Σ
PixArt-Σ:扩散 Transformer 的从弱到强训练,用于 4K 文本到图像生成 由 Junsong Chen、Jincheng Yu、Chongjian Ge、Lewei Yao、Enze Xie、Yue Wu、Zhongdao Wang、James Kwok、Ping Luo、Huchuan Lu 和 Zhenguo Li 撰写。
论文摘要如下:
在本文中,我们介绍了 PixArt-Σ,一个能够直接生成 4K 分辨率图像的扩散 Transformer 模型(DiT)。PixArt-Σ 相较于其前身 PixArt-α 取得了显著进步,提供了更高保真度的图像并改善了与文本提示的对齐。PixArt-Σ 的一个关键特性是其训练效率。它利用 PixArt-α 的基础预训练,通过整合更高质量的数据,从“较弱”的基线模型演变为“更强”的模型,我们称之为“从弱到强训练”。PixArt-Σ 的进步体现在两个方面:(1)高质量训练数据:PixArt-Σ 采用了更高质量的图像数据,并配以更精确和详细的图像字幕。(2)高效 Token 压缩:我们提出了 DiT 框架内的一种新颖的注意力模块,它能同时压缩键和值,显著提高了效率并促进了超高分辨率图像的生成。由于这些改进,PixArt-Σ 在显著小于现有文本到图像扩散模型(如 SDXL (2.6B 参数) 和 SD Cascade (5.1B 参数))的模型尺寸(0.6B 参数)下,实现了卓越的图像质量和用户提示一致性能力。此外,PixArt-Σ 生成 4K 图像的能力支持创建高分辨率海报和壁纸,有效促进了电影和游戏等行业高质量视觉内容的生产。
您可以在 PixArt-alpha/PixArt-sigma 找到原始代码库,在 PixArt-alpha 找到所有可用的检查点。
关于此管道的一些注意事项
- 它使用 Transformer 主干(而不是 UNet)进行去噪。因此,它的架构与 DiT 相似。
- 它使用从 T5 计算的文本条件进行训练。这使得该管道更擅长遵循具有复杂细节的复杂文本提示。
- 它擅长生成不同纵横比的高分辨率图像。为了获得最佳结果,作者推荐了一些尺寸范围,可以在这里找到。
- 它在质量上与当前最先进的文本到图像生成系统(截至本文撰写时)如 PixArt-α、Stable Diffusion XL、Playground V2.0 和 DALL-E 3 相媲美,同时比它们更高效。
- 它展示了生成超高分辨率图像的能力,例如 2048px 甚至 4K。
- 它表明文本到图像模型可以通过一些改进(VAEs、数据集等)从一个弱模型发展成为一个更强的模型。
您可以将 PixArtSigmaPipeline 生成的图像传递给 SDXL 细化器模型,进一步提高生成质量。
使用低于 8GB GPU 显存进行推理
通过以 8 位精度加载文本编码器,您可以使用低于 8GB GPU 显存运行 PixArtSigmaPipeline。我们来看一个完整的示例。
首先,安装 bitsandbytes 库
pip install -U bitsandbytes
然后以 8 位加载文本编码器
from transformers import T5EncoderModel
from diffusers import PixArtSigmaPipeline
import torch
text_encoder = T5EncoderModel.from_pretrained(
"PixArt-alpha/PixArt-Sigma-XL-2-1024-MS",
subfolder="text_encoder",
load_in_8bit=True,
device_map="auto",
)
pipe = PixArtSigmaPipeline.from_pretrained(
"PixArt-alpha/PixArt-Sigma-XL-2-1024-MS",
text_encoder=text_encoder,
transformer=None,
device_map="balanced"
)
现在,使用 pipe
对提示进行编码
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()
然后使用提示嵌入作为输入计算潜在变量
pipe = PixArtSigmaPipeline.from_pretrained(
"PixArt-alpha/PixArt-Sigma-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
,这样它就不会被加载。
一旦潜在变量计算完毕,将其传递给 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 显存的情况下运行 PixArtSigmaPipeline。
如果您想要内存使用报告,请运行此 脚本。
以 8 位计算的文本嵌入可能会影响生成图像的质量,因为精度降低导致表示空间中的信息丢失。建议比较 8 位和非 8 位输出。
加载 text_encoder
时,您将 load_in_8bit
设置为 True
。您也可以指定 load_in_4bit
以进一步将内存需求降至 7GB 以下。
PixArtSigmaPipeline
class diffusers.PixArtSigmaPipeline
< 来源 >( tokenizer: T5Tokenizer text_encoder: T5EncoderModel vae: AutoencoderKL transformer: PixArtTransformer2DModel scheduler: KarrasDiffusionSchedulers )
用于文本到图像生成的 PixArt-Sigma 管道。
__call__
< 来源 >( 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 = 300 **kwargs ) → ImagePipelineOutput 或 tuple
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的提示词。如果未定义,则必须传递prompt_embeds
。 - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的提示词。如果未定义,则必须传递negative_prompt_embeds
。当不使用引导时(即,如果guidance_scale
小于1
),此参数将被忽略。 - num_inference_steps (
int
, 可选, 默认为 100) — 去噪步数。更多去噪步数通常会带来更高质量的图像,但推理速度会变慢。 - timesteps (
List[int]
, 可选) — 用于去噪过程的自定义时间步长,适用于支持set_timesteps
方法中timesteps
参数的调度器。如果未定义,将使用传递num_inference_steps
时的默认行为。必须按降序排列。 - sigmas (
List[float]
, 可选) — 用于去噪过程的自定义 σ 值,适用于支持set_timesteps
方法中sigmas
参数的调度器。如果未定义,将使用传递num_inference_steps
时的默认行为。 - guidance_scale (
float
, 可选, 默认为 4.5) — 如 无分类器引导扩散 中定义的引导比例。guidance_scale
定义为 Imagen 论文 中公式 2 的w
。通过设置guidance_scale > 1
来启用引导比例。更高的引导比例会促使生成与文本prompt
紧密相关的图像,通常以牺牲较低图像质量为代价。 - num_images_per_prompt (
int
, 可选, 默认为 1) — 每个提示词生成的图像数量。 - height (
int
, 可选, 默认为 self.unet.config.sample_size) — 生成图像的像素高度。 - width (
int
, 可选, 默认为 self.unet.config.sample_size) — 生成图像的像素宽度。 - eta (
float
, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η):https://huggingface.co/papers/2010.02502。仅适用于 schedulers.DDIMScheduler,对其他调度器将被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 一个或多个 torch 生成器,用于使生成确定性。 - latents (
torch.Tensor
, 可选) — 预先生成的噪声潜在变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同提示词调整同一生成。如果未提供,将使用提供的随机generator
采样生成潜在变量张量。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,文本嵌入将从prompt
输入参数生成。 - prompt_attention_mask (
torch.Tensor
, 可选) — 文本嵌入的预生成注意力掩码。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本嵌入。对于 PixArt-Sigma,这个负面提示词应该是 ""。如果未提供,negative_prompt_embeds
将从negative_prompt
输入参数生成。 - negative_prompt_attention_mask (
torch.Tensor
, 可选) — 负面文本嵌入的预生成注意力掩码。 - output_type (
str
, 可选, 默认为"pil"
) — 生成图像的输出格式。在 PIL:PIL.Image.Image
或np.array
之间选择。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回~pipelines.stable_diffusion.IFPipelineOutput
而不是普通元组。 - callback (
Callable
, 可选) — 在推理过程中,每隔callback_steps
步调用的函数。该函数将使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
。 - callback_steps (
int
, 可选, 默认为 1) —callback
函数被调用的频率。如果未指定,回调将在每一步都被调用。 - clean_caption (
bool
, 可选, 默认为True
) — 是否在创建嵌入之前清理标题。需要安装beautifulsoup4
和ftfy
。如果未安装这些依赖项,嵌入将从原始提示词创建。 - use_resolution_binning (
bool
默认为True
) — 如果设置为True
,则首先使用ASPECT_RATIO_1024_BIN
将请求的高度和宽度映射到最接近的分辨率。生成的潜在变量解码为图像后,会将其大小调整回请求的分辨率。有助于生成非方形图像。 - max_sequence_length (
int
默认为 300) — 与prompt
一起使用的最大序列长度。
返回
ImagePipelineOutput 或 tuple
如果 return_dict
为 True
,则返回 ImagePipelineOutput,否则返回一个 tuple
,其中第一个元素是生成的图像列表
调用管道进行生成时调用的函数。
示例
>>> import torch
>>> from diffusers import PixArtSigmaPipeline
>>> # You can replace the checkpoint id with "PixArt-alpha/PixArt-Sigma-XL-2-512-MS" too.
>>> pipe = PixArtSigmaPipeline.from_pretrained(
... "PixArt-alpha/PixArt-Sigma-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
< 源文件 >( 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 = 300 **kwargs )
参数
- prompt (
str
或List[str]
, 可选) — 待编码的提示词 - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的提示词。如果未定义,则必须传入negative_prompt_embeds
。当不使用引导时(即,如果guidance_scale
小于1
时被忽略)。对于 PixArt-Alpha,这应该是空字符串 “”。 - do_classifier_free_guidance (
bool
, 可选, 默认为True
) — 是否使用分类器自由引导。 - num_images_per_prompt (
int
, 可选, 默认为 1) — 每个提示词应生成的图像数量。 - device — (
torch.device
, 可选): 放置结果嵌入的 torch 设备。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,将从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本嵌入。对于 PixArt-Alpha,它应该是 “” 字符串的嵌入。 - clean_caption (
bool
, 默认为False
) — 如果为True
,函数将在编码前预处理和清理提供的标题。 - max_sequence_length (
int
, 默认为 300) — 用于提示词的最大序列长度。
将提示编码为文本编码器隐藏状态。