Diffusers 文档

UniDiffuser

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

UniDiffuser

LoRA

UniDiffuser 模型由 Fan Bao, Shen Nie, Kaiwen Xue, Chongxuan Li, Shi Pu, Yaole Wang, Gang Yue, Yue Cao, Hang Su, Jun Zhu 在 One Transformer Fits All Distributions in Multi-Modal Diffusion at Scale 中提出。

论文摘要如下:

本文提出了一种统一的扩散框架(命名为 UniDiffuser),用于在一个模型中拟合与一组多模态数据相关的所有分布。我们的关键见解是——学习边缘、条件和联合分布的扩散模型可以统一为预测扰动数据中的噪声,其中不同模态的扰动级别(即时间步长)可以不同。受统一观点的启发,UniDiffuser 通过对原始扩散模型进行最小修改,同时学习所有分布——扰动所有模态的数据而不是单一模态,输入不同模态的独立时间步长,并预测所有模态的噪声而不是单一模态。UniDiffuser 由一个用于扩散模型的 Transformer 参数化,以处理不同模态的输入类型。UniDiffuser 在大规模配对图像-文本数据上实现,通过设置适当的时间步长,无需额外开销即可执行图像、文本、文本到图像、图像到文本和图像-文本对生成。特别是,UniDiffuser 能够生成所有任务中感知上真实的样本,其定量结果(例如,FID 和 CLIP 分数)不仅优于现有通用模型,而且在代表性任务(例如,文本到图像生成)中可与专用模型(例如,Stable Diffusion 和 DALL-E 2)媲美。

您可以在 thu-ml/unidiffuser 找到原始代码库,在 thu-ml 找到其他检查点。

PyTorch 1.X 目前存在一个问题,即输出图像全黑或像素值变为 NaNs。通过切换到 PyTorch 2.X 可以缓解此问题。

此流水线由 dg845 贡献。❤️

使用示例

由于 UniDiffuser 模型经过训练以对(图像、文本)对的联合分布进行建模,因此它能够执行各种生成任务

无条件图像和文本生成

UniDiffuserPipeline 进行无条件生成(我们仅从标准高斯先验中采样的潜在空间开始)将生成一个(图像,文本)对

import torch

from diffusers import UniDiffuserPipeline

device = "cuda"
model_id_or_path = "thu-ml/unidiffuser-v1"
pipe = UniDiffuserPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
pipe.to(device)

# Unconditional image and text generation. The generation task is automatically inferred.
sample = pipe(num_inference_steps=20, guidance_scale=8.0)
image = sample.images[0]
text = sample.text[0]
image.save("unidiffuser_joint_sample_image.png")
print(text)

这在 UniDiffuser 论文中也称为“联合”生成,因为我们从联合图像-文本分布中进行采样。

请注意,生成任务是从调用流水线时使用的输入推断出来的。也可以使用 UniDiffuserPipeline.set_joint_mode() 手动指定无条件生成任务(“模式”)。

# Equivalent to the above.
pipe.set_joint_mode()
sample = pipe(num_inference_steps=20, guidance_scale=8.0)

手动设置模式后,对流水线的后续调用将使用所设置的模式,而不会尝试推断模式。您可以使用 UniDiffuserPipeline.reset_mode() 重置模式,之后流水线将再次推断模式。

您也可以只生成图像或只生成文本(UniDiffuser 论文称之为“边缘”生成,因为我们分别从图像和文本的边缘分布中采样)

# Unlike other generation tasks, image-only and text-only generation don't use classifier-free guidance
# Image-only generation
pipe.set_image_mode()
sample_image = pipe(num_inference_steps=20).images[0]
# Text-only generation
pipe.set_text_mode()
sample_text = pipe(num_inference_steps=20).text[0]

文本到图像生成

UniDiffuser 也能够从条件分布中采样;也就是说,给定文本提示的图像分布,或给定图像的文本分布。以下是条件图像分布采样的示例(文本到图像生成或文本条件图像生成)

import torch

from diffusers import UniDiffuserPipeline

device = "cuda"
model_id_or_path = "thu-ml/unidiffuser-v1"
pipe = UniDiffuserPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
pipe.to(device)

