Diffusers 文档

MultiDiffusion

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始

MultiDiffusion

MultiDiffusion:融合扩散路径以实现可控图像生成 由 Omer Bar-Tal、Lior Yariv、Yaron Lipman 和 Tali Dekel 撰写。

论文摘要如下:

最近扩散模型在文本到图像生成方面的进展,为图像质量带来了变革性的能力。然而,用户对生成图像的可控性,以及快速适应新任务仍然是一个开放的挑战,目前主要通过代价高昂且耗时的再训练和微调,或针对特定图像生成任务的临时调整来解决。在这项工作中,我们提出了 MultiDiffusion,这是一个统一的框架,可以使用预训练的文本到图像扩散模型,无需任何进一步的训练或微调,即可实现通用且可控的图像生成。我们方法的核心是一个新的生成过程,它基于一个优化任务,该任务将多个扩散生成过程与一组共享的参数或约束绑定在一起。我们表明,MultiDiffusion 可以轻松应用于生成高质量和多样化的图像,这些图像符合用户提供的控制,例如所需的宽高比(例如,全景图)和空间引导信号,范围从严格的分割掩码到边界框。

您可以在项目页面原始代码库上找到关于 MultiDiffusion 的更多信息,并在演示中尝试使用它。

提示

当调用 StableDiffusionPanoramaPipeline 时,可以指定 view_batch_size 参数为 > 1。对于某些高性能 GPU,这可以加速生成过程并增加 VRAM 使用量。

要生成类似全景图的图像,请确保您相应地传递 width 参数。我们建议宽度值为 2048,这是默认值。

应用圆形填充是为了确保在处理全景图时没有拼接伪影,以确保从最右边部分到最左边部分的无缝过渡。通过启用圆形填充(设置 circular_padding=True),该操作会在图像最右点之后应用额外的裁剪,使模型能够“看到”从最右边部分到最左边部分的过渡。这有助于在 360 度意义上保持视觉一致性,并创建可以使用 360 度全景查看器查看的适当“全景图”。当在 Stable Diffusion 中解码潜在空间时,应用圆形填充以确保解码后的潜在空间在 RGB 空间中匹配。

例如,在没有圆形填充的情况下,会存在拼接伪影(默认): img

但是使用圆形填充后,右侧和左侧部分是匹配的 (circular_padding=True): img

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

StableDiffusionPanoramaPipeline

class diffusers.StableDiffusionPanoramaPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: DDIMScheduler safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: typing.Optional[transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection] = None requires_safety_checker: bool = True )

参数

  • vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示形式,以及从潜在表示形式解码为图像。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用于对文本进行标记化的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 用于对编码后的图像潜在空间进行去噪的 UNet2DConditionModel
  • scheduler (SchedulerMixin) — 调度器,与 unet 结合使用,以对编码后的图像潜在空间进行去噪。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • safety_checker (StableDiffusionSafetyChecker) — 分类模块,用于估计生成的图像是否可能被认为是冒犯性或有害的。有关模型潜在危害的更多详细信息,请参阅模型卡
  • feature_extractor (CLIPImageProcessor) — CLIPImageProcessor,用于从生成的图像中提取特征;用作 safety_checker 的输入。

使用 MultiDiffusion 进行文本到图像生成的 Pipeline。

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

