Diffusers 文档

Stable unCLIP

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

Stable unCLIP

Stable unCLIP 检查点是从 Stable Diffusion 2.1 检查点微调而来,以 CLIP 图像嵌入为条件。Stable unCLIP 仍然以文本嵌入为条件。鉴于这两个独立的条件,stable unCLIP 可以用于文本引导的图像变体。当与 unCLIP prior 结合使用时,它也可以用于完整的文本到图像生成。

论文摘要如下:

像 CLIP 这样的对比模型已被证明可以学习图像的鲁棒表示,这些表示既捕捉语义又捕捉风格。为了利用这些表示进行图像生成,我们提出了一个两阶段模型:一个 prior,它根据文本标题生成 CLIP 图像嵌入;以及一个解码器,它根据图像嵌入生成图像。我们表明,显式生成图像表示可以提高图像多样性,同时最大限度地减少照片真实感和标题相似性的损失。我们的以图像表示为条件的解码器还可以生成图像的变体,这些变体保留了其语义和风格,同时改变了图像表示中不存在的非必要细节。此外,CLIP 的联合嵌入空间支持以零样本方式进行语言引导的图像操作。我们对解码器使用扩散模型,并对 prior 使用自回归模型和扩散模型进行实验,发现后者在计算上更有效率,并产生更高质量的样本。

提示

Stable unCLIP 在推理时将 noise_level 作为输入,这决定了添加到图像嵌入的噪声量。较高的 noise_level 会增加最终去噪图像的变化。默认情况下,我们不会向图像嵌入添加任何额外的噪声 (noise_level = 0)。

文本到图像生成

Stable unCLIP 可以通过将其与 KakaoBrain 开源 DALL-E 2 复制品 Karlo 的 prior 模型进行流水线连接,从而用于文本到图像生成。

import torch
from diffusers import UnCLIPScheduler, DDPMScheduler, StableUnCLIPPipeline
from diffusers.models import PriorTransformer
from transformers import CLIPTokenizer, CLIPTextModelWithProjection

prior_model_id = "kakaobrain/karlo-v1-alpha"
data_type = torch.float16
prior = PriorTransformer.from_pretrained(prior_model_id, subfolder="prior", torch_dtype=data_type)

prior_text_model_id = "openai/clip-vit-large-patch14"
prior_tokenizer = CLIPTokenizer.from_pretrained(prior_text_model_id)
prior_text_model = CLIPTextModelWithProjection.from_pretrained(prior_text_model_id, torch_dtype=data_type)
prior_scheduler = UnCLIPScheduler.from_pretrained(prior_model_id, subfolder="prior_scheduler")
prior_scheduler = DDPMScheduler.from_config(prior_scheduler.config)

stable_unclip_model_id = "stabilityai/stable-diffusion-2-1-unclip-small"

pipe = StableUnCLIPPipeline.from_pretrained(
    stable_unclip_model_id,
    torch_dtype=data_type,
    variant="fp16",
    prior_tokenizer=prior_tokenizer,
    prior_text_encoder=prior_text_model,
    prior=prior,
    prior_scheduler=prior_scheduler,
)

pipe = pipe.to("cuda")
wave_prompt = "dramatic wave, the Oceans roar, Strong wave spiral across the oceans as the waves unfurl into roaring crests; perfect wave form; perfect wave shape; dramatic wave shape; wave shape unbelievable; wave; wave shape spectacular"

image = pipe(prompt=wave_prompt).images[0]
image

对于文本到图像,我们使用 stabilityai/stable-diffusion-2-1-unclip-small,因为它是在 CLIP ViT-L/14 嵌入上训练的,与 Karlo 模型 prior 相同。stabilityai/stable-diffusion-2-1-unclip 是在 OpenCLIP ViT-H 上训练的,因此我们不建议使用它。

文本引导的图像到图像变异

from diffusers import StableUnCLIPImg2ImgPipeline
from diffusers.utils import load_image
import torch