# Text-to-image generation
prompt = "an elephant under the sea"

sample = pipe(prompt=prompt, num_inference_steps=20, guidance_scale=8.0)
t2i_image = sample.images[0]
t2i_image

text2img 模式要求提供输入 promptprompt_embeds。您可以使用 UniDiffuserPipeline.set_text_to_image_mode() 手动设置 text2img 模式。

图像到文本生成

同样,UniDiffuser 也可以根据图像生成文本样本(图像到文本或图像条件文本生成)

import torch

from diffusers import UniDiffuserPipeline
from diffusers.utils import load_image

device = "cuda"
model_id_or_path = "thu-ml/unidiffuser-v1"
pipe = UniDiffuserPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
pipe.to(device)

# Image-to-text generation
image_url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unidiffuser/unidiffuser_example_image.jpg"
init_image = load_image(image_url).resize((512, 512))

sample = pipe(image=init_image, num_inference_steps=20, guidance_scale=8.0)
i2t_text = sample.text[0]
print(i2t_text)

img2text 模式要求提供输入 image。您可以使用 UniDiffuserPipeline.set_image_to_text_mode() 手动设置 img2text 模式。

图像变体

UniDiffuser 作者建议通过“往返”生成方法执行图像变体,即给定输入图像,我们首先执行图像到文本生成,然后对第一次生成的输出执行文本到图像生成。这会生成与输入图像语义相似的新图像

import torch

from diffusers import UniDiffuserPipeline
from diffusers.utils import load_image

device = "cuda"
model_id_or_path = "thu-ml/unidiffuser-v1"
pipe = UniDiffuserPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
pipe.to(device)

# Image variation can be performed with an image-to-text generation followed by a text-to-image generation:
# 1. Image-to-text generation
image_url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unidiffuser/unidiffuser_example_image.jpg"
init_image = load_image(image_url).resize((512, 512))

sample = pipe(image=init_image, num_inference_steps=20, guidance_scale=8.0)
i2t_text = sample.text[0]
print(i2t_text)

# 2. Text-to-image generation
sample = pipe(prompt=i2t_text, num_inference_steps=20, guidance_scale=8.0)
final_image = sample.images[0]
final_image.save("unidiffuser_image_variation_sample.png")

文本变体

同样,文本变体可以通过文本到图像生成,然后图像到文本生成在输入提示上执行

import torch

from diffusers import UniDiffuserPipeline

device = "cuda"
model_id_or_path = "thu-ml/unidiffuser-v1"
pipe = UniDiffuserPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
pipe.to(device)

# Text variation can be performed with a text-to-image generation followed by a image-to-text generation:
# 1. Text-to-image generation
prompt = "an elephant under the sea"

sample = pipe(prompt=prompt, num_inference_steps=20, guidance_scale=8.0)
t2i_image = sample.images[0]
t2i_image.save("unidiffuser_text2img_sample_image.png")

# 2. Image-to-text generation
sample = pipe(image=t2i_image, num_inference_steps=20, guidance_scale=8.0)
final_prompt = sample.text[0]
print(final_prompt)

请务必查看调度器 指南,了解如何探索调度器速度和质量之间的权衡,并查看 在流水线之间重用组件 部分,了解如何高效地将相同组件加载到多个流水线中。

UniDiffuserPipeline

class diffusers.UniDiffuserPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel image_encoder: CLIPVisionModelWithProjection clip_image_processor: CLIPImageProcessor clip_tokenizer: CLIPTokenizer text_decoder: UniDiffuserTextDecoder text_tokenizer: GPT2Tokenizer unet: UniDiffuserModel scheduler: KarrasDiffusionSchedulers )

