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

潜在一致性模型

LoRA

Latent Consistency Models: Synthesizing High-Resolution Images with Few-Step Inference 一文的作者 Simian Luo、Yiqin Tan、Longbo Huang、Jian Li 和 Hang Zhao 提出了潜在一致性模型(Latent Consistency Models,LCM)。

该论文的摘要如下:

潜在扩散模型(LDMs)在合成高分辨率图像方面取得了显著成果。然而,迭代采样过程计算开销大,导致生成速度缓慢。受一致性模型(Consistency Models,song et al.)的启发,我们提出了潜在一致性模型(LCMs),能够在任意预训练 LDM(包括 Stable Diffusion,rombach et al.)上以极少步数实现快速推理。将带引导的反向扩散过程视为求解一个增广的概率流常微分方程(PF-ODE),LCMs 被设计为直接在潜在空间中预测该 ODE 的解,从而减少了对大量迭代的需求,并允许快速、高保真的采样。从预训练的分类器自由引导扩散模型中高效蒸馏后,一个高质量的 768 x 768 2~4 步 LCM 仅需 32 个 A100 GPU 小时进行训练。此外,我们引入了潜在一致性微调(LCF),这是一种专为在自定义图像数据集上微调 LCMs 而设计的新方法。在 LAION-5B-Aesthetics 数据集上的评估表明,LCMs 在少步推理下实现了最先进的文本到图像生成性能。项目主页:this https URL。

SimianLuo/LCM_Dreamshaper_v7 检查点的演示可在此处找到。

这些流水线由 luosiallen、nagolinc 和 dg845 贡献。

LCM 和 LCM-LoRA 适用于 Stable Diffusion v1.5、Stable Diffusion XL 以及 SSD-1B 模型。您可以在 Latent Consistency 集合中找到它们的检查点。

文本到图像

LCM
LCM-LoRA

要使用 LCM,你需要将受支持模型的 LCM 检查点加载到 UNet2DConditionModel 中,并将调度器替换为 LCMScheduler。之后,你可以像往常一样使用流水线,并传入文本提示,仅需 4 步即可生成图像。

使用 LCM 时,有几点需要注意:

  • 通常,在管道内部,batch size 会加倍以实现 classifier-free guidance。但 LCM 通过 guidance embeddings 来应用 guidance,因此无需加倍 batch size,从而带来更快的推理速度。其缺点是,negative prompts 在 LCM 中不起作用,因为它们对去噪过程没有任何影响。
  • guidance_scale 的理想取值范围是 [3., 13.],因为 UNet 就是在这个范围内进行训练的。不过,在大多数情况下,将 guidance_scale 设为 1.0 以禁用该参数同样有效。
from diffusers import StableDiffusionXLPipeline, UNet2DConditionModel, LCMScheduler
import torch

unet = UNet2DConditionModel.from_pretrained(
    "latent-consistency/lcm-sdxl",
    dtype=torch.float16,
    variant="fp16",
)
pipe = StableDiffusionXLPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", unet=unet, dtype=torch.float16, variant="fp16",
).to("cuda")  # or "mps", "xpu", "cpu"
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)

prompt = "Self-portrait oil painting, a beautiful cyborg with golden hair, 8k"
generator = torch.manual_seed(0)
image = pipe(
    prompt=prompt, num_inference_steps=4, generator=generator, guidance_scale=8.0
).images[0]
image

图像到图像

LCM
LCM-LoRA

要在图像到图像任务中使用 LCM,你需要将受支持模型的 LCM 检查点加载到 UNet2DConditionModel 中,并将调度器替换为 LCMScheduler。之后,你可以像往常一样使用该流水线,传入文本提示和初始图像,仅需 4 步即可生成图像。

尝试调整 num_inference_steps、strength 和 guidance_scale 的不同取值,以获得最佳效果。

import torch
from diffusers import AutoPipelineForImage2Image, UNet2DConditionModel, LCMScheduler
from diffusers.utils import load_image

unet = UNet2DConditionModel.from_pretrained(
    "SimianLuo/LCM_Dreamshaper_v7",
    subfolder="unet",
    dtype=torch.float16,
)

pipe = AutoPipelineForImage2Image.from_pretrained(
    "Lykon/dreamshaper-7",
    unet=unet,
    dtype=torch.float16,
    variant="fp16",
).to("cuda")  # or "mps", "xpu", "cpu"
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)