pipe = StableUnCLIPImg2ImgPipeline.from_pretrained(
    "stabilityai/stable-diffusion-2-1-unclip", torch_dtype=torch.float16, variation="fp16"
)
pipe = pipe.to("cuda")

url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/tarsila_do_amaral.png"
init_image = load_image(url)

images = pipe(init_image).images
images[0].save("variation_image.png")

可选地,您还可以将提示传递给 pipe,例如

prompt = "A fantasy landscape, trending on artstation"

image = pipe(init_image, prompt=prompt).images[0]
image

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

StableUnCLIPPipeline

class diffusers.StableUnCLIPPipeline

< >

( prior_tokenizer: CLIPTokenizer prior_text_encoder: CLIPTextModelWithProjection prior: PriorTransformer prior_scheduler: KarrasDiffusionSchedulers image_normalizer: StableUnCLIPImageNormalizer image_noising_scheduler: KarrasDiffusionSchedulers tokenizer: CLIPTokenizer text_encoder: CLIPTextModelWithProjection unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers vae: AutoencoderKL )

参数

  • prior_tokenizer (CLIPTokenizer) — 一个 CLIPTokenizer
  • prior_text_encoder (CLIPTextModelWithProjection) — 冻结的 CLIPTextModelWithProjection 文本编码器。
  • prior (PriorTransformer) — 规范的 unCLIP 先验模型,用于从文本嵌入近似图像嵌入。
  • prior_scheduler (KarrasDiffusionSchedulers) — 先验去噪过程中使用的调度器。
  • image_normalizer (StableUnCLIPImageNormalizer) — 用于在应用噪声之前标准化预测的图像嵌入,并在应用噪声之后反标准化图像嵌入。
  • image_noising_scheduler (KarrasDiffusionSchedulers) — 用于向预测的图像嵌入添加噪声的噪声调度器。要添加的噪声量由 noise_level 确定。
  • tokenizer (CLIPTokenizer) — 一个 CLIPTokenizer
  • text_encoder (CLIPTextModel) — 冻结的 CLIPTextModel 文本编码器。
  • unet (UNet2DConditionModel) — 用于去噪编码图像潜在空间的 UNet2DConditionModel
  • scheduler (KarrasDiffusionSchedulers) — 与 unet 结合使用的调度器,用于去噪编码图像潜在空间。
  • vae (AutoencoderKL) — 变分自动编码器 (VAE) 模型,用于将图像编码和解码为潜在表示。

使用 stable unCLIP 进行文本到图像生成的 Pipeline。

此模型继承自 DiffusionPipeline。查看超类文档以获取为所有管道实现的通用方法(下载、保存、在特定设备上运行等)。

该 pipeline 还继承了以下加载方法

__call__

< >

