Diffusers 文档

潜在升采样器

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

潜在升采样器

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

务必查看 Stable Diffusion 的 提示 部分,了解如何探索调度器速度和质量之间的权衡,以及如何高效地重用管道组件!

如果您有兴趣将其中一个官方检查点用于某个任务,请浏览 CompVisRunwayStability AI Hub 组织!

StableDiffusionLatentUpscalePipeline

class diffusers.StableDiffusionLatentUpscalePipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: EulerDiscreteScheduler )

参数

用于将 Stable Diffusion 输出图像分辨率提高 2 倍的管道。

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

该管道还继承了以下加载方法

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None num_inference_steps: int = 75 guidance_scale: float = 9.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_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 ) StableDiffusionPipelineOutput or tuple

参数

  • prompt (strList[str]) — 用于引导图像升采样的提示。
  • image (torch.TensorPIL.Image.Imagenp.ndarrayList[torch.Tensor]List[PIL.Image.Image]List[np.ndarray]) — 要升采样的图像或表示图像批次的张量。如果它是张量,它可以是 Stable Diffusion 模型的潜在输出,也可以是范围 [-1, 1] 内的图像张量。如果 image.shape[1]4,则被视为 latent;否则,被视为图像表示并使用此管道的 vae 编码器进行编码。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步数。更多的去噪步数通常会带来更高质量的图像,但推理速度会变慢。
  • guidance_scale (float, 可选, 默认为 7.5) — 较高的引导比例值鼓励模型生成与文本 prompt 密切相关的图像,但图像质量较低。当 guidance_scale > 1 时,启用引导比例。
  • negative_prompt (strList[str], 可选) — 引导图像生成中不应包含的内容的提示。如果未定义,您需要传递 negative_prompt_embeds。当不使用引导(guidance_scale < 1)时,忽略此参数。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 一个 torch.Generator,用于使生成具有确定性。
  • latents (torch.Tensor, 可选) — 从高斯分布采样的预生成噪声潜在表示,用作图像生成的输入。可用于使用不同提示调整相同的生成。如果未提供,则使用提供的随机 generator 进行采样生成一个潜在张量。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。在 PIL.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • callback (Callable, 可选) — 一个函数,在推理过程中每 callback_steps 步调用一次。该函数使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可选, 默认为 1) — 调用 callback 函数的频率。如果未指定,则在每一步调用回调。

返回

StableDiffusionPipelineOutputtuple

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

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

示例

>>> 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: typing.Optional[int] = None device: typing.Union[torch.device, str] = None )

参数

  • gpu_id (int, 可选) — 推理中应使用的加速器 ID。如果未指定,默认为 0。
  • device (torch.Devicestr, 可选, 默认为 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: 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(
...     "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]

disable_attention_slicing

< >

( )

禁用切片注意力计算。如果之前调用过 enable_attention_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)

disable_xformers_memory_efficient_attention

< >

( )

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

encode_prompt

< >

( prompt device do_classifier_free_guidance negative_prompt = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None )

参数

  • prompt (strlist(int)) — 要编码的提示词。
  • device — (torch.device): torch 设备。
  • do_classifier_free_guidance (bool) — 是否使用分类器自由引导。
  • negative_prompt (strList[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_embeds 将从 negative_prompt 输入参数生成。

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

StableDiffusionPipelineOutput

class diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput

< >

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

参数

  • 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 管道的输出类。

< > 在 GitHub 上更新