init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png")
prompt = "Astronauts in a jungle, cold color palette, muted colors, detailed, 8k"
generator = torch.manual_seed(0)
image = pipe(
    prompt,
    image=init_image,
    num_inference_steps=4,
    guidance_scale=7.5,
    strength=0.5,
    generator=generator
).images[0]
image
初始图像
生成的图像

图像修复

要在图像修复中使用 LCM-LoRA,您需要将调度器替换为 LCMScheduler,并使用 load_lora_weights() 方法加载 LCM-LoRA 权重。之后,您可以像往常一样使用该流水线,传入文本提示、初始图像和掩码图像,仅需 4 步即可生成图像。

import torch
from diffusers import AutoPipelineForInpainting, LCMScheduler
from diffusers.utils import load_image, make_image_grid

pipe = AutoPipelineForInpainting.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-inpainting",
    dtype=torch.float16,
    variant="fp16",
).to("cuda")  # or "mps", "xpu", "cpu"

pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)

pipe.load_lora_weights("latent-consistency/lcm-lora-sdv1-5")

init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png")
mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint_mask.png")

prompt = "concept art digital painting of an elven castle, inspired by lord of the rings, highly detailed, 8k"
generator = torch.manual_seed(0)
image = pipe(
    prompt=prompt,
    image=init_image,
    mask_image=mask_image,
    generator=generator,
    num_inference_steps=4,
    guidance_scale=4,
).images[0]
image
初始图像
生成的图像

适配器

LCM 与 LoRA、ControlNet、T2I-Adapter 和 AnimateDiff 等适配器兼容。您可以将 LCM 的速度优势应用于这些适配器,以生成特定风格的图像,或基于其他输入(例如 canny 图像)对模型进行条件约束。

LoRA

LoRA 适配器可以快速微调,仅从少量图像中学习新的风格,然后插入预训练模型中,以生成该风格的图像。

LCM
LCM-LoRA

将受支持模型的 LCM 检查点加载到 UNet2DConditionModel 中,并将调度器替换为 LCMScheduler。然后,您可以使用 load_lora_weights() 方法将 LoRA 权重加载到 LCM 中,并在几步内生成一张风格化图像。

from diffusers import StableDiffusionXLPipeline, UNet2DConditionModel, LCMScheduler
import torch

unet = UNet2DConditionModel.from_pretrained(
    "latent-consistency/lcm-sdxl",
    dtype=torch.float16,
    variant="fp16",
)
pipe = StableDiffusionXLPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", unet=unet, dtype=torch.float16, variant="fp16",
).to("cuda")  # or "mps", "xpu", "cpu"
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
pipe.load_lora_weights("TheLastBen/Papercut_SDXL", weight_name="papercut.safetensors", adapter_name="papercut")

prompt = "papercut, a cute fox"
generator = torch.manual_seed(0)
image = pipe(
    prompt=prompt, num_inference_steps=4, generator=generator, guidance_scale=8.0
).images[0]
image

ControlNet

ControlNet 是一种适配器,可针对多种输入进行训练,例如 canny 边缘、姿态估计或深度图。将 ControlNet 插入流水线中,可以为模型提供额外的条件约束和控制,从而实现更精确的生成。

您可以在 lllyasviel 的仓库中找到使用其他输入训练的更多 ControlNet 模型。

LCM
LCM-LoRA

加载一个在 canny 图像上训练的 ControlNet 模型,并将其传递给 ControlNetModel。然后,你可以将 LCM 模型加载到 StableDiffusionControlNetPipeline 中,并用 LCMScheduler 替换调度器。现在,将 canny 图像传递给流水线并生成图像。

尝试调整 num_inference_steps、controlnet_conditioning_scale、cross_attention_kwargs 和 guidance_scale 的不同取值,以获得最佳效果。

import torch
import cv2
import numpy as np
from PIL import Image

from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, LCMScheduler
from diffusers.utils import load_image, make_image_grid

image = load_image(
    "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
).resize((512, 512))

image = np.array(image)

low_threshold = 100
high_threshold = 200

image = cv2.Canny(image, low_threshold, high_threshold)
image = image[:, :, None]
image = np.concatenate([image, image, image], axis=2)
canny_image = Image.fromarray(image)

controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", dtype=torch.float16)
pipe = StableDiffusionControlNetPipeline.from_pretrained(
    "SimianLuo/LCM_Dreamshaper_v7",
    controlnet=controlnet,
    dtype=torch.float16,
    safety_checker=None,
).to("cuda")  # or "mps", "xpu", "cpu"
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)