( prompt: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 20 guidance_scale: float = 10.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Optional[torch._C.Generator] = None 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 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None noise_level: int = 0 prior_num_inference_steps: int = 25 prior_guidance_scale: float = 4.0 prior_latents: typing.Optional[torch.Tensor] = None clip_skip: typing.Optional[int] = None ) ImagePipelineOutput or tuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示。如果未定义,则需要传递 prompt_embeds
  • height (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度,以像素为单位。
  • width (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度,以像素为单位。
  • num_inference_steps (int, 可选, 默认为 20) — 去噪步骤的数量。更多去噪步骤通常会带来更高质量的图像,但会牺牲较慢的推理速度。
  • guidance_scale (float, 可选, 默认为 10.0) — 更高的 guidance scale 值会鼓励模型生成与文本 prompt 紧密相关的图像,但会牺牲较低的图像质量。当 guidance_scale > 1 时,guidance scale 生效。
  • negative_prompt (strList[str], 可选) — 用于引导图像生成中不应包含的内容的提示。如果未定义,则需要传递 negative_prompt_embeds 代替。当不使用 guidance 时(guidance_scale < 1),将被忽略。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示要生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中将被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成过程具有确定性的 torch.Generator
  • latents (torch.Tensor, 可选) — 预生成的、从高斯分布中采样的噪声潜在变量,用作图像生成的输入。可用于通过不同的提示调整相同的生成结果。如果未提供,则会使用提供的随机 generator 采样生成潜在变量张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则会从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则会从 negative_prompt 输入参数生成 negative_prompt_embeds
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。在 PIL.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ImagePipelineOutput 而不是普通元组。
  • callback (Callable, 可选) — 在推理过程中每 callback_steps 步调用的函数。该函数使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可选, 默认为 1) — 调用 callback 函数的频率。如果未指定,则在每个步骤都调用回调函数。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,则作为 self.processor 中定义的 AttentionProcessor 的参数传递。
  • noise_level (int, 可选, 默认为 0) — 要添加到图像嵌入的噪声量。较高的 noise_level 会增加最终去噪图像中的方差。有关更多详细信息,请参阅 StableUnCLIPPipeline.noise_image_embeddings()
  • prior_num_inference_steps (int, 可选, 默认为 25) — 先验去噪过程中的去噪步骤数。更多的去噪步骤通常会带来更高质量的图像,但会牺牲推理速度。
  • prior_guidance_scale (float, 可选, 默认为 4.0) — 较高的 guidance scale 值会鼓励模型生成与文本 prompt 紧密相关的图像,但会牺牲较低的图像质量。当 guidance_scale > 1 时,会启用 guidance scale。
  • prior_latents (torch.Tensor, 可选) — 预生成的、从高斯分布中采样的噪声潜在变量,用作先验去噪过程中图像嵌入生成的输入。可用于通过不同的提示调整相同的生成结果。如果未提供,则会使用提供的随机 generator 采样生成潜在变量张量。
  • clip_skip (int, 可选) — 从 CLIP 中跳过的层数,用于计算提示嵌入。值为 1 表示预最终层的输出将用于计算提示嵌入。

返回值

ImagePipelineOutputtuple

如果 return_dict 为 True,则为 ~ pipeline_utils.ImagePipelineOutput,否则为 tuple。当返回元组时,第一个元素是包含生成图像的列表。

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

示例

>>> import torch
>>> from diffusers import StableUnCLIPPipeline

>>> pipe = StableUnCLIPPipeline.from_pretrained(
...     "fusing/stable-unclip-2-1-l", torch_dtype=torch.float16
... )  # TODO update model path
>>> pipe = pipe.to("cuda")

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> images = pipe(prompt).images
>>> images[0].save("astronaut_horse.png")

enable_attention_slicing

< >

( slice_size: typing.Union[int, str, NoneType] = 'auto' )

参数

  • slice_size (strint, 可选, 默认为 "auto") — 当为 "auto" 时,将注意力头的输入减半,以便分两步计算注意力。如果为 "max",则通过一次只运行一个切片来最大程度地节省内存。如果提供数字,则使用 attention_head_dim // slice_size 个切片。在这种情况下,attention_head_dim 必须是 slice_size 的倍数。

启用切片注意力计算。启用此选项后,注意力模块会将输入张量拆分为切片,以分几个步骤计算注意力。对于多个注意力头,计算将按顺序在每个头上执行。这有助于节省一些内存,但会略微降低速度。

⚠️ 如果您已经在使用 PyTorch 2.0 或 xFormers 中的 scaled_dot_product_attention (SDPA),请勿启用注意力切片。这些注意力计算已经非常节省内存,因此您无需启用此功能。如果您在使用 SDPA 或 xFormers 的情况下启用注意力切片,则可能会导致严重的减速!

示例

>>> import torch
>>> from diffusers import StableDiffusionPipeline

>>> pipe = StableDiffusionPipeline.from_pretrained(
...     "runwayml/stable-diffusion-v1-5",
...     torch_dtype=torch.float16,
...     use_safetensors=True,
... )

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> pipe.enable_attention_slicing()
>>> image = pipe(prompt).images[0]

disable_attention_slicing

< >

( )

禁用切片注意力计算。如果先前调用了 enable_attention_slicing,则注意力将一步计算完成。

enable_vae_slicing

< >

( )

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

disable_vae_slicing

< >

( )

禁用切片 VAE 解码。如果先前启用了 enable_vae_slicing,则此方法将恢复为一步计算解码。

enable_xformers_memory_efficient_attention

< >

( attention_op: typing.Optional[typing.Callable] = None )

参数

启用来自 xFormers 的内存高效注意力。启用此选项后,您应该会观察到 GPU 内存使用率降低,并且推理过程中可能会加速。不保证训练期间的加速。

⚠️ 当内存高效注意力和切片注意力都启用时,内存高效注意力优先。

示例

>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)

