Diffusers documentation

潜在上采样器

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

潜在上采样器

Stable Diffusion 潜在上采样模型由 Katherine Crowson 与 Stability AI 合作创建。该模型用于将输出图像的分辨率提升 2 倍(有关原始实现的演示,请参阅此 notebook)。

请务必查看 Stable Diffusion 的 技巧 部分,了解如何探索调度器速度与质量之间的权衡,以及如何高效地复用流水线组件!

如果您对使用某个任务的官方检查点感兴趣,请探索 CompVis 和 Stability AI Hub 组织!

StableDiffusionLatentUpscalePipeline

类 diffusers.StableDiffusionLatentUpscalePipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModelscheduler: EulerDiscreteScheduler )

参数

用于将 Stable Diffusion 输出图像分辨率放大 2 倍的 Pipeline。

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

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

__call__

< >

( prompt: str | list[str] = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonenum_inference_steps: int = 75guidance_scale: float = 9.0negative_prompt: str | list[str] | None = Nonegenerator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_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 = 1 ) → StableDiffusionPipelineOutput or tuple

参数

  • prompt (str 或 list[str]) — 用于指导图像放大的提示词或提示词列表。
  • image (torch.Tensor、PIL.Image.Image、np.ndarray、list[torch.Tensor]、list[PIL.Image.Image] 或 list[np.ndarray]) — Image 或表示待放大图像批次的张量。如果它是张量,则可以是 Stable Diffusion 模型的潜在输出,也可以是范围在 [-1, 1] 内的图像张量。如果 image.shape[1] 为 4,则被视为 latent;否则,它被视为图像表示,并使用此流水线中的 vae 编码器进行编码。
  • num_inference_steps (int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • guidance_scale (float,可选,默认值为 7.5) — 较高的 guidance scale 值会促使模型生成与文本 prompt 紧密相关的图像,但代价是图像质量降低。当 guidance_scale > 1 时,guidance scale 生效。
  • negative_prompt (str 或 list[str],可选) — 用于指导图像生成中不应包含的内容的提示词或提示词列表。如果未定义,则需要改为传入 negative_prompt_embeds。在未使用引导(guidance_scale < 1)时将被忽略。
  • 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 输入参数生成。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入(提示词加权)。如果未提供,则从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds(torch.Tensor,可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入(提示词权重)。如果未提供,则会根据 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选 PIL.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • callback (Callable, 可选) — 一个在推理过程中每隔 callback_steps 步调用一次的函数。该函数以以下参数被调用:callback(step: int, timestep: int, latents: torch.Tensor)。
  • callback_steps (int,可选,默认为 1) — 调用 callback 函数的频率。如果未指定,则会在每一步调用该回调。

返回值

StableDiffusionPipelineOutput 或 tuple

如果 return_dict 为 True,则返回 StableDiffusionPipelineOutput,否则返回一个 tuple,其中第一个元素是包含生成图像的列表。

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

示例:

>>> from diffusers import StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline
>>> import torch

>>> pipeline = StableDiffusionPipeline.from_pretrained(
...     "CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16
... )
>>> pipeline.to("cuda")

>>> model_id = "stabilityai/sd-x2-latent-upscaler"
>>> upscaler = StableDiffusionLatentUpscalePipeline.from_pretrained(model_id, torch_dtype=torch.float16)
>>> upscaler.to("cuda")

>>> prompt = "a photo of an astronaut high resolution, unreal engine, ultra realistic"
>>> generator = torch.manual_seed(33)

>>> low_res_latents = pipeline(prompt, generator=generator, output_type="latent").images

>>> with torch.no_grad():
...     image = pipeline.decode_latents(low_res_latents)
>>> image = pipeline.numpy_to_pil(image)[0]

>>> image.save("../images/a1.png")

>>> upscaled_image = upscaler(
...     prompt=prompt,
...     image=low_res_latents,
...     num_inference_steps=20,
...     guidance_scale=0,
...     generator=generator,
... ).images[0]

>>> upscaled_image.save("../images/a2.png")

enable_sequential_cpu_offload

< >

( gpu_id: int | None = Nonedevice: typing.Union[torch.device, str] = None )

参数

  • gpu_id (int, 可选) — 用于推理的加速器 ID。如果未指定,则默认为 0。
  • device (torch.Device 或 str,可选,默认为 None) — 用于推理的加速器的 PyTorch 设备类型。如果未指定,将自动检测可用的加速器并使用。

使用 🤗 Accelerate 将所有模型卸载到 CPU,从而显著降低内存占用。调用时,所有 torch.nn.Module 组件(self._exclude_from_cpu_offload 中的除外)的状态字典会被保存到 CPU,然后移至 torch.device('meta'),仅当特定子模块的 forward 方法被调用时才加载到加速器上。卸载以子模块为单位进行。与 enable_model_cpu_offload 相比,内存节省更多,但性能较低。

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

< >

( promptdevicedo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None )

参数

  • prompt (str 或 list(int)) — 要编码的提示
  • device — (torch.device): torch 设备
  • do_classifier_free_guidance (bool) — 是否使用 classifier free guidance
  • negative_prompt (str 或 list[str]) — 用于引导图像生成的负面提示词。当不使用引导时会被忽略(即当 guidance_scale 小于 1 时会被忽略)。
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将根据 negative_prompt 输入参数生成。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。 如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。

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

StableDiffusionPipelineOutput

类 diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput

< >

( images: list[PIL.Image.Image] | numpy.ndarraynsfw_content_detected: list[bool] | None )

参数

  • images (list[PIL.Image.Image] 或 np.ndarray) — 长度为 batch_size 的去噪 PIL 图像列表,或形状为 (batch_size, height, width, num_channels) 的 NumPy 数组。
  • nsfw_content_detected (list[bool]) — 一个列表,指示对应的生成图像是否包含“不适合工作场所”(nsfw)内容;如果无法执行安全检查,则为 None。

Stable Diffusion 管道的输出类。

Update on GitHub