generator = torch.manual_seed(0)
image = pipe(
    "the mona lisa",
    image=canny_image,
    num_inference_steps=4,
    generator=generator,
).images[0]
make_image_grid([canny_image, image], rows=1, cols=2)

T2I-Adapter

T2I-Adapter 是一种比 ControlNet 更轻量级的适配器,它为预训练模型提供了额外的条件输入。它的速度比 ControlNet 更快,但结果可能会稍差一些。

您可以在 TencentArc 的仓库中找到在其他输入上训练的其他 T2I-Adapter 检查点。

LCM
LCM-LoRA

加载一个在 canny 图像上训练好的 T2IAdapter,并将其传递给 StableDiffusionXLAdapterPipeline。然后将 LCM 检查点加载到 UNet2DConditionModel 中,并将调度器替换为 LCMScheduler。现在将 canny 图像传递给流水线并生成图像。

import torch
import cv2
import numpy as np
from PIL import Image

from diffusers import StableDiffusionXLAdapterPipeline, UNet2DConditionModel, T2IAdapter, LCMScheduler
from diffusers.utils import load_image, make_image_grid

# detect the canny map in low resolution to avoid high-frequency details
image = load_image(
    "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
).resize((384, 384))

image = np.array(image)

low_threshold = 100
high_threshold = 200

image = cv2.Canny(image, low_threshold, high_threshold)
image = image[:, :, None]
image = np.concatenate([image, image, image], axis=2)
canny_image = Image.fromarray(image).resize((1024, 1216))

adapter = T2IAdapter.from_pretrained("TencentARC/t2i-adapter-canny-sdxl-1.0", dtype=torch.float16, variant="fp16").to("cuda")  # or "mps", "xpu", "cpu"

unet = UNet2DConditionModel.from_pretrained(
    "latent-consistency/lcm-sdxl",
    dtype=torch.float16,
    variant="fp16",
)
pipe = StableDiffusionXLAdapterPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    unet=unet,
    adapter=adapter,
    dtype=torch.float16,
    variant="fp16",
).to("cuda")

pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)

prompt = "the mona lisa, 4k picture, high quality"
negative_prompt = "extra digit, fewer digits, cropped, worst quality, low quality, glitch, deformed, mutated, ugly, disfigured"

generator = torch.manual_seed(0)
image = pipe(
    prompt=prompt,
    negative_prompt=negative_prompt,
    image=canny_image,
    num_inference_steps=4,
    guidance_scale=5,
    adapter_conditioning_scale=0.8,
    adapter_conditioning_factor=1,
    generator=generator,
).images[0]

AnimateDiff

AnimateDiff 是一个为图像添加动态效果的适配器。它可以与大多数 Stable Diffusion 模型配合使用,从而将这些模型有效地转变为“视频生成”模型。使用视频模型生成高质量结果通常需要生成多帧(16-24 帧),而使用常规的 Stable Diffusion 模型时这一过程可能非常缓慢。LCM-LoRA 可以将每帧的步数减少到 4-8 步,从而加速这一过程。

加载一个 AnimateDiffPipeline,并向其传入一个 MotionAdapter。然后将调度器替换为 LCMScheduler,并使用 ~loaders.UNet2DConditionLoadersMixin.set_adapters 方法将两个 LoRA 适配器组合起来。现在,你可以向流水线传入提示词并生成动画图像。

import torch
from diffusers import MotionAdapter, AnimateDiffPipeline, DDIMScheduler, LCMScheduler
from diffusers.utils import export_to_gif

adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5")
pipe = AnimateDiffPipeline.from_pretrained(
    "frankjoshua/toonyou_beta6",
    motion_adapter=adapter,
).to("cuda")  # or "mps", "xpu", "cpu"

# set scheduler
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)

# load LCM-LoRA
pipe.load_lora_weights("latent-consistency/lcm-lora-sdv1-5", adapter_name="lcm")
pipe.load_lora_weights("guoyww/animatediff-motion-lora-zoom-in", weight_name="diffusion_pytorch_model.safetensors", adapter_name="motion-lora")

pipe.set_adapters(["lcm", "motion-lora"], adapter_weights=[0.55, 1.2])

