Diffusers 文档

潜在扩散

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

潜在扩散

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

论文摘要如下:

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

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

请务必查看调度器指南,了解如何探索调度器速度和质量之间的权衡,并查看跨 pipelines 重用组件部分,了解如何有效地将相同的组件加载到多个 pipelines 中。

LDMTextToImagePipeline

class diffusers.LDMTextToImagePipeline

< >

( vqvae: typing.Union[diffusers.models.autoencoders.vq_model.VQModel, diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL] bert: PreTrainedModel tokenizer: PreTrainedTokenizer unet: typing.Union[diffusers.models.unets.unet_2d.UNet2DModel, diffusers.models.unets.unet_2d_condition.UNet2DConditionModel] scheduler: typing.Union[diffusers.schedulers.scheduling_ddim.DDIMScheduler, diffusers.schedulers.scheduling_pndm.PNDMScheduler, diffusers.schedulers.scheduling_lms_discrete.LMSDiscreteScheduler] )

参数

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

使用潜在扩散进行文本到图像生成的 Pipeline。

此模型继承自 DiffusionPipeline。查看超类文档以获取为所有 pipelines 实现的通用方法(下载、保存、在特定设备上运行等)。

__call__

< >

( prompt: typing.Union[str, typing.List[str]] height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: typing.Optional[int] = 50 guidance_scale: typing.Optional[float] = 1.0 eta: typing.Optional[float] = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True **kwargs ) ImagePipelineOutputtuple

参数

  • prompt (strList[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 功能启用。
  • generator (torch.Generator, 可选) — 用于使生成结果具有确定性的 torch.Generator
  • latents (torch.Tensor, 可选) — 预生成的噪声潜在空间,从高斯分布中采样,用作图像生成的输入。可用于使用不同的 prompt 微调相同的生成结果。如果未提供,则会通过使用提供的随机 generator 进行采样来生成潜在空间张量。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。在 PIL.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ImagePipelineOutput 而不是普通元组。

返回值

ImagePipelineOutputtuple

如果 return_dictTrue,则返回 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

class diffusers.LDMSuperResolutionPipeline

< >

( vqvae: VQModel unet: UNet2DModel scheduler: typing.Union[diffusers.schedulers.scheduling_ddim.DDIMScheduler, diffusers.schedulers.scheduling_pndm.PNDMScheduler, diffusers.schedulers.scheduling_lms_discrete.LMSDiscreteScheduler, diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler, diffusers.schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteScheduler, diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler] )

参数

用于图像超分辨率的 pipeline,使用潜在扩散。

此模型继承自 DiffusionPipeline。查看超类文档以获取为所有 pipelines 实现的通用方法(下载、保存、在特定设备上运行等)。

__call__

< >

( image: typing.Union[torch.Tensor, PIL.Image.Image] = None batch_size: typing.Optional[int] = 1 num_inference_steps: typing.Optional[int] = 100 eta: typing.Optional[float] = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True ) ImagePipelineOutputtuple

参数

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

返回值

ImagePipelineOutputtuple

如果 return_dictTrue,则返回 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

class diffusers.ImagePipelineOutput

< >

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

参数

  • images (List[PIL.Image.Image]np.ndarray) — 长度为 batch_size 的去噪 PIL 图像列表,或形状为 (batch_size, height, width, num_channels) 的 NumPy 数组。

图像管道的输出类。

< > 在 GitHub 上更新