disable_xformers_memory_efficient_attention

< >

( )

禁用来自 xFormers 的内存高效注意力。

encode_prompt

< >

( prompt device num_images_per_prompt do_classifier_free_guidance negative_prompt = 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 输入参数生成 negative_prompt_embeds。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器所有 LoRA 层的 LoRA 缩放比例。
  • clip_skip (int, 可选) — 从 CLIP 跳过的层数,用于计算提示嵌入。值为 1 表示预最终层的输出将用于计算提示嵌入。

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

noise_image_embeddings

< >

( image_embeds: Tensor noise_level: int noise: typing.Optional[torch.Tensor] = None generator: typing.Optional[torch._C.Generator] = None )

向图像嵌入添加噪声。 噪声量由 noise_level 输入控制。 较高的 noise_level 会增加最终去噪图像的方差。

噪声以两种方式应用

  1. 噪声计划直接应用于嵌入。
  2. 正弦时间嵌入向量附加到输出。

在这两种情况下,噪声量都由相同的 noise_level 控制。

嵌入在应用噪声之前进行归一化,并在应用噪声之后取消归一化。

StableUnCLIPImg2ImgPipeline

class diffusers.StableUnCLIPImg2ImgPipeline

< >

( feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection image_normalizer: StableUnCLIPImageNormalizer image_noising_scheduler: KarrasDiffusionSchedulers tokenizer: CLIPTokenizer text_encoder: CLIPTextModel unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers vae: AutoencoderKL )

参数

  • feature_extractor (CLIPImageProcessor) — 特征提取器,用于在编码前对图像进行预处理。
  • image_encoder (CLIPVisionModelWithProjection) — CLIP 视觉模型,用于编码图像。
  • image_normalizer (StableUnCLIPImageNormalizer) — 用于在应用噪声之前归一化预测的图像嵌入,并在应用噪声之后取消归一化图像嵌入。
  • image_noising_scheduler (KarrasDiffusionSchedulers) — 噪声调度器,用于向预测的图像嵌入添加噪声。 要添加的噪声量由 noise_level 确定。
  • tokenizer (~transformers.CLIPTokenizer) — 一个 [~transformers.CLIPTokenizer)]。
  • text_encoder (CLIPTextModel) — 冻结的 CLIPTextModel 文本编码器。
  • unet (UNet2DConditionModel) — 一个 UNet2DConditionModel,用于对编码的图像潜在表示进行去噪。
  • scheduler (KarrasDiffusionSchedulers) — 调度器,与 unet 结合使用,以对编码的图像潜在表示进行去噪。
  • vae (AutoencoderKL) — 变分自动编码器 (VAE) 模型,用于将图像编码和解码为潜在表示和从潜在表示解码图像。

用于文本引导的图像到图像生成的 Stable UnCLIP 管线。

此模型继承自 DiffusionPipeline。查看超类文档以获取为所有管道实现的通用方法(下载、保存、在特定设备上运行等)。

该 pipeline 还继承了以下加载方法

__call__

< >