prompt = "best quality, masterpiece, 1girl, looking at viewer, blurry background, upper body, contemporary, dress"
generator = torch.manual_seed(0)
frames = pipe(
    prompt=prompt,
    num_inference_steps=5,
    guidance_scale=1.25,
    cross_attention_kwargs={"scale": 1},
    num_frames=24,
    generator=generator
).frames[0]
export_to_gif(frames, "animation.gif")

LatentConsistencyModelPipeline

class diffusers.LatentConsistencyModelPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModelscheduler: LCMSchedulersafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilimage_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection | None = Nonerequires_safety_checker: bool = True )

参数

  • vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码为图像。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用于对文本进行分词的 CLIPTokenizer。
  • unet (UNet2DConditionModel) — 用于对编码后的图像潜变量进行去噪的 UNet2DConditionModel。
  • scheduler (SchedulerMixin) — 用于与 unet 配合,对编码后的图像潜变量进行去噪的调度器。目前仅支持 LCMScheduler。
  • safety_checker (StableDiffusionSafetyChecker) — 用于评估生成图像是否可能被视为冒犯性或有害的分类模块。 有关模型潜在危害的更多详细信息,请参阅模型卡片。
  • feature_extractor (CLIPImageProcessor) — 一个 CLIPImageProcessor,用于从生成的图像中提取特征;作为 safety_checker 的输入。
  • requires_safety_checker (bool,可选,默认为 True) — 该流水线是否需要安全检测器组件。

使用潜在一致性模型进行文本到图像生成的 Pipeline。

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

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

__call__

< >

( prompt: str | list[str] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 4original_inference_steps: int = Nonetimesteps: list = Noneguidance_scale: float = 8.5num_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']**kwargs ) → StableDiffusionPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则需要传入 prompt_embeds。
  • 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) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • original_inference_steps (int, 可选) — 用于生成线性间隔时间步调度的原始推理步数。我们将从中均匀抽取 num_inference_steps 个时间步,作为最终的时间步调度,遵循论文中的 Skipping-Step 方法(参见第 4.3 节)。如果未设置,则默认为调度器的 original_inference_steps 属性。
  • timesteps (list[int], 可选) — 用于去噪过程的自定义时间步。如果未定义,则使用原始 LCM 训练/蒸馏时间步调度上均匀间隔的 num_inference_steps 个时间步。必须按降序排列。
  • guidance_scale (float,可选,默认值为 7.5) — 较高的 guidance scale 值会促使模型生成与文本 prompt 紧密相关的图像,但代价是图像质量降低。当 guidance_scale > 1 时启用 guidance scale。 请注意,原始的 latent consistency models 论文采用了不同的 CFG 公式,其中 guidance scale 会减少 1(因此在论文的公式中,当 guidance_scale > 0 时启用 CFG)。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 用于使生成过程确定性的 torch.Generator。
  • latents (torch.Tensor, 可选) — 预先生成的、从高斯分布中采样的含噪潜变量,用作图像生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供,则使用提供的随机generator进行采样,生成一个潜变量张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示词加权)。如果未提供,则从 prompt 输入参数生成文本嵌入。
  • ip_adapter_image — (PipelineImageInput,可选): 用于配合 IP Adapter 使用的可选图像输入。
  • ip_adapter_image_embeds (list[torch.Tensor], 可选) — IP-Adapter 的预生成图像嵌入。它应是一个列表,长度与 IP-Adapter 的数量相同。每个元素应为形状为 (batch_size, num_images, emb_dim) 的张量。如果 do_classifier_free_guidance 设置为 True,则应包含负向图像嵌入。如果未提供,嵌入将从 ip_adapter_image 输入参数计算得出。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选 PIL.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 self.processor 中定义的 AttentionProcessor。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
  • callback_on_step_end (Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用: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,可选) — callback_on_step_end 函数的张量输入列表。列表中指定的张量将作为 callback_kwargs 参数传递。您只能包含流水线类 ._callback_tensor_inputs 属性中列出的变量。

返回值

StableDiffusionPipelineOutput 或 tuple

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

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

示例:

>>> from diffusers import DiffusionPipeline
>>> import torch

>>> pipe = DiffusionPipeline.from_pretrained("SimianLuo/LCM_Dreamshaper_v7")
>>> # To save GPU memory, torch.float16 can be used, but it may compromise image quality.
>>> pipe.to(torch_device="cuda", torch_dtype=torch.float32)

>>> prompt = "Self-portrait oil painting, a beautiful cyborg with golden hair, 8k"

