Diffusers documentation

Stable unCLIP

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

and get access to the augmented documentation experience

to get started

Stable unCLIP

LoRA

Stable unCLIP 检查点基于 Stable Diffusion 2.1 检查点微调,以使用 CLIP 图像嵌入作为条件。 Stable unCLIP 仍然以文本嵌入作为条件。由于存在两种独立的条件,stable unCLIP 可用于文本引导的图像变化。当与 unCLIP 先验模型结合使用时,它还可用于完整的文本到图像生成。

该论文的摘要如下:

CLIP 等对比模型已被证明能够学习捕获图像语义和风格的鲁棒表示。为了将这些表示用于图像生成,我们提出了一种两阶段模型:一个先验模型,根据文本描述生成 CLIP 图像嵌入;以及一个解码器,根据图像嵌入生成图像。我们表明,显式生成图像表示可以在几乎不损失照片真实感和描述相似度的情况下提高图像多样性。基于图像表示进行条件生成的解码器还可以生成图像的变体,在保留其语义和风格的同时,改变图像表示中不存在的非关键细节。此外,CLIP 的联合嵌入空间支持以零样本方式进行语言引导的图像操作。我们使用扩散模型作为解码器,并分别使用自回归模型和扩散模型作为先验模型进行实验,发现后者在计算上更高效,且能生成更高质量的样本。

提示

Stable unCLIP 在推理过程中以 noise_level 作为输入,用于确定向图像嵌入中添加多少噪声。较高的 noise_level 会增加最终去噪图像的多样性。默认情况下,我们不会向图像嵌入添加任何额外噪声(noise_level = 0)。

文本到图像生成

Stable unCLIP 可与 KakaoBrain 开源的 DALL-E 2 复刻项目 Karlo 的先验模型进行流水线组合,从而实现文本到图像的生成:

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", 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, 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,
    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")  # or "mps", "xpu", "cpu"
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 模型先验相同。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", dtype=torch.float16, variation="fp16"
)
pipe = pipe.to("cuda")  # or "mps", "xpu", "cpu"

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: CLIPTokenizerprior_text_encoder: CLIPTextModelWithProjectionprior: PriorTransformerprior_scheduler: KarrasDiffusionSchedulersimage_normalizer: StableUnCLIPImageNormalizerimage_noising_scheduler: KarrasDiffusionSchedulerstokenizer: CLIPTokenizertext_encoder: CLIPTextModelunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulersvae: AutoencoderKL )

参数

  • prior_tokenizer (CLIPTokenizer) — A CLIPTokenizer.
  • prior_text_encoder (CLIPTextModelWithProjection) — 冻结的 CLIPTextModelWithProjection 文本编码器。
  • prior (PriorTransformer) — 用于从文本嵌入近似图像嵌入的 unCLIP 标准先验模型。
  • prior_scheduler (KarrasDiffusionSchedulers) — 用于先验去噪过程的调度器。
  • image_normalizer (StableUnCLIPImageNormalizer) — 用于在添加噪声之前对预测的图像嵌入进行归一化,并在添加噪声之后对图像嵌入进行反归一化。
  • image_noising_scheduler (KarrasDiffusionSchedulers) — 用于向预测图像嵌入添加噪声的噪声调度器。添加的噪声量由 noise_level 决定。
  • tokenizer (CLIPTokenizer) — A CLIPTokenizer.
  • text_encoder (CLIPTextModel) — 冻结的 CLIPTextModel 文本编码器。
  • unet (UNet2DConditionModel) — 用于对编码后的图像潜变量进行去噪的 UNet2DConditionModel。
  • scheduler (KarrasDiffusionSchedulers) — 用于与 unet 配合,对编码后的图像潜变量进行去噪的调度器。
  • vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码回图像。

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

该模型继承自 DiffusionPipeline。有关为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等),请参阅父类文档。

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

__call__

< >

( prompt: str | list[str] | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 20guidance_scale: float = 10.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Optional[torch.Generator] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1cross_attention_kwargs: dict[str, typing.Any] | None = Nonenoise_level: int = 0prior_num_inference_steps: int = 25prior_guidance_scale: float = 4.0prior_latents: typing.Optional[torch.Tensor] = Noneclip_skip: int | None = None ) → ImagePipelineOutput or tuple