该 pipeline 还继承了以下加载方法

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None height: typing.Optional[int] = 512 width: typing.Optional[int] = 2048 num_inference_steps: int = 50 timesteps: typing.List[int] = None guidance_scale: float = 7.5 view_batch_size: int = 1 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 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 ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None guidance_rescale: float = 0.0 circular_padding: bool = False clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **kwargs: typing.Any ) StableDiffusionPipelineOutput or tuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示。如果未定义,则需要传递 prompt_embeds
  • height (int, 可选, 默认为 512) — 生成图像的高度像素值。
  • width (int, 可选, 默认为 2048) — 生成图像的宽度像素值。宽度保持较高值是因为该 pipeline 旨在生成类似全景图的图像。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但会以较慢的推理速度为代价。
  • timesteps (List[int], 可选) — 用于生成图像的时间步长。如果未指定,则使用调度器的默认时间步长策略。
  • guidance_scale (float, 可选, 默认为 7.5) — 更高的 guidance scale 值会鼓励模型生成与文本 prompt 紧密相关的图像,但会以降低图像质量为代价。当 guidance_scale > 1 时,启用 Guidance scale。
  • view_batch_size (int, 可选, 默认为 1) — 用于去噪分割视图的批处理大小。对于某些高性能 GPU,更高的 view batch size 可以加速生成并增加 VRAM 使用量。
  • negative_prompt (strList[str], 可选) — 用于引导图像生成中不应包含的内容的提示。如果未定义,则需要传递 negative_prompt_embeds 代替。当不使用 guidance 时(guidance_scale < 1),将被忽略。
  • num_images_per_prompt (int, optional, defaults to 1) — 每个提示生成的图像数量。
  • eta (float, optional, defaults to 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中将被忽略。
  • generator (torch.Generator or List[torch.Generator], optional) — 用于使生成过程具有确定性的 torch.Generator
  • latents (torch.Tensor, optional) — 预生成的、从高斯分布中采样的噪声潜变量,用作图像生成的输入。可用于通过不同的提示调整相同的生成结果。如果未提供,则会通过使用提供的随机 generator 进行采样来生成潜变量张量。
  • prompt_embeds (torch.Tensor, optional) — 预生成的文本嵌入。可用于轻松调整文本输入(提示词权重)。如果未提供,则会从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, optional) — 预生成的负面文本嵌入。可用于轻松调整文本输入(提示词权重)。如果未提供,则会从 negative_prompt 输入参数生成 negative_prompt_embeds
  • ip_adapter_image — (PipelineImageInput, optional): 用于 IP 适配器的可选图像输入。
  • ip_adapter_image_embeds (List[torch.Tensor], optional) — IP 适配器的预生成图像嵌入。它应该是一个列表,长度与 IP 适配器的数量相同。每个元素都应该是一个形状为 (batch_size, num_images, emb_dim) 的张量。如果 do_classifier_free_guidance 设置为 True,则应包含负面图像嵌入。如果未提供,则会从 ip_adapter_image 输入参数计算嵌入。
  • output_type (str, optional, defaults to "pil") — 生成图像的输出格式。在 PIL.Imagenp.array 之间选择。
  • return_dict (bool, optional, defaults to True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, optional) — 一个 kwargs 字典,如果指定,则会传递给 diffusers.models.attention_processorself.processor 下定义的 AttentionProcessor
  • guidance_rescale (float, optional, defaults to 0.0) — 指导嵌入的重新缩放因子。值为 0.0 表示不应用重新缩放。
  • circular_padding (bool, optional, defaults to False) — 如果设置为 True,则应用循环填充以确保没有拼接伪影。循环填充允许模型无缝地生成从图像最右部分到最左部分的过渡,从而在 360 度意义上保持一致性。
  • clip_skip (int, optional) — 从 CLIP 中跳过的层数,用于计算提示词嵌入。值为 1 表示将使用预最终层的输出计算提示词嵌入。
  • callback_on_step_end (Callable, optional) — 在推理期间每个去噪步骤结束时调用的函数。该函数被调用时带有以下参数:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)callback_kwargs 将包含 callback_on_step_end_tensor_inputs 指定的所有张量列表。
  • callback_on_step_end_tensor_inputs (List[str], optional) — callback_on_step_end 函数的张量输入列表。列表中指定的张量将作为 callback_kwargs 参数传递。您将只能包含管道类 ._callback_tensor_inputs 属性中列出的变量。

