# 潜在一致性模型

  

[Latent Consistency Models: Synthesizing High-Resolution Images with Few-Step Inference](https://huggingface.co/papers/2310.04378) 一文的作者 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](https://latent-consistency-models.github.io/)。*

[SimianLuo/LCM_Dreamshaper_v7](https://huggingface.co/SimianLuo/LCM_Dreamshaper_v7) 检查点的演示可在[此处](https://huggingface.co/spaces/SimianLuo/Latent_Consistency_Model)找到。

这些流水线由 [luosiallen](https://luosiallen.github.io/)、[nagolinc](https://github.com/nagolinc) 和 [dg845](https://github.com/dg845) 贡献。

> [!TIP]
> LCM 和 LCM-LoRA 适用于 Stable Diffusion v1.5、Stable Diffusion XL 以及 SSD-1B 模型。您可以在 [Latent Consistency](https://hf.co/collections/latent-consistency/latent-consistency-models-weights-654ce61a95edd6dffccef6a8) 集合中找到它们的检查点。

## 文本到图像

要使用 LCM，你需要将受支持模型的 LCM 检查点加载到 [UNet2DConditionModel](/docs/diffusers/v0.43.0/zh/api/models/unet2d-cond#diffusers.UNet2DConditionModel) 中，并将调度器替换为 [LCMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/lcm#diffusers.LCMScheduler)。之后，你可以像往常一样使用流水线，并传入文本提示，仅需 4 步即可生成图像。

使用 LCM 时，有几点需要注意：

* 通常，在管道内部，为了进行无分类器引导（classifier-free guidance），批量大小（batch size）会加倍。但 LCM 通过引导嵌入（guidance embeddings）来应用引导，因此无需加倍批量大小，从而实现了更快的推理速度。其缺点是，负提示词（negative prompts）在 LCM 中不起作用，因为它们对去噪过程没有任何影响。
* `guidance_scale` 的理想取值范围是 [3., 13.]，因为 UNet 就是在这个范围内进行训练的。不过，在大多数情况下，将 `guidance_scale` 设为 1.0 以禁用该参数同样有效。

```python
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-LoRA，你需要将调度器替换为 [LCMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/lcm#diffusers.LCMScheduler)，并使用 [load_lora_weights()](/docs/diffusers/v0.43.0/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) 方法加载 LCM-LoRA 权重。之后，你可以像往常一样使用该 pipeline，只需传入文本提示词，即可在 4 步内生成图像。

在使用 LCM-LoRA 时，有几点需要注意：

* 通常，在管道内部，为了进行无分类器引导（classifier-free guidance），批量大小（batch size）会加倍。但 LCM 通过引导嵌入（guidance embeddings）来应用引导，因此无需加倍批量大小，从而实现了更快的推理速度。其缺点是，负提示词（negative prompts）在 LCM 中不起作用，因为它们对去噪过程没有任何影响。
* 您可以将 guidance 与 LCM-LoRA 配合使用，但它对较高的 `guidance_scale` 值非常敏感，可能会导致生成的图像出现伪影。我们发现的最佳取值范围在 [1.0, 2.0] 之间。
* 将 [stabilityai/stable-diffusion-xl-base-1.0](https://hf.co/stabilityai/stable-diffusion-xl-base-1.0) 替换为任意经过微调的模型。例如，可以尝试使用 [animagine-xl](https://huggingface.co/Linaqruf/animagine-xl) 检查点，利用 SDXL 生成动漫风格的图像。

```py
import torch
from diffusers import DiffusionPipeline, LCMScheduler

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

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

    

## 图像到图像

要在图像到图像任务中使用 LCM，你需要将受支持模型的 LCM 检查点加载到 [UNet2DConditionModel](/docs/diffusers/v0.43.0/zh/api/models/unet2d-cond#diffusers.UNet2DConditionModel) 中，并将调度器替换为 [LCMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/lcm#diffusers.LCMScheduler)。之后，你可以像往常一样使用该流水线，传入文本提示和初始图像，仅需 4 步即可生成图像。

> [!TIP]
> 尝试调整 `num_inference_steps`、`strength` 和 `guidance_scale` 的不同取值，以获得最佳效果。

```python
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](/docs/diffusers/v0.43.0/zh/api/schedulers/lcm#diffusers.LCMScheduler)，并使用 [load_lora_weights()](/docs/diffusers/v0.43.0/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) 方法加载 LCM-LoRA 权重。之后，你可以像往常一样使用该 pipeline，传入文本提示和初始图像，仅需 4 步即可生成图像。

> [!TIP]
> 尝试调整 `num_inference_steps`、`strength` 和 `guidance_scale` 的不同取值，以获得最佳效果。

```py
import torch
from diffusers import AutoPipelineForImage2Image, LCMScheduler
from diffusers.utils import make_image_grid, load_image

pipe = AutoPipelineForImage2Image.from_pretrained(
    "Lykon/dreamshaper-7",
    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/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=1,
    strength=0.6,
    generator=generator
).images[0]
image
```

  
    
    初始图像
  
  
    
    生成的图像
  

## 图像修复

要在图像修复中使用 LCM-LoRA，您需要将调度器替换为 [LCMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/lcm#diffusers.LCMScheduler)，并使用 [load_lora_weights()](/docs/diffusers/v0.43.0/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) 方法加载 LCM-LoRA 权重。之后，您可以像往常一样使用该流水线，传入文本提示、初始图像和掩码图像，仅需 4 步即可生成图像。

```py
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](../../tutorials/using_peft_for_inference) 适配器可以快速微调，仅从少量图像中学习新的风格，然后插入预训练模型中，以生成该风格的图像。

将受支持模型的 LCM 检查点加载到 [UNet2DConditionModel](/docs/diffusers/v0.43.0/zh/api/models/unet2d-cond#diffusers.UNet2DConditionModel) 中，并将调度器替换为 [LCMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/lcm#diffusers.LCMScheduler)。然后，您可以使用 [load_lora_weights()](/docs/diffusers/v0.43.0/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) 方法将 LoRA 权重加载到 LCM 中，并在几步内生成一张风格化图像。

```python
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
```

    

将调度器替换为 [LCMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/lcm#diffusers.LCMScheduler)。然后，你可以使用 [load_lora_weights()](/docs/diffusers/v0.43.0/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) 方法加载 LCM-LoRA 权重以及你想要使用的风格 LoRA。使用 `~loaders.UNet2DConditionLoadersMixin.set_adapters` 方法将这两个 LoRA 适配器组合起来，并在几步内生成一张风格化图像。

```py
import torch
from diffusers import DiffusionPipeline, LCMScheduler

pipe = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    variant="fp16",
    dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"

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

pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl", adapter_name="lcm")
pipe.load_lora_weights("TheLastBen/Papercut_SDXL", weight_name="papercut.safetensors", adapter_name="papercut")

pipe.set_adapters(["lcm", "papercut"], adapter_weights=[1.0, 0.8])

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

    

### ControlNet

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

您可以在 [lllyasviel](https://hf.co/lllyasviel) 的仓库中找到基于其他输入训练的更多 ControlNet 模型。

加载一个在 canny 图像上训练的 ControlNet 模型，并将其传递给 [ControlNetModel](/docs/diffusers/v0.43.0/zh/api/models/controlnet#diffusers.ControlNetModel)。然后，你可以将 LCM 模型加载到 [StableDiffusionControlNetPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/controlnet#diffusers.StableDiffusionControlNetPipeline) 中，并用 [LCMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/lcm#diffusers.LCMScheduler) 替换调度器。现在，将 canny 图像传递给流水线并生成图像。

> [!TIP]
> 尝试调整 `num_inference_steps`、`controlnet_conditioning_scale`、`cross_attention_kwargs` 和 `guidance_scale` 的不同取值，以获得最佳效果。

```python
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)
```

    

加载一个在 canny 图像上训练的 ControlNet 模型，并将其传递给 [ControlNetModel](/docs/diffusers/v0.43.0/zh/api/models/controlnet#diffusers.ControlNetModel)。然后，你可以将 Stable Diffusion v1.5 模型加载到 [StableDiffusionControlNetPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/controlnet#diffusers.StableDiffusionControlNetPipeline) 中，并将调度器替换为 [LCMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/lcm#diffusers.LCMScheduler)。使用 [load_lora_weights()](/docs/diffusers/v0.43.0/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) 方法加载 LCM-LoRA 权重，将 canny 图像传入 pipeline 并生成图像。

> [!TIP]
> 尝试调整 `num_inference_steps`、`controlnet_conditioning_scale`、`cross_attention_kwargs` 和 `guidance_scale` 的不同取值，以获得最佳效果。

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

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

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(
    "stable-diffusion-v1-5/stable-diffusion-v1-5",
    controlnet=controlnet,
    dtype=torch.float16,
    safety_checker=None,
    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")

generator = torch.manual_seed(0)
image = pipe(
    "the mona lisa",
    image=canny_image,
    num_inference_steps=4,
    guidance_scale=1.5,
    controlnet_conditioning_scale=0.8,
    cross_attention_kwargs={"scale": 1},
    generator=generator,
).images[0]
image
```

    

### T2I-Adapter

[T2I-Adapter](../../using-diffusers/legacy_adapters#t2i-adapter) 是一种比 ControlNet 更轻量级的适配器，它为预训练模型提供了额外的条件输入。它的速度比 ControlNet 更快，但结果可能会稍差一些。

您可以在 [TencentArc](https://hf.co/TencentARC) 的仓库中找到在其他输入上训练的其他 T2I-Adapter 检查点。

加载一个在 canny 图像上训练好的 T2IAdapter，并将其传递给 [StableDiffusionXLAdapterPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/adapter#diffusers.StableDiffusionXLAdapterPipeline)。然后将 LCM 检查点加载到 [UNet2DConditionModel](/docs/diffusers/v0.43.0/zh/api/models/unet2d-cond#diffusers.UNet2DConditionModel) 中，并将调度器替换为 [LCMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/lcm#diffusers.LCMScheduler)。现在将 canny 图像传递给流水线并生成图像。

```python
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]
```

    

加载一个在 canny 图像上训练的 T2IAdapter，并将其传递给 [StableDiffusionXLAdapterPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/adapter#diffusers.StableDiffusionXLAdapterPipeline)。将调度器替换为 [LCMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/lcm#diffusers.LCMScheduler)，并使用 [load_lora_weights()](/docs/diffusers/v0.43.0/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) 方法加载 LCM-LoRA 权重。将 canny 图像传入 pipeline 并生成图像。

```py
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, 1024))

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

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

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

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

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=1.5,
    adapter_conditioning_scale=0.8,
    adapter_conditioning_factor=1,
    generator=generator,
).images[0]
```

    

### AnimateDiff

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

加载一个 [AnimateDiffPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/animatediff#diffusers.AnimateDiffPipeline)，并向其传入一个 `MotionAdapter`。然后将调度器替换为 [LCMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/lcm#diffusers.LCMScheduler)，并使用 `~loaders.UNet2DConditionLoadersMixin.set_adapters` 方法将两个 LoRA 适配器组合起来。现在，你可以向流水线传入提示词并生成动画图像。

```py
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[[diffusers.LatentConsistencyModelPipeline]]

#### diffusers.LatentConsistencyModelPipeline[[diffusers.LatentConsistencyModelPipeline]]

```python
diffusers.LatentConsistencyModelPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: LCMScheduler, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection | None = None, requires_safety_checker: bool = True)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py#L133)

**参数：**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl#diffusers.AutoencoderKL))：变分自编码器（VAE）模型，用于将图像编码为潜在表示，并从潜在表示解码回图像。

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTextModel))：冻结的文本编码器（[clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)）。

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTokenizer))：一个用于对文本进行分词的 `CLIPTokenizer`。

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/zh/api/models/unet2d-cond#diffusers.UNet2DConditionModel))：一个用于对编码后的图像潜变量进行去噪的 `UNet2DConditionModel`。

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/zh/api/schedulers/overview#diffusers.SchedulerMixin))：用于与 `unet` 配合，对编码后的图像潜变量进行去噪的调度器。目前仅支持 [LCMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/lcm#diffusers.LCMScheduler)。

safety_checker (`StableDiffusionSafetyChecker`)：分类模块，用于评估生成的图像是否可能被视为冒犯性或有害内容。有关模型潜在危害的更多详细信息，请参阅[模型卡片](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)。

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPImageProcessor))：一个 `CLIPImageProcessor`，用于从生成的图像中提取特征；作为 `safety_checker` 的输入。

requires_safety_checker (`bool`，*可选*，默认为 `True`)：该流水线是否需要安全检查器组件。

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

该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。有关为所有流水线实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

该 pipeline 还继承了以下加载方法：
- 用于加载文本反转嵌入的 [load_textual_inversion()](/docs/diffusers/v0.43.0/zh/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- 用于加载 LoRA 权重的 [load_lora_weights()](/docs/diffusers/v0.43.0/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights)
- 用于保存 LoRA 权重的 [save_lora_weights()](/docs/diffusers/v0.43.0/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights)
- 用于加载 `.ckpt` 文件的 [from_single_file()](/docs/diffusers/v0.43.0/zh/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)
- 用于加载 IP Adapter 的 [load_ip_adapter()](/docs/diffusers/v0.43.0/zh/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

#### __调用__[[diffusers.LatentConsistencyModelPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 4, original_inference_steps: int = None, timesteps: list[int] = None, guidance_scale: float = 8.5, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, clip_skip: int | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py#L640)

**参数：**

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`](https://pytorch.org/docs/stable/generated/torch.Generator.html)。

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](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 而不是普通元组。

cross_attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为 [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中定义的 `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](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 或 `tuple`

如果 `return_dict` 为 `True`，则返回 [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表，第二个元素是 `bool` 列表，用于指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容。

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

示例：
```py
>>> 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[[diffusers.LatentConsistencyModelPipeline.enable_freeu]]

```python
enable_freeu(s1: float, s2: float, b1: float, b2: float)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L2267)

**参数：**

s1 (`float`) : 用于第一阶段以衰减跳跃特征贡献的缩放因子。这样做是为了缓解增强去噪过程中的“过度平滑效应”。

s2 (`float`) : 用于阶段 2 的缩放因子，用于衰减跳跃特征的贡献。这样做是为了缓解增强去噪过程中的“过度平滑效应”。

b1 (`float`) : 用于放大骨干网络特征贡献的阶段 1 缩放因子。

b2 (`float`) : 用于放大骨干网络特征贡献的第二阶段缩放因子。

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

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

有关适用于 Stable Diffusion v1、v2 和 Stable Diffusion XL 等不同流水线的已知效果良好的取值组合，请参阅[官方仓库](https://github.com/ChenyangSi/FreeU)。

#### disable_freeu[[diffusers.LatentConsistencyModelPipeline.disable_freeu]]

```python
disable_freeu()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L2289)

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

#### encode_prompt[[diffusers.LatentConsistencyModelPipeline.encode_prompt]]

```python
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: float | None = None, clip_skip: int | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py#L226)

**参数：**

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[[diffusers.LatentConsistencyModelPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py#L517)

**参数：**

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[[diffusers.LatentConsistencyModelImg2ImgPipeline]]

#### diffusers.LatentConsistencyModelImg2ImgPipeline[[diffusers.LatentConsistencyModelImg2ImgPipeline]]

```python
diffusers.LatentConsistencyModelImg2ImgPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: LCMScheduler, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection | None = None, requires_safety_checker: bool = True)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py#L154)

**参数：**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl#diffusers.AutoencoderKL))：变分自编码器（VAE）模型，用于将图像编码为潜在表示，并从潜在表示解码回图像。

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTextModel))：冻结的文本编码器（[clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)）。

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTokenizer))：一个用于对文本进行分词的 `CLIPTokenizer`。

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/zh/api/models/unet2d-cond#diffusers.UNet2DConditionModel))：一个用于对编码后的图像潜变量进行去噪的 `UNet2DConditionModel`。

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/zh/api/schedulers/overview#diffusers.SchedulerMixin))：用于与 `unet` 配合，对编码后的图像潜变量进行去噪的调度器。目前仅支持 [LCMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/lcm#diffusers.LCMScheduler)。

safety_checker (`StableDiffusionSafetyChecker`)：分类模块，用于评估生成的图像是否可能被视为冒犯性或有害内容。有关模型潜在危害的更多详细信息，请参阅[模型卡片](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)。

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPImageProcessor))：一个 `CLIPImageProcessor`，用于从生成的图像中提取特征；作为 `safety_checker` 的输入。

requires_safety_checker (`bool`，*可选*，默认为 `True`)：该流水线是否需要安全检查器组件。

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

该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。有关为所有流水线实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

该 pipeline 还继承了以下加载方法：
- 用于加载文本反转嵌入的 [load_textual_inversion()](/docs/diffusers/v0.43.0/zh/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- 用于加载 LoRA 权重的 [load_lora_weights()](/docs/diffusers/v0.43.0/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights)
- 用于保存 LoRA 权重的 [save_lora_weights()](/docs/diffusers/v0.43.0/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights)
- 用于加载 `.ckpt` 文件的 [from_single_file()](/docs/diffusers/v0.43.0/zh/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)
- 用于加载 IP Adapter 的 [load_ip_adapter()](/docs/diffusers/v0.43.0/zh/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

#### __调用__[[diffusers.LatentConsistencyModelImg2ImgPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, num_inference_steps: int = 4, strength: float = 0.8, original_inference_steps: int = None, timesteps: list[int] = None, guidance_scale: float = 8.5, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, clip_skip: int | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py#L709)

**参数：**

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`](https://pytorch.org/docs/stable/generated/torch.Generator.html)。

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](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 而不是普通元组。

cross_attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为 [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中定义的 `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](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 或 `tuple`

如果 `return_dict` 为 `True`，则返回 [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表，第二个元素是 `bool` 列表，用于指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容。

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

示例：
```py
>>> 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[[diffusers.LatentConsistencyModelImg2ImgPipeline.enable_freeu]]

```python
enable_freeu(s1: float, s2: float, b1: float, b2: float)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L2267)

**参数：**

s1 (`float`) : 用于第一阶段以衰减跳跃特征贡献的缩放因子。这样做是为了缓解增强去噪过程中的“过度平滑效应”。

s2 (`float`) : 用于阶段 2 的缩放因子，用于衰减跳跃特征的贡献。这样做是为了缓解增强去噪过程中的“过度平滑效应”。

b1 (`float`) : 用于放大骨干网络特征贡献的阶段 1 缩放因子。

b2 (`float`) : 用于放大骨干网络特征贡献的第二阶段缩放因子。

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

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

有关适用于 Stable Diffusion v1、v2 和 Stable Diffusion XL 等不同流水线的已知效果良好的取值组合，请参阅[官方仓库](https://github.com/ChenyangSi/FreeU)。

#### disable_freeu[[diffusers.LatentConsistencyModelImg2ImgPipeline.disable_freeu]]

```python
disable_freeu()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L2289)

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

#### encode_prompt[[diffusers.LatentConsistencyModelImg2ImgPipeline.encode_prompt]]

```python
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: float | None = None, clip_skip: int | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py#L241)

**参数：**

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[[diffusers.LatentConsistencyModelImg2ImgPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py#L576)

**参数：**

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

#### diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput[[diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput]]

```python
diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray, nsfw_content_detected: list[bool] | None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion/pipeline_output.py#L10)

**参数：**

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