参数

  • prompt (str 或 list[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 (str 或 list[str],可选) — 用于指导图像生成中不应包含的内容的提示词或提示词列表。如果未定义,则需要改为传入 negative_prompt_embeds。在未使用引导(guidance_scale < 1)时将被忽略。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • eta(float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中会被忽略。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 用于使生成过程确定性的 torch.Generator。
  • latents (torch.Tensor, 可选) — 预先生成的、从高斯分布中采样的含噪潜变量,用作图像生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供,则使用提供的随机generator进行采样,生成一个潜变量张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示词加权)。如果未提供,则从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor,可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入(提示词权重)。如果未提供,negative_prompt_embeds 将根据 negative_prompt 输入参数生成。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选 PIL.Image 或 np.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 表示使用倒数第二层的输出来计算提示嵌入。

返回值

ImagePipelineOutput 或 tuple

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

用于生成的 pipeline 的调用函数。

示例:

>>> 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: str | int = 'auto' )

参数

  • slice_size (str 或 int,可选,默认为 "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(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     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_xformers_memory_efficient_attention

< >

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

参数

启用来自 xFormers 的内存高效注意力机制。启用此选项后,您应能观察到更低的 GPU 内存占用,并且在推理期间可能会获得加速。训练期间的加速并不保证。

> ⚠️ 当同时启用 memory efficient attention 和 sliced attention 时,memory efficient attention 具有 > 优先权。

示例:

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

>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", 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

< >

( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用 classifier free guidance
  • negative_prompt (str 或 list[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 表示使用倒数第二层的输出来计算提示嵌入。

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

noise_image_embeddings

< >

( image_embeds: Tensornoise_level: intnoise: typing.Optional[torch.Tensor] = Nonegenerator: typing.Optional[torch.Generator] = None )

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

噪声以两种方式施加:

  1. 噪声调度直接应用于嵌入。
  2. 在输出中附加一个正弦时间嵌入向量。

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

在应用噪声之前,嵌入会被归一化;在应用噪声之后,嵌入会被反归一化。

StableUnCLIPImg2ImgPipeline

类 diffusers.StableUnCLIPImg2ImgPipeline

< >

( feature_extractor: CLIPImageProcessorPilimage_encoder: CLIPVisionModelWithProjectionimage_normalizer: StableUnCLIPImageNormalizerimage_noising_scheduler: KarrasDiffusionSchedulerstokenizer: CLIPTokenizertext_encoder: CLIPTextModelunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulersvae: AutoencoderKL )

参数

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

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

该模型继承自 DiffusionPipeline。有关为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等),请参阅父类文档。

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

__call__

< >

( image: typing.Union[torch.Tensor, PIL.Image.Image] = Noneprompt: str | list[str] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 20guidance_scale: float = 10negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Optional[torch.Generator] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1cross_attention_kwargs: dict[str, typing.Any] | None = Nonenoise_level: int = 0image_embeds: typing.Optional[torch.Tensor] = Noneclip_skip: int | None = None ) → ImagePipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则使用 prompt_embeds,或将 prompt 初始化为 ""。
  • image (torch.Tensor 或 PIL.Image.Image) — Image 或表示图像批次的张量。该图像会被编码为其 CLIP 嵌入,unet 将以此作为条件。与标准 Stable Diffusion 文本引导的图像变体流程不同,该图像不会先由 vae 编码,再作为潜变量用于去噪过程。
  • 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 (str 或 list[str],可选) — 用于指导图像生成中不应包含的内容的提示词或提示词列表。如果未定义,则需要改为传入 negative_prompt_embeds。在未使用引导(guidance_scale < 1)时将被忽略。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • eta(float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中会被忽略。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 用于使生成过程确定性的 torch.Generator。
  • latents (torch.Tensor, 可选) — 预先生成的、从高斯分布中采样的含噪潜变量,用作图像生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供,则使用提供的随机generator进行采样,生成一个潜变量张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示词加权)。如果未提供,则从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor,可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入(提示词权重)。如果未提供,negative_prompt_embeds 将根据 negative_prompt 输入参数生成。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选 PIL.Image 或 np.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()。
  • image_embeds (torch.Tensor, 可选) — 用于条件化 unet 的预生成 CLIP 嵌入。这些潜在变量不会用于去噪过程。如果您想提供预生成的潜在变量,请将其作为 latents 传递给 __call__。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。

返回值

ImagePipelineOutput 或 tuple

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

用于生成的 pipeline 的调用函数。

示例:

>>> 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: str | int = 'auto' )

参数

  • slice_size (str 或 int,可选,默认为 "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(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     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_xformers_memory_efficient_attention

< >

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

参数

启用来自 xFormers 的内存高效注意力机制。启用此选项后,您应能观察到更低的 GPU 内存占用,并且在推理期间可能会获得加速。训练期间的加速并不保证。

> ⚠️ 当同时启用 memory efficient attention 和 sliced attention 时,memory efficient attention 具有 > 优先权。

示例:

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

>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", 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

< >

( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用 classifier free guidance
  • negative_prompt (str 或 list[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 表示使用倒数第二层的输出来计算提示嵌入。

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

noise_image_embeddings

< >

( image_embeds: Tensornoise_level: intnoise: typing.Optional[torch.Tensor] = Nonegenerator: typing.Optional[torch.Generator] = None )

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

噪声以两种方式施加:

  1. 噪声调度直接应用于嵌入。
  2. 在输出中附加一个正弦时间嵌入向量。

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

在应用噪声之前,嵌入会被归一化;在应用噪声之后,嵌入会被反归一化。

ImagePipelineOutput

类 diffusers.ImagePipelineOutput

< >

( images: 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