Diffusers 文档

潜扩散

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

潜在扩散

潜在扩散是由 Robin Rombach、Andreas Blattmann、Dominik Lorenz、Patrick Esser 和 Björn Ommer 在 高分辨率图像合成与潜在扩散模型 中提出的。

论文摘要如下:

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

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

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

LDMTextToImagePipeline

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 结合使用的调度器,用于对编码图像潜在表示进行去噪。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。

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

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

__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) — 更高的引导比例值鼓励模型生成与文本 prompt 紧密相关的图像,但图像质量会降低。当 guidance_scale > 1 时,启用引导比例。
  • generator (torch.Generator, 可选) — 用于使生成具有确定性的 torch.Generator
  • latents (torch.Tensor, 可选) — 从高斯分布中采样的预生成噪声潜在表示,用作图像生成的输入。可用于使用不同的提示调整相同的生成。如果未提供,则使用提供的随机 generator 进行采样生成潜在张量。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。在 PIL.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ImagePipelineOutput 而不是纯元组。

返回

ImagePipelineOutputtuple

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

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

示例

>>> 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: 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] )

参数

用于使用潜在扩散进行图像超分辨率的管道。

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

__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) — 用作流程起点的图像或表示图像批次的张量。
  • 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,其中第一个元素是生成的图像列表。

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

示例

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