# 潜在一貫性モデル

  

Latent Consistency Models (LCM) は、Simian Luo、Yiqin Tan、Longbo Huang、Jian Li、Hang Zhao による [Latent Consistency Models: Synthesizing High-Resolution Images with Few-Step Inference](https://huggingface.co/papers/2310.04378) で提案されました。

本論文の抄録は以下の通りです。

*潜在拡散モデル（LDM）は、高解像度画像の合成において目覚ましい成果を上げています。しかし、反復的なサンプリングプロセスは計算負荷が大きく、生成が遅くなるという問題があります。Consistency Models（song et al.）に着想を得て、私たちはLatent Consistency Models（LCM）を提案しました。これにより、Stable Diffusion（rombach et al）を含む任意の事前学習済みLDMにおいて、最小限のステップ数で高速な推論が可能になります。誘導付き逆拡散プロセスを拡張確率流ODE（PF-ODE）の解として捉え、LCMは潜在空間においてそのようなODEの解を直接予測するように設計されています。これにより、多数の反復の必要性を軽減し、高速かつ高忠実度のサンプリングを可能にします。事前学習済みclassifier-free guided拡散モデルから効率的に蒸留されたLCMは、高品質な768 x 768の2〜4ステップ推論を実現し、学習にはわずか32 A100 GPU時間しかかかりません。さらに、カスタマイズされた画像データセットでのLCMのファインチューニングに特化した新手法であるLatent Consistency Fine-tuning（LCF）を導入しました。LAION-5B-Aestheticsデータセットでの評価により、LCMは少数ステップの推論で最先端のテキストから画像への生成性能を達成することが示されました。プロジェクトページ: [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/main/ja/api/models/unet2d-cond#diffusers.UNet2DConditionModel)に読み込み、スケジューラーを[LCMScheduler](/docs/diffusers/main/ja/api/schedulers/lcm#diffusers.LCMScheduler)に置き換える必要があります。その後、パイプラインを通常どおり使用し、テキストプロンプトを渡すだけで、わずか4ステップで画像を生成できます。

LCMを使用する際に注意すべき点として、以下の2点があります。

* 通常、パイプライン内部では、classifier-free guidanceのためにバッチサイズが2倍になります。しかし、LCMはguidance embeddingsを用いてguidanceを適用するため、バッチサイズの2倍化が不要であり、推論が高速になります。その代わり、LCMではnegative promptsが機能しません。これは、negative promptsがdenoisingプロセスに何の影響も与えないためです。
* `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/main/ja/api/schedulers/lcm#diffusers.LCMScheduler)に置き換え、[load_lora_weights()](/docs/diffusers/main/ja/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights)メソッドでLCM-LoRAの重みを読み込む必要があります。その後、パイプラインを通常通り使用し、テキストプロンプトを渡すだけで、わずか4ステップで画像を生成できます。

LCM-LoRAを使用する際に注意すべき点はいくつかあります。

* 通常、パイプライン内部では、classifier-free guidanceのためにバッチサイズが2倍になります。しかし、LCMはguidance embeddingsを用いてguidanceを適用するため、バッチサイズの2倍化が不要であり、推論が高速になります。その代わり、LCMではnegative promptsが機能しません。これは、negative promptsがdenoisingプロセスに何の影響も与えないためです。
* LCM-LoRA と guidance を併用することは可能ですが、`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/main/ja/api/models/unet2d-cond#diffusers.UNet2DConditionModel)に読み込み、スケジューラーを[LCMScheduler](/docs/diffusers/main/ja/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
```

  
    
    初期画像
  
  
    
    生成された画像
  

image-to-image で LCM-LoRA を使用するには、スケジューラーを [LCMScheduler](/docs/diffusers/main/ja/api/schedulers/lcm#diffusers.LCMScheduler) に置き換え、[load_lora_weights()](/docs/diffusers/main/ja/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) メソッドで LCM-LoRA の重みを読み込む必要があります。その後、パイプラインを通常どおり使用し、テキストプロンプトと初期画像を渡すことで、わずか 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/main/ja/api/schedulers/lcm#diffusers.LCMScheduler)に置き換え、[load_lora_weights()](/docs/diffusers/main/ja/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/main/ja/api/models/unet2d-cond#diffusers.UNet2DConditionModel)に読み込み、スケジューラーを[LCMScheduler](/docs/diffusers/main/ja/api/schedulers/lcm#diffusers.LCMScheduler)に置き換えます。その後、[load_lora_weights()](/docs/diffusers/main/ja/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/main/ja/api/schedulers/lcm#diffusers.LCMScheduler)に置き換えます。その後、[load_lora_weights()](/docs/diffusers/main/ja/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights)メソッドを使用して、LCM-LoRAの重みと使用したいスタイルLoRAを読み込みます。両方のLoRAアダプターを`~loaders.UNet2DConditionLoadersMixin.set_adapters`メソッドで組み合わせ、数ステップでスタイル付きの画像を生成します。

```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をパイプラインに挿入することで、モデルに追加の条件付けと制御を提供し、より正確な生成を実現できます。

他の入力データで学習された追加のControlNetモデルは、[lllyasviel](https://hf.co/lllyasviel)のリポジトリで確認できます。

canny画像で学習されたControlNetモデルを読み込み、[ControlNetModel](/docs/diffusers/main/ja/api/models/controlnet#diffusers.ControlNetModel)に渡します。次に、LCMモデルを[StableDiffusionControlNetPipeline](/docs/diffusers/main/ja/api/pipelines/controlnet#diffusers.StableDiffusionControlNetPipeline)に読み込み、スケジューラーを[LCMScheduler](/docs/diffusers/main/ja/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/main/ja/api/models/controlnet#diffusers.ControlNetModel)に渡します。次に、Stable Diffusion v1.5モデルを[StableDiffusionControlNetPipeline](/docs/diffusers/main/ja/api/pipelines/controlnet#diffusers.StableDiffusionControlNetPipeline)に読み込み、スケジューラーを[LCMScheduler](/docs/diffusers/main/ja/api/schedulers/lcm#diffusers.LCMScheduler)に置き換えます。[load_lora_weights()](/docs/diffusers/main/ja/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights)メソッドを使用してLCM-LoRAの重みを読み込み、canny画像をパイプラインに渡して画像を生成します。

> [!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 より高速ですが、結果はやや劣る場合があります。

他の入力データで学習された追加のT2I-Adapterチェックポイントは、[TencentArc](https://hf.co/TencentARC)のリポジトリで確認できます。

canny画像で学習されたT2IAdapterを読み込み、[StableDiffusionXLAdapterPipeline](/docs/diffusers/main/ja/api/pipelines/stable_diffusion/adapter#diffusers.StableDiffusionXLAdapterPipeline)に渡します。次に、LCMチェックポイントを[UNet2DConditionModel](/docs/diffusers/main/ja/api/models/unet2d-cond#diffusers.UNet2DConditionModel)に読み込み、スケジューラーを[LCMScheduler](/docs/diffusers/main/ja/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/main/ja/api/pipelines/stable_diffusion/adapter#diffusers.StableDiffusionXLAdapterPipeline)に渡します。スケジューラーを[LCMScheduler](/docs/diffusers/main/ja/api/schedulers/lcm#diffusers.LCMScheduler)に置き換え、[load_lora_weights()](/docs/diffusers/main/ja/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights)メソッドを使用してLCM-LoRAの重みを読み込みます。canny画像をパイプラインに渡し、画像を生成します。

```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/main/ja/api/pipelines/animatediff#diffusers.AnimateDiffPipeline)を読み込み、`MotionAdapter`を渡します。次に、スケジューラーを[LCMScheduler](/docs/diffusers/main/ja/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/main/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py#L133)

**パラメータ:**

vae ([AutoencoderKL](/docs/diffusers/main/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ（VAE）モデル。

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/main/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/main/en/model_doc/clip#transformers.CLIPTokenizer)) : テキストをトークン化するための`CLIPTokenizer`。

unet ([UNet2DConditionModel](/docs/diffusers/main/ja/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : エンコードされた画像の潜在変数をノイズ除去するための `UNet2DConditionModel`。

scheduler ([SchedulerMixin](/docs/diffusers/main/ja/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラ。現在サポートされているのは [LCMScheduler](/docs/diffusers/main/ja/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/main/en/model_doc/clip#transformers.CLIPImageProcessor)) : 生成された画像から特徴量を抽出するための`CLIPImageProcessor`。`safety_checker`の入力として使用されます。

requires_safety_checker (`bool`、*任意*、デフォルトは`True`) : パイプラインにセーフティチェッカーコンポーネントが必要かどうかを示します。

潜在一貫性モデルを使用したテキストから画像への生成を行うPipeline。

このモデルは [DiffusionPipeline](/docs/diffusers/main/ja/api/pipelines/overview#diffusers.DiffusionPipeline) を継承しています。すべてのパイプラインに実装されている汎用的なメソッド（ダウンロード、保存、特定のデバイスでの実行など）については、スーパークラスのドキュメントを参照してください。

パイプラインは、以下の読み込みメソッドも継承します:
- テキストインバージョンの埋め込みを読み込むための[load_textual_inversion()](/docs/diffusers/main/ja/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- LoRA重みの読み込みに[load_lora_weights()](/docs/diffusers/main/ja/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights)
- LoRA重みの保存には[save_lora_weights()](/docs/diffusers/main/ja/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights)を使用します
- `.ckpt`ファイルを読み込むための[from_single_file()](/docs/diffusers/main/ja/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)
- IP Adapterの読み込みに[load_ip_adapter()](/docs/diffusers/main/ja/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

#### __call__[[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/main/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`, *optional*) : 線形間隔のタイムステップスケジュールを生成するために使用される元の推論ステップ数です。論文の Skipping-Step 手法（セクション 4.3 参照）に従い、このスケジュールから等間隔に `num_inference_steps` 個のタイムステップを抽出して、最終的なタイムステップスケジュールとして使用します。設定されない場合、スケジューラーの `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 の論文では、guidance scale を 1 減らした別の CFG 定式化が使用されています（つまり、論文の定式化では `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/main/ja/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)を返すかどうか。

cross_attention_kwargs (`dict`, *任意*) : 指定された場合、[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) で定義されている `AttentionProcessor` に渡される kwargs の辞書です。

clip_skip (`int`, *optional*) : プロンプト埋め込みを計算する際に、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/main/ja/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) または `tuple`

If `return_dict` is `True`, [StableDiffusionPipelineOutput](/docs/diffusers/main/ja/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) is returned, otherwise a `tuple` is returned where the first element is a list with the generated images and the second element is a list of `bool`s indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.

生成用の 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/main/src/diffusers/pipelines/pipeline_utils.py#L2267)

**パラメータ:**

s1 (`float`) : ステージ1におけるスキップ特徴の寄与を減衰させるためのスケーリング係数です。これは、強化されたノイズ除去プロセスにおける「過剰平滑化効果」を緩和するために使用されます。

s2 (`float`) : ステージ2におけるスキップ特徴の寄与を減衰させるためのスケーリング係数です。これは、強化されたノイズ除去プロセスにおける「過剰平滑化効果」を緩和するために使用されます。

b1 (`float`) : ステージ1のスケール係数。バックボーン特徴の寄与を強調するために使用します。

b2 (`float`) : ステージ2のスケール係数。バックボーン特徴の寄与を強調するために使用します。

https://huggingface.co/papers/2309.11497 に記載されている FreeU メカニズムを有効にします。

スケーリング係数の後ろの接尾辞は、それらが適用されるステージを表しています。

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/main/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/main/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` 入力引数から negative_prompt_embeds が生成されます。

lora_scale (`float`、*任意*) : LoRAレイヤーが読み込まれている場合、テキストエンコーダーのすべてのLoRAレイヤーに適用されるLoRAスケールです。

clip_skip (`int`, *optional*) : プロンプト埋め込みを計算する際に、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/main/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py#L517)

**パラメータ:**

w (`torch.Tensor`) : 指定されたガイダンススケールで埋め込みベクトルを生成し、タイムステップ埋め込みを後で強化します。

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/main/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py#L154)

**パラメータ:**

vae ([AutoencoderKL](/docs/diffusers/main/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ（VAE）モデル。

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/main/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/main/en/model_doc/clip#transformers.CLIPTokenizer)) : テキストをトークン化するための`CLIPTokenizer`。

unet ([UNet2DConditionModel](/docs/diffusers/main/ja/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : エンコードされた画像の潜在変数をノイズ除去するための `UNet2DConditionModel`。

scheduler ([SchedulerMixin](/docs/diffusers/main/ja/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラ。現在サポートされているのは [LCMScheduler](/docs/diffusers/main/ja/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/main/en/model_doc/clip#transformers.CLIPImageProcessor)) : 生成された画像から特徴量を抽出するための`CLIPImageProcessor`。`safety_checker`の入力として使用されます。

requires_safety_checker (`bool`、*任意*、デフォルトは`True`) : パイプラインにセーフティチェッカーコンポーネントが必要かどうかを示します。

潜在一貫性モデルを用いた画像から画像への生成を行うPipeline。

このモデルは [DiffusionPipeline](/docs/diffusers/main/ja/api/pipelines/overview#diffusers.DiffusionPipeline) を継承しています。すべてのパイプラインに実装されている汎用的なメソッド（ダウンロード、保存、特定のデバイスでの実行など）については、スーパークラスのドキュメントを参照してください。

パイプラインは、以下の読み込みメソッドも継承します:
- テキストインバージョンの埋め込みを読み込むための[load_textual_inversion()](/docs/diffusers/main/ja/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- LoRA重みの読み込みに[load_lora_weights()](/docs/diffusers/main/ja/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights)
- LoRA重みの保存には[save_lora_weights()](/docs/diffusers/main/ja/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights)を使用します
- `.ckpt`ファイルを読み込むための[from_single_file()](/docs/diffusers/main/ja/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)
- IP Adapterの読み込みに[load_ip_adapter()](/docs/diffusers/main/ja/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

#### __call__[[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/main/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` またはテンソル。画像の潜在変数（latents）を `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`, *optional*) : 線形間隔のタイムステップスケジュールを生成するために使用される元の推論ステップ数です。論文の Skipping-Step 手法（セクション 4.3 参照）に従い、このスケジュールから等間隔に `num_inference_steps` 個のタイムステップを抽出して、最終的なタイムステップスケジュールとして使用します。設定されない場合、スケジューラーの `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 の論文では、guidance scale を 1 減らした別の CFG 定式化が使用されています（つまり、論文の定式化では `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/main/ja/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)を返すかどうか。

cross_attention_kwargs (`dict`, *任意*) : 指定された場合、[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) で定義されている `AttentionProcessor` に渡される kwargs の辞書です。

clip_skip (`int`, *optional*) : プロンプト埋め込みを計算する際に、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/main/ja/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) または `tuple`

If `return_dict` is `True`, [StableDiffusionPipelineOutput](/docs/diffusers/main/ja/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) is returned, otherwise a `tuple` is returned where the first element is a list with the generated images and the second element is a list of `bool`s indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.

生成用の 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/main/src/diffusers/pipelines/pipeline_utils.py#L2267)

**パラメータ:**

s1 (`float`) : ステージ1におけるスキップ特徴の寄与を減衰させるためのスケーリング係数です。これは、強化されたノイズ除去プロセスにおける「過剰平滑化効果」を緩和するために使用されます。

s2 (`float`) : ステージ2におけるスキップ特徴の寄与を減衰させるためのスケーリング係数です。これは、強化されたノイズ除去プロセスにおける「過剰平滑化効果」を緩和するために使用されます。

b1 (`float`) : ステージ1のスケール係数。バックボーン特徴の寄与を強調するために使用します。

b2 (`float`) : ステージ2のスケール係数。バックボーン特徴の寄与を強調するために使用します。

https://huggingface.co/papers/2309.11497 に記載されている FreeU メカニズムを有効にします。

スケーリング係数の後ろの接尾辞は、それらが適用されるステージを表しています。

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/main/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/main/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` 入力引数から negative_prompt_embeds が生成されます。

lora_scale (`float`、*任意*) : LoRAレイヤーが読み込まれている場合、テキストエンコーダーのすべてのLoRAレイヤーに適用されるLoRAスケールです。

clip_skip (`int`, *optional*) : プロンプト埋め込みを計算する際に、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/main/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py#L576)

**パラメータ:**

w (`torch.Tensor`) : 指定されたガイダンススケールで埋め込みベクトルを生成し、タイムステップ埋め込みを後で強化します。

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/main/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]`) : 対応する生成画像に「not-safe-for-work」（nsfw）コンテンツが含まれるかどうかを示すリスト。安全性チェックを実行できなかった場合は`None`。

Stable Diffusion パイプライン用の出力クラスです。