>>> # Can be set to 1~50 steps. LCM support fast inference even <= 4 steps. Recommend: 1~8 steps.
>>> num_inference_steps = 4
>>> images = pipe(prompt=prompt, num_inference_steps=num_inference_steps, guidance_scale=8.0).images
>>> images[0].save("image.png")

enable_freeu

< >

( s1: floats2: floatb1: floatb2: float )

参数

  • s1 (float) — 用于第一阶段的比例因子,用于衰减跳跃特征的贡献。这样做是为了缓解增强去噪过程中的“过度平滑效应”。
  • s2 (float) — 用于衰减跳跃特征贡献的第二阶段缩放因子。这样做是为了缓解增强去噪过程中的“过度平滑效应”。
  • b1 (float) — 用于放大骨干网络特征贡献的第一阶段缩放因子。
  • b2 (float) — 用于放大骨干网络特征贡献的第二阶段缩放因子。

启用 https://huggingface.co/papers/2309.11497 中所述的 FreeU 机制。

缩放因子后面的后缀表示它们被应用的阶段。

有关适用于 Stable Diffusion v1、v2 和 Stable Diffusion XL 等不同流水线的已知良好参数组合,请参阅官方仓库。

disable_freeu

< >

( )

如果已启用,则禁用 FreeU 机制。

encode_prompt

< >

( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

参数

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

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

get_guidance_scale_embedding

< >

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

参数

  • w (torch.Tensor) — 生成具有指定 guidance scale 的嵌入向量,以用于后续丰富时间步嵌入。
  • embedding_dim (int,可选,默认为 512) — 要生成的嵌入的维度。
  • dtype (torch.dtype,可选,默认为 torch.float32) — 生成嵌入的数据类型。

返回值

torch.Tensor

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

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

LatentConsistencyModelImg2ImgPipeline

class diffusers.LatentConsistencyModelImg2ImgPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModelscheduler: LCMSchedulersafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilimage_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection | None = Nonerequires_safety_checker: bool = True )

参数

  • vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码为图像。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用于对文本进行分词的 CLIPTokenizer。
  • unet (UNet2DConditionModel) — 用于对编码后的图像潜变量进行去噪的 UNet2DConditionModel。
  • scheduler (SchedulerMixin) — 用于与 unet 配合,对编码后的图像潜变量进行去噪的调度器。目前仅支持 LCMScheduler。
  • safety_checker (StableDiffusionSafetyChecker) — 用于评估生成图像是否可能被视为冒犯性或有害的分类模块。 有关模型潜在危害的更多详细信息,请参阅模型卡片。
  • feature_extractor (CLIPImageProcessor) — 一个 CLIPImageProcessor,用于从生成的图像中提取特征;作为 safety_checker 的输入。
  • requires_safety_checker (bool,可选,默认为 True) — 该流水线是否需要安全检测器组件。

使用潜在一致性模型进行图像到图像生成的 Pipeline。

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

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

__call__

< >