( image: typing.Union[torch.Tensor, PIL.Image.Image] = None prompt: typing.Union[str, typing.List[str]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 20 guidance_scale: float = 10 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Optional[torch._C.Generator] = None 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 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None noise_level: int = 0 image_embeds: typing.Optional[torch.Tensor] = None clip_skip: typing.Optional[int] = None ) ImagePipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示或提示列表。 如果未定义,则将使用 prompt_embeds 或将 prompt 初始化为 ""
  • image (torch.TensorPIL.Image.Image) — 代表图像批次的 Image 或张量。 图像被编码为其 CLIP 嵌入,unet 以此为条件。 图像不是vae 编码,然后像标准 Stable Diffusion 文本引导图像变体过程那样用作去噪过程中的潜在表示。
  • height (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的像素高度。
  • width (int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的像素宽度,默认为 self.unet.config.sample_size * self.vae_scale_factor
  • num_inference_steps (int, optional, defaults to 20) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但会牺牲推理速度。
  • guidance_scale (float, optional, defaults to 10.0) — 更高的 guidance scale 值会鼓励模型生成与文本 prompt 紧密相关的图像,但会以降低图像质量为代价。当 guidance_scale > 1 时,guidance scale 生效。
  • negative_prompt (str or List[str], optional) — 引导图像生成中不包含的内容的 prompt 或 prompts。如果未定义,则需要传递 negative_prompt_embeds 代替。当不使用 guidance 时(guidance_scale < 1),将被忽略。
  • num_images_per_prompt (int, optional, defaults to 1) — 每个 prompt 生成的图像数量。
  • eta (float, optional, defaults to 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中会被忽略。
  • generator (torch.Generator or List[torch.Generator], optional) — 一个 torch.Generator,用于使生成过程确定化。
  • latents (torch.Tensor, optional) — 从高斯分布中采样的预生成噪声 latents,用作图像生成的输入。可用于通过不同的 prompts 调整相同的生成结果。如果未提供,则会使用提供的随机 generator 采样生成 latents tensor。
  • prompt_embeds (torch.Tensor, optional) — 预生成的文本 embeddings。可用于轻松调整文本输入(prompt 权重)。如果未提供,则会从 prompt 输入参数生成文本 embeddings。
  • negative_prompt_embeds (torch.Tensor, optional) — 预生成的负面文本 embeddings。可用于轻松调整文本输入(prompt 权重)。如果未提供,则会从 negative_prompt 输入参数生成 negative_prompt_embeds
  • output_type (str, optional, defaults to "pil") — 生成图像的输出格式。在 PIL.Imagenp.array 之间选择。
  • return_dict (bool, optional, defaults to True) — 是否返回 ImagePipelineOutput 而不是普通元组。
  • callback (Callable, optional) — 在推理期间每 callback_steps 步调用一次的函数。该函数使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, optional, defaults to 1) — 调用 callback 函数的频率。如果未指定,则在每个步骤都调用回调。
  • cross_attention_kwargs (dict, optional) — 一个 kwargs 字典,如果指定,则会传递给 self.processor 中定义的 AttentionProcessor
  • noise_level (int, optional, defaults to 0) — 添加到图像 embeddings 的噪声量。较高的 noise_level 会增加最终去噪图像的方差。有关更多详细信息,请参阅 StableUnCLIPPipeline.noise_image_embeddings()
  • image_embeds (torch.Tensor, optional) — 预生成的 CLIP embeddings,用于在 unet 上进行条件控制。这些 latents 不用于去噪过程。如果您想提供预生成的 latents,请将它们作为 latents 传递给 __call__
  • clip_skip (int, optional) — 从 CLIP 中跳过的层数,用于计算 prompt embeddings。值为 1 表示将使用预最终层的输出计算 prompt embeddings。

返回值

ImagePipelineOutputtuple

如果 return_dict 为 True,则为 ~ pipeline_utils.ImagePipelineOutput,否则为 tuple。当返回元组时,第一个元素是包含生成图像的列表。

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

示例

>>> import requests
>>> import torch
>>> from PIL import Image
>>> from io import BytesIO

>>> from diffusers import StableUnCLIPImg2ImgPipeline

>>> pipe = StableUnCLIPImg2ImgPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-2-1-unclip-small", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"

>>> response = requests.get(url)
>>> init_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> init_image = init_image.resize((768, 512))

>>> prompt = "A fantasy landscape, trending on artstation"

>>> images = pipe(init_image, prompt).images
>>> images[0].save("fantasy_landscape.png")

enable_attention_slicing

< >

( slice_size: typing.Union[int, str, NoneType] = 'auto' )

参数

  • slice_size (str or int, optional, defaults to "auto") — 当为 "auto" 时,将 attention heads 的输入减半,因此 attention 将分两步计算。如果为 "max",则通过一次只运行一个 slice 来最大程度地节省内存。如果提供数字,则使用 attention_head_dim // slice_size 个 slices。在这种情况下,attention_head_dim 必须是 slice_size 的倍数。

启用切片注意力计算。启用此选项后,注意力模块会将输入张量拆分为切片,以分几个步骤计算注意力。对于多个注意力头,计算将按顺序在每个头上执行。这有助于节省一些内存,但会略微降低速度。

⚠️ 如果您已经在使用 PyTorch 2.0 或 xFormers 中的 scaled_dot_product_attention (SDPA),请勿启用注意力切片。这些注意力计算已经非常节省内存,因此您无需启用此功能。如果您在使用 SDPA 或 xFormers 的情况下启用注意力切片,则可能会导致严重的减速!

示例

>>> import torch
>>> from diffusers import StableDiffusionPipeline

>>> pipe = StableDiffusionPipeline.from_pretrained(
...     "runwayml/stable-diffusion-v1-5",
...     torch_dtype=torch.float16,
...     use_safetensors=True,
... )

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> pipe.enable_attention_slicing()
>>> image = pipe(prompt).images[0]

disable_attention_slicing

< >

( )

禁用切片注意力计算。如果先前调用了 enable_attention_slicing,则注意力将一步计算完成。

enable_vae_slicing

< >

( )

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

disable_vae_slicing

< >

( )

禁用切片 VAE 解码。如果先前启用了 enable_vae_slicing,则此方法将恢复为一步计算解码。

enable_xformers_memory_efficient_attention

< >

( attention_op: typing.Optional[typing.Callable] = None )

参数

  • attention_op (Callable, optional) — 覆盖默认的 None 运算符,用作 xFormers 的 memory_efficient_attention() 函数的 op 参数。

启用来自 xFormers 的内存高效注意力。启用此选项后,您应该会观察到 GPU 内存使用率降低,并且推理过程中可能会加速。不保证训练期间的加速。

⚠️ 当内存高效注意力和切片注意力都启用时,内存高效注意力优先。

示例

>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)

disable_xformers_memory_efficient_attention

< >

( )

禁用来自 xFormers 的内存高效注意力。

encode_prompt

< >

( prompt device num_images_per_prompt do_classifier_free_guidance negative_prompt = 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 (str or List[str], optional) — 要编码的 prompt
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个 prompt 应生成的图像数量
  • 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 输入参数生成 `negative_prompt_embeds`。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器的所有 LoRA 层的 LoRA 缩放比例。
  • clip_skip (int, 可选) — 计算提示嵌入时,从 CLIP 跳过的层数。值为 1 表示预最终层的输出将用于计算提示嵌入。

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

noise_image_embeddings

< >

( image_embeds: Tensor noise_level: int noise: typing.Optional[torch.Tensor] = None generator: typing.Optional[torch._C.Generator] = None )

向图像嵌入添加噪声。 噪声量由 noise_level 输入控制。 较高的 noise_level 会增加最终去噪图像的方差。

噪声以两种方式应用

  1. 噪声计划直接应用于嵌入。
  2. 正弦时间嵌入向量附加到输出。

在这两种情况下,噪声量都由相同的 noise_level 控制。

嵌入在应用噪声之前进行归一化,并在应用噪声之后取消归一化。

ImagePipelineOutput

class diffusers.ImagePipelineOutput

< >

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

参数

  • images (List[PIL.Image.Image]np.ndarray) — 长度为 batch_size 的去噪 PIL 图像列表,或形状为 (batch_size, height, width, num_channels) 的 NumPy 数组。

图像管道的输出类。

< > Update on GitHub