参数

  • vae (AutoencoderKL) — 用于将图像编码和解码为潜在表示的变分自编码器 (VAE) 模型。这是 UniDiffuser 图像表示的一部分,以及 CLIP 视觉编码。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
  • image_encoder (CLIPVisionModel) — 一个 CLIPVisionModel,用于将图像编码为图像表示的一部分,以及 VAE 潜在表示。
  • image_processor (CLIPImageProcessor) — CLIPImageProcessor,用于在用 image_encoder 进行 CLIP 编码之前预处理图像。
  • clip_tokenizer (CLIPTokenizer) — 一个 CLIPTokenizer,用于在用 text_encoder 编码提示之前对提示进行标记化。
  • text_decoder (UniDiffuserTextDecoder) — 冻结的文本解码器。这是一个 GPT 风格的模型,用于从 UniDiffuser 嵌入生成文本。
  • text_tokenizer (GPT2Tokenizer) — 一个 GPT2Tokenizer,用于文本生成中的文本解码;与 text_decoder 一起使用。
  • unet (UniDiffuserModel) — 一个 U-ViT 模型,具有 UNNet 风格的 Transformer 层之间的跳跃连接,用于对编码后的图像潜在表示进行去噪。
  • scheduler (SchedulerMixin) — 一个与 unet 结合使用的调度器,用于对编码后的图像和/或文本潜在表示进行去噪。原始的 UniDiffuser 论文使用 DPMSolverMultistepScheduler 调度器。

用于双模态图像-文本模型的流水线,支持无条件文本和图像生成、文本条件图像生成、图像条件文本生成以及联合图像-文本生成。

此模型继承自 DiffusionPipeline。有关所有流水线通用的方法(下载、保存、在特定设备上运行等),请查看超类文档。

__call__

< >

