Diffusers 文档

潜在空间放大器

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

潜在空间放大器

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

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

如果您有兴趣使用官方检查点来执行任务,请浏览 CompVisRunwayStability AI Hub 组织!

StableDiffusionLatentUpscalePipeline

class diffusers.StableDiffusionLatentUpscalePipeline

< >

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

参数

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

此模型继承自 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 ) StableDiffusionPipelineOutputtuple

参数

  • prompt (strList[str]) — 用于引导图像放大的 prompt (提示) 或 prompts (提示列表)。
  • image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], 或 List[np.ndarray]) — Image (图像) 或 tensor (张量),表示要放大的图像批次。如果它是张量,则可以是来自 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 (strList[str], 可选) — prompt (提示) 或 prompts (提示列表),用于引导图像生成中不应包含的内容。如果未定义,则需要传递 negative_prompt_embeds 代替。当不使用 guidance (引导) 时(guidance_scale < 1),将被忽略。
  • eta (float, 可选,默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler (DDIM 调度器),在其他调度器中将被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — torch.Generator,用于使生成结果具有确定性。
  • latents (torch.Tensor, 可选) — 预生成的噪声潜在空间,从高斯分布中采样,用作图像生成的输入。可用于通过不同的 prompt (提示) 调整相同的生成结果。如果未提供,则将通过使用提供的随机 generator (生成器) 进行采样来生成潜在空间张量。
  • output_type (str, 可选,默认为 "pil") — 生成图像的输出格式。在 PIL.Imagenp.array 之间选择。
  • return_dict (bool, 可选,默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通的 tuple (元组)。
  • 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] = 'cuda' )

参数

  • gpu_id (int, 可选) — 推理中应使用的加速器的 ID。如果未指定,则默认为 0。
  • device (torch.Devicestr, 可选,默认为 “cuda”) — 推理中应使用的加速器的 PyTorch 设备类型。如果未指定,则默认为 “cuda”。

使用 🤗 Accelerate 将所有模型卸载到 CPU,从而显著减少内存使用量。调用时,所有 torch.nn.Module 组件(self._exclude_from_cpu_offload 中的组件除外)的状态字典将保存到 CPU,然后移动到 torch.device('meta'),并且仅当其特定子模块的 forward 方法被调用时才加载到 GPU。卸载是基于子模块进行的。内存节省高于 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(
...     "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_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 输入参数生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,则将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,则将从 negative_prompt 输入参数生成池化 negative_prompt_embeds。

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

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 上更新