Diffusers 文档
Stable unCLIP
并获得增强的文档体验
开始使用
Stable unCLIP
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", 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 模型先验相同。不建议使用 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: CLIPTextModel 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 管道。
此模型继承自 DiffusionPipeline。有关所有管道实现的通用方法(下载、保存、在特定设备上运行等)的更多信息,请查看超类文档。
该管道还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演嵌入
- load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
__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 或 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) — 更高的指导比例值会促使模型生成与文本prompt
紧密相关的图像,但会牺牲图像质量。当guidance_scale > 1
时启用指导比例。 - 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
输入参数生成negative_prompt_embeds
。 - 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 字典将作为op
参数传递给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) — 更高的指导比例值会促使模型生成与文本prompt
紧密相关的图像,但会牺牲图像质量。当guidance_scale > 1
时启用指导比例。 - prior_latents (
torch.Tensor
, 可选) — 预先生成的高斯分布采样噪声潜变量,用作先验去噪过程中图像嵌入生成的输入。可用于使用不同提示调整相同的生成。如果未提供,则使用提供的随机generator
进行采样生成潜变量张量。 - clip_skip (
int
, 可选) — 计算提示嵌入时从 CLIP 跳过的层数。值为 1 表示将使用倒数第二层的输出计算提示嵌入。
返回
ImagePipelineOutput 或 tuple
如果 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' )
启用切片注意力计算。启用此选项后,注意力模块会将输入张量切片以分多步计算注意力。对于多个注意力头,计算将按顺序在每个头上执行。这有助于节省一些内存,但会略微降低速度。
⚠️ 如果您已经在使用 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",
... 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]
禁用切片注意力计算。如果之前调用过 enable_attention_slicing
,则注意力将一步计算完成。
启用切片 VAE 解码。启用此选项后,VAE 会将输入张量分片,分步计算解码。这有助于节省一些内存并允许更大的批次大小。
禁用切片 VAE 解码。如果之前启用了 enable_vae_slicing
,此方法将返回一步计算解码。
enable_xformers_memory_efficient_attention
< 源 >( attention_op: typing.Optional[typing.Callable] = None )
参数
- attention_op (
Callable
, 可选) — 覆盖默认的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)
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
或List[str]
, 可选) — 待编码的提示 - device — (
torch.device
): torch 设备 - num_images_per_prompt (
int
) — 每个提示应生成的图像数量 - do_classifier_free_guidance (
bool
) — 是否使用分类器自由指导 - 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: Tensor noise_level: int noise: typing.Optional[torch.Tensor] = None generator: typing.Optional[torch._C.Generator] = None )
向图像嵌入添加噪声。噪声量由 noise_level
输入控制。更高的 noise_level
会增加最终去噪图像的方差。
噪声通过两种方式施加:
- 噪声时间表直接应用于嵌入。
- 将正弦时间嵌入向量附加到输出。
两种情况下,噪声量都由相同的 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。有关所有管道实现的通用方法(下载、保存、在特定设备上运行等)的更多信息,请查看超类文档。
该管道还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演嵌入
- load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
__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 ) → ImagePipelineOutput 或 tuple
参数
- prompt (
str
或List[str]
, 可选) — 指导图像生成的提示或提示列表。如果未定义,将使用prompt_embeds
或将提示初始化为""
。 - image (
torch.Tensor
或PIL.Image.Image
) — 表示图像批次的图像或张量。图像被编码为其 CLIP 嵌入,unet
以此为条件。图像**未**通过vae
编码,然后像标准 Stable Diffusion 文本引导图像变体过程那样用作去噪过程中的潜在表示。 - 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) — 更高的引导尺度值会促使模型生成与文本prompt
紧密相关的图像,但会牺牲图像质量。当guidance_scale > 1
时,启用引导尺度。 - 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 字典,如果指定,则作为AttentionProcessor
的参数传递,如self.processor
中定义。 - noise_level (
int
, 可选, 默认为0
) — 添加到图像嵌入中的噪声量。更高的noise_level
会增加最终去噪图像中的方差。有关更多详细信息,请参见 StableUnCLIPPipeline.noise_image_embeddings()。 - image_embeds (
torch.Tensor
, 可选) — 预生成的 CLIP 嵌入,用于将unet
作为条件。这些潜在变量不用于去噪过程。如果希望提供预生成的潜在变量,请将其作为latents
传递给__call__
。 - clip_skip (
int
, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示将使用倒数第二层的输出计算提示嵌入。
返回
ImagePipelineOutput 或 tuple
如果 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' )
启用切片注意力计算。启用此选项后,注意力模块会将输入张量切片以分多步计算注意力。对于多个注意力头,计算将按顺序在每个头上执行。这有助于节省一些内存,但会略微降低速度。
⚠️ 如果您已经在使用 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",
... 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]
禁用切片注意力计算。如果之前调用过 enable_attention_slicing
,则注意力将一步计算完成。
启用切片 VAE 解码。启用此选项后,VAE 会将输入张量分片,分步计算解码。这有助于节省一些内存并允许更大的批次大小。
禁用切片 VAE 解码。如果之前启用了 enable_vae_slicing
,此方法将返回一步计算解码。
enable_xformers_memory_efficient_attention
< 源 >( attention_op: typing.Optional[typing.Callable] = None )
参数
- attention_op (
Callable
, 可选) — 覆盖默认的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)
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
或List[str]
, 可选) — 要编码的提示 - device — (
torch.device
): torch 设备 - num_images_per_prompt (
int
) — 每个提示应生成的图像数量 - do_classifier_free_guidance (
bool
) — 是否使用无分类器引导 - 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: Tensor noise_level: int noise: typing.Optional[torch.Tensor] = None generator: typing.Optional[torch._C.Generator] = None )
向图像嵌入添加噪声。噪声量由 noise_level
输入控制。更高的 noise_level
会增加最终去噪图像的方差。
噪声通过两种方式施加:
- 噪声时间表直接应用于嵌入。
- 将正弦时间嵌入向量附加到输出。
两种情况下,噪声量都由相同的 noise_level
控制。
在应用噪声之前,嵌入会被归一化,并在应用噪声之后解除归一化。
ImagePipelineOutput
class diffusers.ImagePipelineOutput
< 源 >( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] )
图像流水线的输出类。