Diffusers documentation

潜在扩散

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

潜在扩散

Latent Diffusion 由 Robin Rombach、Andreas Blattmann、Dominik Lorenz、Patrick Esser 和 Björn Ommer 在 High-Resolution Image Synthesis with Latent Diffusion Models 中提出。

该论文的摘要如下:

通过将图像生成过程分解为去噪自编码器的顺序应用,扩散模型(DMs)在图像数据及其他领域实现了最先进的合成效果。此外,其数学形式允许引入引导机制,从而无需重新训练即可控制图像生成过程。然而,由于这些模型通常直接在像素空间中进行操作,训练强大的 DMs 往往需要消耗数百个 GPU 天,且由于需要顺序评估,推理成本高昂。为了在保留模型质量和灵活性的同时,使 DMs 能够在有限的计算资源上进行训练,我们将它们应用于强大的预训练自编码器的潜在空间中。与以往工作不同,在这种表示上训练扩散模型首次实现了在降低复杂度和保留细节之间达到近乎最优的平衡,从而极大地提升了视觉保真度。通过在模型架构中引入交叉注意力层,我们将扩散模型转变为强大的通用条件输入(如文本或边界框)生成器,并使得以卷积方式实现高分辨率合成成为可能。我们的潜在扩散模型(LDMs)在图像修复任务上达到了新的最先进水平,并在无条件图像生成、语义场景合成和超分辨率等多种任务上展现出极具竞争力的性能,同时与基于像素的 DMs 相比,显著降低了计算需求。

原始代码库可在 CompVis/latent-diffusion 中找到。

请务必参阅 调度器指南,了解如何探索调度器速度与质量之间的权衡,并查看 跨流水线复用组件 部分,了解如何高效地将相同组件加载到多个流水线中。

LDMTextToImagePipeline

class diffusers.LDMTextToImagePipeline

< >

( vqvae: diffusers.models.autoencoders.vq_model.VQModel | diffusers.models.autoencoders.autoencoder_kl.AutoencoderKLbert: PreTrainedModeltokenizer: PythonBackendunet: diffusers.models.unets.unet_2d.UNet2DModel | diffusers.models.unets.unet_2d_condition.UNet2DConditionModelscheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_pndm.PNDMScheduler | diffusers.utils.dummy_torch_and_scipy_objects.LMSDiscreteScheduler )

参数

  • vqvae (VQModel) — 向量量化(VQ)模型,用于将图像编码为潜在表示,以及从潜在表示解码为图像。
  • bert (LDMBertModel) — 基于 BERT 的文本编码器模型。
  • tokenizer(BertTokenizer)— 用于对文本进行分词的 BertTokenizer。
  • unet (UNet2DConditionModel) — 用于对编码后的图像潜变量进行去噪的 UNet2DConditionModel。
  • scheduler (SchedulerMixin) — 用于与 unet 配合,对编码后的图像潜变量进行去噪的调度器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。

用于基于潜在扩散的文本到图像生成的 Pipeline。

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

__call__

< >

( prompt: str | list[str]height: int | None = Nonewidth: int | None = Nonenum_inference_steps: int | None = 50guidance_scale: float | None = 1.0eta: float | None = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = True**kwargs ) → ImagePipelineOutput or tuple

参数

  • prompt (str 或 list[str]) — 用于引导图像生成的提示词或提示词列表。
  • 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,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • guidance_scale (float,可选,默认值为 1.0) — 较高的 guidance scale 值会促使模型生成与文本 prompt 紧密相关的图像,但代价是图像质量降低。当 guidance_scale > 1 时,启用 guidance scale。
  • eta(float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中会被忽略。
  • generator (torch.Generator,可选) — 用于使生成过程确定性的 torch.Generator。
  • latents (torch.Tensor, 可选) — 预先生成的、从高斯分布中采样的含噪潜变量,用作图像生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供,则使用提供的随机generator进行采样,生成一个潜变量张量。
  • output_type (str, 可选,默认为 "pil") — 生成图像的输出格式。可选 "pil" (PIL.Image)、"np" (np.array) 或 "pt" (torch.Tensor)。
  • return_dict (bool,可选,默认为 True) — 是否返回 ImagePipelineOutput 而不是普通元组。

返回值

ImagePipelineOutput 或 tuple

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

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

示例:

>>> from diffusers import DiffusionPipeline

>>> # load model and scheduler
>>> ldm = DiffusionPipeline.from_pretrained("CompVis/ldm-text2im-large-256")

>>> # run pipeline in inference (sample random noise and denoise)
>>> prompt = "A painting of a squirrel eating a burger"
>>> images = ldm([prompt], num_inference_steps=50, eta=0.3, guidance_scale=6).images

>>> # save images
>>> for idx, image in enumerate(images):
...     image.save(f"squirrel-{idx}.png")

LDMSuperResolutionPipeline

类 diffusers.LDMSuperResolutionPipeline

< >

( vqvae: VQModelunet: UNet2DModelscheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_pndm.PNDMScheduler | diffusers.utils.dummy_torch_and_scipy_objects.LMSDiscreteScheduler | diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler | diffusers.schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteScheduler | diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler )

参数

用于图像超分辨率的潜在扩散模型流水线。

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

__call__

< >

( image: typing.Union[torch.Tensor, PIL.Image.Image] = Nonebatch_size: int | None = 1num_inference_steps: int | None = 100eta: float | None = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneoutput_type: str | None = 'pil'return_dict: bool = True ) → ImagePipelineOutput or tuple

参数

  • image(torch.Tensor 或 PIL.Image.Image)— Image 或表示图像批次的张量,用作流程的起始点。
  • batch_size (int,可选,默认为 1) — 要生成的图像数量。
  • num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • eta(float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中会被忽略。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 用于使生成过程确定性的 torch.Generator。
  • output_type (str, 可选,默认为 "pil") — 生成图像的输出格式。可选 "pil" (PIL.Image)、"np" (np.array) 或 "pt" (torch.Tensor)。
  • return_dict (bool,可选,默认为 True) — 是否返回 ImagePipelineOutput 而不是普通元组。

返回值

ImagePipelineOutput 或 tuple

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

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

示例:

>>> import requests
>>> from PIL import Image
>>> from io import BytesIO
>>> from diffusers import LDMSuperResolutionPipeline
>>> import torch

>>> # load model and scheduler
>>> pipeline = LDMSuperResolutionPipeline.from_pretrained("CompVis/ldm-super-resolution-4x-openimages")
>>> pipeline = pipeline.to("cuda")

>>> # let's download an  image
>>> url = (
...     "https://user-images.githubusercontent.com/38061659/199705896-b48e17b8-b231-47cd-a270-4ffa5a93fa3e.png"
... )
>>> response = requests.get(url)
>>> low_res_img = Image.open(BytesIO(response.content)).convert("RGB")
>>> low_res_img = low_res_img.resize((128, 128))

>>> # run pipeline in inference (sample random noise and denoise)
>>> upscaled_image = pipeline(low_res_img, num_inference_steps=100, eta=1).images[0]
>>> # save image
>>> upscaled_image.save("ldm_generated_image.png")

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