( prompt: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[torch.Tensor, PIL.Image.Image, NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None data_type: typing.Optional[int] = 1 num_inference_steps: int = 50 guidance_scale: float = 8.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 num_prompts_per_image: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_latents: typing.Optional[torch.Tensor] = None vae_latents: typing.Optional[torch.Tensor] = None clip_latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: 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 ) ImageTextPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示。如果未定义,则需要传递 prompt_embeds。文本条件图像生成 (text2img) 模式所必需。
  • image (torch.TensorPIL.Image.Image, 可选) — Image 或表示图像批次的张量。图像条件文本生成 (img2text) 模式所必需。
  • height (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度(像素)。
  • width (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度(像素)。
  • data_type (int, 可选, 默认为 1) — 数据类型(0 或 1)。仅当您加载支持数据类型嵌入的检查点时使用;这为了与 UniDiffuser-v1 检查点兼容而添加。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步数。更多的去噪步数通常会带来更高质量的图像,但推理速度会变慢。
  • guidance_scale (float, 可选, 默认为 8.0) — 较高的引导比例值鼓励模型生成与文本 prompt 紧密相关的图像,但会以较低的图像质量为代价。当 guidance_scale > 1 时启用引导比例。
  • negative_prompt (strList[str], 可选) — 用于引导图像生成中不包含内容的提示。如果未定义,则需要传递 negative_prompt_embeds。当不使用引导时 (guidance_scale < 1) 忽略。在文本条件图像生成 (text2img) 模式下使用。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示要生成的图像数量。在 text2img(文本条件图像生成)和 img 模式下使用。如果模式为 joint 且同时提供了 num_images_per_promptnum_prompts_per_image,则生成 min(num_images_per_prompt, num_prompts_per_image) 个样本。
  • num_prompts_per_image (int, 可选, 默认为 1) — 每张图像生成的提示数量。用于 img2text(图像条件文本生成)和 text 模式。如果模式为联合模式,并且同时提供了 num_images_per_promptnum_prompts_per_image,则生成 min(num_images_per_prompt, num_prompts_per_image) 个样本。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成具有确定性的 torch.Generator
  • latents (torch.Tensor, 可选) — 预先生成的噪声潜在变量,从高斯分布中采样,用作联合图像-文本生成的输入。可用于使用不同的提示微调相同的生成。如果未提供,则使用提供的随机 generator 进行采样生成一个潜在变量张量。这假定提供了一整套 VAE、CLIP 和文本潜在变量,如果提供了,则会覆盖 prompt_latentsvae_latentsclip_latents 的值。
  • prompt_latents (torch.Tensor, 可选) — 预先生成的噪声潜在变量,从高斯分布中采样,用作文本生成的输入。可用于使用不同的提示微调相同的生成。如果未提供,则使用提供的随机 generator 进行采样生成一个潜在变量张量。
  • vae_latents (torch.Tensor, 可选) — 预先生成的噪声潜在变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示微调相同的生成。如果未提供,则使用提供的随机 generator 进行采样生成一个潜在变量张量。
  • clip_latents (torch.Tensor, 可选) — 预先生成的噪声潜在变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示微调相同的生成。如果未提供,则使用提供的随机 generator 进行采样生成一个潜在变量张量。
  • prompt_embeds (torch.Tensor, 可选) — 预先生成的文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,文本嵌入将从 prompt 输入参数生成。用于文本条件图像生成(text2img)模式。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预先生成的负面文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。用于文本条件图像生成(text2img)模式。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。选择 PIL.Imagenp.array
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ImageTextPipelineOutput 而不是普通元组。
  • callback (Callable, 可选) — 在推理过程中每 callback_steps 步调用的函数。该函数以以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可选, 默认为 1) — callback 函数被调用的频率。如果未指定,则在每一步都调用回调。

返回

ImageTextPipelineOutputtuple

如果 return_dictTrue,则返回 ImageTextPipelineOutput,否则返回一个 tuple,其中第一个元素是生成的图像列表,第二个元素是生成的文本列表。

用于生成的管道的调用函数。

disable_vae_slicing

< >

( )

禁用切片 VAE 解码。如果之前启用了 enable_vae_slicing,此方法将返回一步计算解码。

disable_vae_tiling

< >

( )

禁用平铺 VAE 解码。如果之前启用了 enable_vae_tiling,此方法将恢复一步计算解码。

enable_vae_slicing

< >

( )

启用切片 VAE 解码。启用此选项后,VAE 会将输入张量分片,分步计算解码。这有助于节省一些内存并允许更大的批次大小。

enable_vae_tiling

< >

( )

启用平铺 VAE 解码。启用此选项后,VAE 将把输入张量分割成瓦片,分多步计算编码和解码。这对于节省大量内存和处理更大的图像非常有用。

encode_prompt

< >

( prompt device num_images_per_prompt do_classifier_free_guidance negative_prompt: typing.Optional[typing.Union[str, typing.List[str]]] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

参数

  • prompt (strList[str], 可选) — 待编码的提示
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用分类器无关引导
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示。如果未定义,则必须传递 negative_prompt_embeds。当不使用引导时(即,如果 guidance_scale 小于 1 时)将被忽略。
  • prompt_embeds (torch.Tensor, 可选) — 预先生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预先生成的负面文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • lora_scale (float, 可选) — 应用于文本编码器所有 LoRA 层的 LoRA 比例(如果加载了 LoRA 层)。
  • clip_skip (int, 可选) — 计算提示嵌入时从 CLIP 跳过的层数。值为 1 表示使用倒数第二层的输出计算提示嵌入。

将提示编码为文本编码器隐藏状态。

reset_mode

< >

( )

移除手动设置的模式;调用此函数后,管道将从输入推断模式。

set_image_mode

< >

( )

手动将生成模式设置为无条件(“边际”)图像生成。

set_image_to_text_mode

< >

( )

手动将生成模式设置为图像条件文本生成。

set_joint_mode

< >

( )

手动将生成模式设置为无条件联合图像-文本生成。

set_text_mode

< >

( )

手动将生成模式设置为无条件(“边际”)文本生成。

set_text_to_image_mode

< >

( )

手动将生成模式设置为文本条件图像生成。

ImageTextPipelineOutput

class diffusers.ImageTextPipelineOutput

< >

( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray, NoneType] text: typing.Union[typing.List[str], typing.List[typing.List[str]], NoneType] )

参数

  • images (List[PIL.Image.Image]np.ndarray) — 长度为 batch_size 的去噪 PIL 图像列表或形状为 (batch_size, height, width, num_channels) 的 NumPy 数组。
  • text (List[str]List[List[str]]) — 长度为 batch_size 的生成文本字符串列表,或者一个列表的列表,其中外部列表的长度为 batch_size

联合图像-文本管道的输出类。

< > 在 GitHub 上更新