( prompt: str | list[str] = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonenum_inference_steps: int = 4strength: float = 0.8original_inference_steps: int = Nonetimesteps: list = Noneguidance_scale: float = 8.5num_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']**kwargs ) → StableDiffusionPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则需要传入 prompt_embeds。
  • image (torch.Tensor、PIL.Image.Image、np.ndarray、list[torch.Tensor]、list[PIL.Image.Image] 或 list[np.ndarray]) — Image 或表示图像批次的张量,用作起始点。也可以接受图像潜在表示作为 image,但如果直接传入潜在表示,则不会再次进行编码。
  • num_inference_steps (int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • strength (float, 可选,默认为 0.8) — 指示对参考 image 进行变换的程度。取值必须在 0 到 1 之间。image 用作起始点,strength 越高,添加的噪声越多。去噪步数取决于初始添加的噪声量。当 strength 为 1 时,添加的噪声达到最大值,去噪过程将运行 num_inference_steps 中指定的完整迭代次数。值为 1 时,基本上会忽略 image。
  • original_inference_steps (int, 可选) — 用于生成线性间隔时间步调度的原始推理步数,我们将从中均匀抽取 num_inference_steps 个时间步作为最终的时间步调度,遵循论文中的 Skipping-Step 方法(参见第 4.3 节)。如果未设置,则默认为调度器的 original_inference_steps 属性。
  • timesteps (list[int], 可选) — 用于去噪过程的自定义时间步。如果未定义,则使用原始 LCM 训练/蒸馏时间步调度上均匀间隔的 num_inference_steps 个时间步。必须按降序排列。
  • guidance_scale (float,可选,默认值为 7.5) — 较高的 guidance scale 值会促使模型生成与文本 prompt 紧密相关的图像,但代价是图像质量降低。当 guidance_scale > 1 时启用 guidance scale。 请注意,原始的 latent consistency models 论文采用了不同的 CFG 公式,其中 guidance scale 会减少 1(因此在论文的公式中,当 guidance_scale > 0 时启用 CFG)。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 用于使生成过程确定性的 torch.Generator。
  • latents (torch.Tensor, 可选) — 预先生成的、从高斯分布中采样的含噪潜变量,用作图像生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供,则使用提供的随机generator进行采样,生成一个潜变量张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示词加权)。如果未提供,则从 prompt 输入参数生成文本嵌入。
  • ip_adapter_image — (PipelineImageInput,可选): 用于配合 IP Adapter 使用的可选图像输入。
  • ip_adapter_image_embeds (list[torch.Tensor], 可选) — IP-Adapter 的预生成图像嵌入。它应是一个列表,长度与 IP-Adapter 的数量相同。每个元素应为形状为 (batch_size, num_images, emb_dim) 的张量。如果 do_classifier_free_guidance 设置为 True,则应包含负向图像嵌入。如果未提供,嵌入将从 ip_adapter_image 输入参数计算得出。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选 PIL.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 self.processor 中定义的 AttentionProcessor。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
  • callback_on_step_end (Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用: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,可选) — callback_on_step_end 函数的张量输入列表。列表中指定的张量将作为 callback_kwargs 参数传递。您只能包含流水线类 ._callback_tensor_inputs 属性中列出的变量。

返回值

StableDiffusionPipelineOutput 或 tuple

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

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

示例:

>>> from diffusers import AutoPipelineForImage2Image
>>> import torch
>>> import PIL

>>> pipe = AutoPipelineForImage2Image.from_pretrained("SimianLuo/LCM_Dreamshaper_v7")
>>> # To save GPU memory, torch.float16 can be used, but it may compromise image quality.
>>> pipe.to(torch_device="cuda", torch_dtype=torch.float32)

>>> prompt = "High altitude snowy mountains"
>>> image = PIL.Image.open("./snowy_mountains.png")

>>> # Can be set to 1~50 steps. LCM support fast inference even <= 4 steps. Recommend: 1~8 steps.
>>> num_inference_steps = 4
>>> images = pipe(
...     prompt=prompt, image=image, num_inference_steps=num_inference_steps, guidance_scale=8.0
... ).images

>>> images[0].save("image.png")

enable_freeu

< >

( s1: floats2: floatb1: floatb2: float )

参数

  • s1 (float) — 用于第一阶段的比例因子,用于衰减跳跃特征的贡献。这样做是为了缓解增强去噪过程中的“过度平滑效应”。
  • s2 (float) — 用于衰减跳跃特征贡献的第二阶段缩放因子。这样做是为了缓解增强去噪过程中的“过度平滑效应”。
  • b1 (float) — 用于放大骨干网络特征贡献的第一阶段缩放因子。
  • b2 (float) — 用于放大骨干网络特征贡献的第二阶段缩放因子。

启用 https://huggingface.co/papers/2309.11497 中所述的 FreeU 机制。

缩放因子后面的后缀表示它们被应用的阶段。

有关适用于 Stable Diffusion v1、v2 和 Stable Diffusion XL 等不同流水线的已知良好参数组合,请参阅官方仓库。

disable_freeu

< >

( )

如果已启用,则禁用 FreeU 机制。

encode_prompt

< >

( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

参数

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

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

get_guidance_scale_embedding

< >

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

参数

  • w (torch.Tensor) — 生成具有指定 guidance scale 的嵌入向量,以用于后续丰富时间步嵌入。
  • embedding_dim (int,可选,默认为 512) — 要生成的嵌入的维度。
  • dtype (torch.dtype,可选,默认为 torch.float32) — 生成嵌入的数据类型。

返回值

torch.Tensor

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

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

StableDiffusionPipelineOutput

类 diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput

< >

( images: list[PIL.Image.Image] | numpy.ndarraynsfw_content_detected: list[bool] | None )

参数

  • 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 管道的输出类。

Update on GitHub