返回

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,则返回 StableDiffusionPipelineOutput,否则返回一个 tuple,其中第一个元素是包含生成图像的列表,第二个元素是 bool 列表,指示相应的生成图像是否包含“不适合工作场所”(nsfw)内容。

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

示例

>>> import torch
>>> from diffusers import StableDiffusionPanoramaPipeline, DDIMScheduler

>>> model_ckpt = "stabilityai/stable-diffusion-2-base"
>>> scheduler = DDIMScheduler.from_pretrained(model_ckpt, subfolder="scheduler")
>>> pipe = StableDiffusionPanoramaPipeline.from_pretrained(
...     model_ckpt, scheduler=scheduler, torch_dtype=torch.float16
... )

>>> pipe = pipe.to("cuda")

>>> prompt = "a photo of the dolomites"
>>> image = pipe(prompt).images[0]

decode_latents_with_padding

< >

( latents: Tensor padding: int = 8 ) torch.Tensor

参数

  • latents (torch.Tensor) — 要解码的输入潜变量。
  • padding (int, optional) — 在每一侧添加的潜变量数量,用于填充。默认为 8。

返回

torch.Tensor

移除填充后的解码图像。

解码给定的带有填充的潜变量,用于循环推理。

注释

  • 添加填充是为了消除边界伪影并提高输出质量。
  • 这会稍微增加内存使用量。
  • 然后从解码后的图像中移除填充像素。

encode_prompt

< >

( prompt device num_images_per_prompt do_classifier_free_guidance negative_prompt = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

参数

  • prompt (str or List[str], optional) — 要编码的提示词
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用无分类器指导
  • negative_prompt (str or List[str], optional) — 不引导图像生成的提示词或提示词列表。如果未定义,则必须传递 negative_prompt_embeds。当不使用指导时(即,如果 guidance_scale 小于 1),将被忽略。
  • prompt_embeds (torch.Tensor, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, optional) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • lora_scale (float, optional) — 如果加载了 LoRA 层,则将应用于文本编码器所有 LoRA 层的 LoRA 缩放比例。
  • clip_skip (int, optional) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示预最终层的输出将用于计算提示嵌入。

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

get_guidance_scale_embedding

< >

( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) torch.Tensor

参数

  • w (torch.Tensor) — 生成具有指定引导比例的嵌入向量,以随后丰富时间步长嵌入。
  • embedding_dim (int, optional, defaults to 512) — 要生成的嵌入的维度。
  • dtype (torch.dtype, optional, defaults to torch.float32) — 生成的嵌入的数据类型。

返回

torch.Tensor

形状为 (len(w), embedding_dim) 的嵌入向量。

参见 https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

get_views

< >

( panorama_height: int panorama_width: int window_size: int = 64 stride: int = 8 circular_padding: bool = False ) List[Tuple[int, int, int, int]]

参数

  • panorama_height (int) — 全景图的高度。
  • panorama_width (int) — 全景图的宽度。
  • window_size (int, optional) — 窗口大小。默认为 64。
  • stride (int, optional) — 步幅值。默认为 8。
  • circular_padding (bool, optional) — 是否应用循环填充。默认为 False。

返回

List[Tuple[int, int, int, int]]

表示视图的元组列表。每个元组包含四个整数,表示全景图中窗口的起始和结束坐标。

根据给定参数生成视图列表。 这里,我们定义了映射 F_i(参见 MultiDiffusion 论文 https://arxiv.org/abs/2302.08113 中的公式 7)。 如果全景图的高度/宽度 < window_size,则高度/宽度的 num_blocks 应返回 1。

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] or np.ndarray) — 长度为 batch_size 的去噪 PIL 图像列表或形状为 (batch_size, height, width, num_channels) 的 NumPy 数组。
  • nsfw_content_detected (List[bool]) — 列表,指示相应的生成图像是否包含“不适合工作场所观看”(nsfw)内容;如果无法执行安全检查,则为 None

Stable Diffusion 管道的输出类。

< > Update on GitHub