# Mô hình nhất quán tiềm ẩn

  

Latent Consistency Models (LCMs) được đề xuất trong [Latent Consistency Models: Synthesizing High-Resolution Images with Few-Step Inference](https://huggingface.co/papers/2310.04378) bởi Simian Luo, Yiqin Tan, Longbo Huang, Jian Li và Hang Zhao.

Tóm tắt của bài báo như sau:

*Các mô hình Diffusion ẩn (LDM) đã đạt được những kết quả đáng kể trong việc tổng hợp ảnh độ phân giải cao. Tuy nhiên, quá trình lấy mẫu lặp lại đòi hỏi nhiều tài nguyên tính toán và dẫn đến tốc độ tạo ảnh chậm. Lấy cảm hứng từ Consistency Models (song et al.), chúng tôi đề xuất Latent Consistency Models (LCM), cho phép suy luận nhanh với số bước tối thiểu trên bất kỳ LDM nào đã được huấn luyện trước, bao gồm cả Stable Diffusion (rombach et al). Bằng cách xem xét quá trình khuếch tán ngược có hướng dẫn như việc giải một phương trình vi phân thường (PF-ODE) xác suất dòng tăng cường, LCM được thiết kế để dự đoán trực tiếp nghiệm của PF-ODE đó trong không gian ẩn, giảm thiểu nhu cầu về nhiều lần lặp lại và cho phép lấy mẫu nhanh với độ trung thực cao. Được chưng cất hiệu quả từ các mô hình khuếch tán có hướng dẫn không phân loại (classifier-free) đã được huấn luyện trước, một LCM chất lượng cao 768 x 768 với 2~4 bước chỉ cần 32 giờ GPU A100 để huấn luyện. Hơn nữa, chúng tôi giới thiệu Latent Consistency Fine-tuning (LCF), một phương pháp mới được thiết kế riêng để tinh chỉnh LCM trên các bộ dữ liệu ảnh tùy chỉnh. Đánh giá trên bộ dữ liệu LAION-5B-Aesthetics cho thấy LCM đạt được hiệu suất tạo ảnh từ văn bản tiên tiến nhất với suy luận ít bước. Trang dự án: [this https URL](https://latent-consistency-models.github.io/).*

Một demo cho checkpoint [SimianLuo/LCM_Dreamshaper_v7](https://huggingface.co/SimianLuo/LCM_Dreamshaper_v7) có thể được tìm thấy [tại đây](https://huggingface.co/spaces/SimianLuo/Latent_Consistency_Model).

Các pipeline được đóng góp bởi [luosiallen](https://luosiallen.github.io/), [nagolinc](https://github.com/nagolinc) và [dg845](https://github.com/dg845).

> [!TIP]
> LCM và LCM-LoRA có sẵn cho Stable Diffusion v1.5, Stable Diffusion XL và mô hình SSD-1B. Bạn có thể tìm thấy các checkpoint của chúng trong bộ sưu tập [Latent Consistency](https://hf.co/collections/latent-consistency/latent-consistency-models-weights-654ce61a95edd6dffccef6a8).

## Văn bản sang hình ảnh

Để sử dụng LCM, bạn cần nạp checkpoint LCM cho model được hỗ trợ của bạn vào [UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel) và thay thế scheduler bằng [LCMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lcm#diffusers.LCMScheduler). Sau đó, bạn có thể sử dụng pipeline như bình thường và truyền một text prompt để tạo ảnh chỉ trong 4 bước.

Một vài lưu ý cần ghi nhớ khi sử dụng LCM là:

* Thông thường, kích thước lô (batch size) được nhân đôi bên trong pipeline để thực hiện classifier-free guidance. Tuy nhiên, LCM áp dụng guidance thông qua guidance embeddings và không cần nhân đôi kích thước lô, dẫn đến suy luận nhanh hơn. Điểm bất lợi là các prompt âm (negative prompts) không hoạt động với LCM vì chúng không có bất kỳ tác động nào đến quá trình khử nhiễu (denoising).
* Khoảng lý tưởng cho `guidance_scale` là [3., 13.] vì đó là khoảng mà UNet được huấn luyện. Tuy nhiên, việc vô hiệu hóa `guidance_scale` bằng cách đặt giá trị là 1.0 cũng hiệu quả trong hầu hết các trường hợp.

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

    

Để sử dụng LCM-LoRAs, bạn cần thay thế scheduler bằng [LCMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lcm#diffusers.LCMScheduler) và tải trọng số LCM-LoRA bằng phương thức [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights). Sau đó, bạn có thể sử dụng pipeline như bình thường và truyền một text prompt để tạo ảnh chỉ trong 4 bước.

Một vài lưu ý cần ghi nhớ khi sử dụng LCM-LoRAs là:

* Thông thường, kích thước lô (batch size) được nhân đôi bên trong pipeline để thực hiện classifier-free guidance. Tuy nhiên, LCM áp dụng guidance thông qua guidance embeddings và không cần nhân đôi kích thước lô, dẫn đến suy luận nhanh hơn. Điểm bất lợi là các prompt âm (negative prompts) không hoạt động với LCM vì chúng không có bất kỳ tác động nào đến quá trình khử nhiễu (denoising).
* Bạn có thể sử dụng guidance với LCM-LoRAs, nhưng nó rất nhạy cảm với các giá trị `guidance_scale` cao và có thể dẫn đến các lỗi hình ảnh trong ảnh được tạo ra. Các giá trị tốt nhất mà chúng tôi tìm thấy nằm trong khoảng [1.0, 2.0].
* Thay [stabilityai/stable-diffusion-xl-base-1.0](https://hf.co/stabilityai/stable-diffusion-xl-base-1.0) bằng bất kỳ model nào đã được finetune. Ví dụ, hãy thử dùng checkpoint [animagine-xl](https://huggingface.co/Linaqruf/animagine-xl) để tạo ảnh anime với 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
```

    

## Ảnh sang ảnh

Để sử dụng LCM cho image-to-image, bạn cần nạp checkpoint LCM cho model được hỗ trợ của bạn vào [UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel) và thay thế scheduler bằng [LCMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lcm#diffusers.LCMScheduler). Sau đó, bạn có thể sử dụng pipeline như bình thường, và truyền một text prompt cùng hình ảnh ban đầu để tạo ra hình ảnh chỉ trong 4 bước.

> [!TIP]
> Thử nghiệm với các giá trị khác nhau của `num_inference_steps`, `strength` và `guidance_scale` để đạt được kết quả tốt nhất.

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

  
    
    ảnh ban đầu
  
  
    
    hình ảnh được tạo
  

Để sử dụng LCM-LoRAs cho image-to-image, bạn cần thay thế scheduler bằng [LCMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lcm#diffusers.LCMScheduler) và tải trọng số LCM-LoRA bằng phương thức [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights). Sau đó, bạn có thể sử dụng pipeline như bình thường, và truyền một text prompt cùng hình ảnh ban đầu để tạo ra hình ảnh chỉ trong 4 bước.

> [!TIP]
> Thử nghiệm với các giá trị khác nhau của `num_inference_steps`, `strength` và `guidance_scale` để đạt được kết quả tốt nhất.

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

  
    
    ảnh ban đầu
  
  
    
    hình ảnh được tạo
  

## Inpainting

Để sử dụng LCM-LoRAs cho inpainting, bạn cần thay thế scheduler bằng [LCMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lcm#diffusers.LCMScheduler) và tải trọng số LCM-LoRA bằng phương thức [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights). Sau đó, bạn có thể sử dụng pipeline như bình thường, và truyền vào một prompt văn bản, hình ảnh ban đầu và hình ảnh mask để tạo ra hình ảnh chỉ trong 4 bước.

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

  
    
    ảnh ban đầu
  
  
    
    hình ảnh được tạo
  

## Bộ thích ứng

LCM tương thích với các adapter như LoRA, ControlNet, T2I-Adapter và AnimateDiff. Bạn có thể mang tốc độ của LCM đến các adapter này để tạo ảnh theo một phong cách nhất định hoặc điều kiện hóa mô hình dựa trên một đầu vào khác như ảnh canny.

### LoRA

[LoRA](../../tutorials/using_peft_for_inference) adapters có thể được tinh chỉnh nhanh chóng để học một phong cách mới chỉ từ vài hình ảnh và được gắn vào một mô hình đã được huấn luyện trước để tạo ra các hình ảnh theo phong cách đó.

Tải checkpoint LCM cho model được hỗ trợ của bạn vào [UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel) và thay thế scheduler bằng [LCMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lcm#diffusers.LCMScheduler). Sau đó, bạn có thể sử dụng phương thức [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) để tải trọng số LoRA vào LCM và tạo một hình ảnh có phong cách chỉ trong vài bước.

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

    

Thay thế scheduler bằng [LCMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lcm#diffusers.LCMScheduler). Sau đó, bạn có thể sử dụng phương thức [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) để tải trọng số LCM-LoRA và style LoRA mà bạn muốn sử dụng. Kết hợp cả hai bộ thích ứng LoRA bằng phương thức `~loaders.UNet2DConditionLoadersMixin.set_adapters` và tạo một hình ảnh có phong cách chỉ trong vài bước.

```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) là các bộ thích ứng có thể được huấn luyện trên nhiều loại đầu vào khác nhau như canny edge, ước lượng tư thế, hoặc độ sâu. ControlNet có thể được chèn vào pipeline để cung cấp thêm điều kiện và kiểm soát cho mô hình, giúp tạo ra kết quả chính xác hơn.

Bạn có thể tìm thấy các mô hình ControlNet khác được huấn luyện trên các đầu vào khác trong kho lưu trữ của [lllyasviel](https://hf.co/lllyasviel).

Tải một mô hình ControlNet được huấn luyện trên ảnh canny và truyền nó vào [ControlNetModel](/docs/diffusers/v0.43.0/vi/api/models/controlnet#diffusers.ControlNetModel). Sau đó, bạn có thể tải một mô hình LCM vào [StableDiffusionControlNetPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/controlnet#diffusers.StableDiffusionControlNetPipeline) và thay thế scheduler bằng [LCMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lcm#diffusers.LCMScheduler). Bây giờ, truyền ảnh canny vào pipeline và tạo một hình ảnh.

> [!TIP]
> Thử nghiệm với các giá trị khác nhau của `num_inference_steps`, `controlnet_conditioning_scale`, `cross_attention_kwargs` và `guidance_scale` để đạt được kết quả tốt nhất.

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

    

Tải một mô hình ControlNet được huấn luyện trên ảnh canny và truyền nó vào [ControlNetModel](/docs/diffusers/v0.43.0/vi/api/models/controlnet#diffusers.ControlNetModel). Sau đó, bạn có thể tải một mô hình Stable Diffusion v1.5 vào [StableDiffusionControlNetPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/controlnet#diffusers.StableDiffusionControlNetPipeline) và thay thế scheduler bằng [LCMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lcm#diffusers.LCMScheduler). Sử dụng phương thức [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) để tải trọng số LCM-LoRA, truyền ảnh canny vào pipeline và tạo ra một hình ảnh.

> [!TIP]
> Thử nghiệm với các giá trị khác nhau của `num_inference_steps`, `controlnet_conditioning_scale`, `cross_attention_kwargs` và `guidance_scale` để đạt được kết quả tốt nhất.

```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) là một adapter nhẹ hơn cả ControlNet, cung cấp một đầu vào bổ sung để điều kiện hóa một mô hình đã được huấn luyện trước. Nó nhanh hơn ControlNet nhưng kết quả có thể kém hơn một chút.

Bạn có thể tìm thấy các checkpoint T2I-Adapter khác được huấn luyện trên các đầu vào khác trong kho lưu trữ của [TencentArc](https://hf.co/TencentARC).

Tải một T2IAdapter được huấn luyện trên ảnh canny và truyền nó vào [StableDiffusionXLAdapterPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/adapter#diffusers.StableDiffusionXLAdapterPipeline). Sau đó, tải một checkpoint LCM vào [UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel) và thay thế scheduler bằng [LCMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lcm#diffusers.LCMScheduler). Bây giờ, truyền ảnh canny vào pipeline và tạo một hình ảnh.

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

    

Tải một T2IAdapter được huấn luyện trên ảnh canny và truyền nó vào [StableDiffusionXLAdapterPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/adapter#diffusers.StableDiffusionXLAdapterPipeline). Thay thế scheduler bằng [LCMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lcm#diffusers.LCMScheduler), và sử dụng phương thức [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) để tải trọng số LCM-LoRA. Truyền ảnh canny vào pipeline và tạo ra một hình ảnh.

```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) là một adapter thêm chuyển động vào hình ảnh. Nó có thể được sử dụng với hầu hết các mô hình Stable Diffusion, biến chúng thành các mô hình “tạo video” một cách hiệu quả. Việc tạo ra kết quả tốt với một mô hình video thường yêu cầu tạo nhiều khung hình (16-24), điều này có thể rất chậm với một mô hình Stable Diffusion thông thường. LCM-LoRA có thể tăng tốc quy trình này bằng cách chỉ cần 4-8 bước cho mỗi khung hình.

Tải một [AnimateDiffPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/animatediff#diffusers.AnimateDiffPipeline) và truyền một `MotionAdapter` vào nó. Sau đó thay thế scheduler bằng [LCMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lcm#diffusers.LCMScheduler), và kết hợp cả hai bộ thích ứng LoRA bằng phương thức `~loaders.UNet2DConditionLoadersMixin.set_adapters`. Bây giờ bạn có thể truyền một prompt vào pipeline và tạo ra một hình ảnh động.

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

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py#L133)

**Tham số:**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh sang và từ các biểu diễn ẩn.

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTextModel)) : Bộ mã hóa văn bản đóng băng ([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)) : Một `CLIPTokenizer` để phân tách văn bản.

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : Một `UNet2DConditionModel` để khử nhiễu các latents ảnh đã mã hóa.

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/vi/api/schedulers/overview#diffusers.SchedulerMixin)) : Một trình lập lịch được sử dụng kết hợp với `unet` để khử nhiễu các latents của ảnh đã mã hóa. Hiện tại chỉ hỗ trợ [LCMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lcm#diffusers.LCMScheduler).

safety_checker (`StableDiffusionSafetyChecker`) : Module phân loại ước tính xem hình ảnh được tạo ra có thể bị coi là khiêu khích hoặc gây hại hay không. Vui lòng tham khảo [model card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) để biết thêm chi tiết về các tác hại tiềm ẩn của model.

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPImageProcessor)) : Một `CLIPImageProcessor` để trích xuất đặc trưng từ các hình ảnh được tạo ra; được dùng làm đầu vào cho `safety_checker`.

requires_safety_checker (`bool`, *tùy chọn*, mặc định là `True`) : Xác định xem pipeline có yêu cầu thành phần kiểm tra an toàn hay không.

Pipeline để tạo ảnh từ văn bản sử dụng mô hình nhất quán tiềm ẩn.

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).

Pipeline cũng kế thừa các phương thức nạp sau:
- [load_textual_inversion()](/docs/diffusers/v0.43.0/vi/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion) để nạp các embedding textual inversion
- [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) để nạp trọng số LoRA
- [save_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights) để lưu trọng số LoRA
- [from_single_file()](/docs/diffusers/v0.43.0/vi/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file) để tải các tệp `.ckpt`
- [load_ip_adapter()](/docs/diffusers/v0.43.0/vi/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter) để nạp IP Adapters

#### __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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py#L640)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn tạo ảnh. Nếu không được định nghĩa, bạn cần truyền `prompt_embeds`.

height (`int`, *tùy chọn*, mặc định là `self.unet.config.sample_size * self.vae_scale_factor`) : Chiều cao của hình ảnh được tạo ra, tính bằng pixel.

width (`int`, *tùy chọn*, mặc định là `self.unet.config.sample_size * self.vae_scale_factor`) : Độ rộng tính bằng pixel của hình ảnh được tạo ra.

num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

original_inference_steps (`int`, *optional*) : Số bước suy luận ban đầu được dùng để tạo lịch trình bước thời gian (timestep) phân bố tuyến tính, từ đó chúng ta sẽ lấy `num_inference_steps` bước thời gian phân bố đều làm lịch trình bước thời gian cuối cùng, theo phương pháp Skipping-Step trong bài báo (xem Mục 4.3). Nếu không được đặt, giá trị này sẽ mặc định là thuộc tính `original_inference_steps` của scheduler.

timesteps (`list[int]`, *optional*) : Các bước thời gian tùy chỉnh để sử dụng cho quá trình khử nhiễu. Nếu không được định nghĩa, các bước thời gian `num_inference_steps` cách đều trên lịch trình bước thời gian huấn luyện/chưng cất LCM gốc sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.

guidance_scale (`float`, *optional*, mặc định là 7.5) : Giá trị guidance scale cao hơn khuyến khích mô hình tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, với cái giá là chất lượng hình ảnh thấp hơn. Guidance scale được kích hoạt khi `guidance_scale > 1`. Lưu ý rằng bài báo gốc về latent consistency models sử dụng một công thức CFG khác, trong đó các guidance scale được giảm đi 1 (do đó, trong công thức của bài báo, CFG được kích hoạt khi `guidance_scale > 0`).

num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

ip_adapter_image : (`PipelineImageInput`, *tùy chọn*): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.

ip_adapter_image_embeds (`list[torch.Tensor]`, *tùy chọn*) : Các embedding ảnh đã tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng `(batch_size, num_images, emb_dim)`. Nó phải chứa embedding ảnh âm nếu `do_classifier_free_guidance` được đặt thành `True`. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào `ip_adapter_image`.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo ra. Chọn giữa `PIL.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) thay vì một tuple thông thường hay không.

cross_attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa trong [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

callback_on_step_end (`Callable`, *tùy chọn*) : Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

**Trả về:** [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) hoặc `tuple`

Nếu `return_dict` là `True`, [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) sẽ được trả về, ngược lại một `tuple` sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo và phần tử thứ hai là một danh sách các `bool` cho biết hình ảnh tương ứng có chứa nội dung "không an toàn" (nsfw) hay không.

Hàm gọi call của pipeline để tạo nội dung.

Ví dụ:
```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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L2267)

**Tham số:**

s1 (`float`) : Hệ số tỷ lệ cho giai đoạn 1 để làm suy giảm đóng góp của các đặc trưng skip. Việc này được thực hiện để giảm thiểu "hiệu ứng làm mịn quá mức" trong quá trình khử nhiễu được tăng cường.

s2 (`float`) : Hệ số tỷ lệ cho giai đoạn 2 để làm suy giảm đóng góp của các đặc trưng skip. Việc này được thực hiện để giảm thiểu "hiệu ứng làm mịn quá mức" trong quá trình khử nhiễu được tăng cường.

b1 (`float`) : Hệ số tỷ lệ cho giai đoạn 1 để khuếch đại đóng góp của các đặc trưng backbone.

b2 (`float`) : Hệ số tỷ lệ cho giai đoạn 2 để khuếch đại đóng góp của các đặc trưng backbone.

Bật cơ chế FreeU như trong https://huggingface.co/papers/2309.11497.

Các hậu tố sau các hệ số tỷ lệ đại diện cho các giai đoạn mà chúng được áp dụng.

Vui lòng tham khảo [kho mã nguồn chính thức](https://github.com/ChenyangSi/FreeU) để biết các tổ hợp giá trị được biết là hoạt động tốt cho các pipeline khác nhau như Stable Diffusion v1, v2 và Stable Diffusion XL.

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

```python
disable_freeu()
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L2289)

Tắt cơ chế FreeU nếu đang được bật.

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

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py#L226)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

device : (`torch.device`): thiết bị torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

lora_scale (`float`, *tuỳ chọn*) : Thang LoRA sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

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

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py#L517)

**Tham số:**

w (`torch.Tensor`) : Tạo các vector nhúng với thang độ dẫn hướng được chỉ định để sau đó làm phong phú các nhúng bước thời gian.

embedding_dim (`int`, *tuỳ chọn*, mặc định là 512) : Kích thước của các embedding cần tạo.

dtype (`torch.dtype`, *tùy chọn*, mặc định là `torch.float32`) : Kiểu dữ liệu của các embedding được tạo ra.

**Trả về:** `torch.Tensor`

Các vector nhúng có hình dạng `(len(w), embedding_dim)`.

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

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py#L154)

**Tham số:**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh sang và từ các biểu diễn ẩn.

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTextModel)) : Bộ mã hóa văn bản đóng băng ([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)) : Một `CLIPTokenizer` để phân tách văn bản.

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : Một `UNet2DConditionModel` để khử nhiễu các latents ảnh đã mã hóa.

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/vi/api/schedulers/overview#diffusers.SchedulerMixin)) : Một trình lập lịch được sử dụng kết hợp với `unet` để khử nhiễu các latents của ảnh đã mã hóa. Hiện tại chỉ hỗ trợ [LCMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lcm#diffusers.LCMScheduler).

safety_checker (`StableDiffusionSafetyChecker`) : Module phân loại ước tính xem hình ảnh được tạo ra có thể bị coi là khiêu khích hoặc gây hại hay không. Vui lòng tham khảo [model card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) để biết thêm chi tiết về các tác hại tiềm ẩn của model.

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPImageProcessor)) : Một `CLIPImageProcessor` để trích xuất đặc trưng từ các hình ảnh được tạo ra; được dùng làm đầu vào cho `safety_checker`.

requires_safety_checker (`bool`, *tùy chọn*, mặc định là `True`) : Xác định xem pipeline có yêu cầu thành phần kiểm tra an toàn hay không.

Pipeline để tạo ảnh từ ảnh bằng cách sử dụng mô hình nhất quán tiềm ẩn (latent consistency model).

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).

Pipeline cũng kế thừa các phương thức nạp sau:
- [load_textual_inversion()](/docs/diffusers/v0.43.0/vi/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion) để nạp các embedding textual inversion
- [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) để nạp trọng số LoRA
- [save_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights) để lưu trọng số LoRA
- [from_single_file()](/docs/diffusers/v0.43.0/vi/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file) để tải các tệp `.ckpt`
- [load_ip_adapter()](/docs/diffusers/v0.43.0/vi/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter) để nạp IP Adapters

#### __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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py#L709)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn tạo ảnh. Nếu không được định nghĩa, bạn cần truyền `prompt_embeds`.

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, hoặc `list[np.ndarray]`) : `Image` hoặc tensor đại diện cho một lô ảnh (image batch) được sử dụng làm điểm khởi đầu. Cũng có thể nhận image latents dưới dạng `image`, nhưng nếu truyền latents trực tiếp thì chúng sẽ không được mã hóa lại.

num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

strength (`float`, *optional*, mặc định là 0.8) : Chỉ định mức độ biến đổi ảnh tham chiếu `image`. Giá trị phải nằm trong khoảng từ 0 đến 1. `image` được dùng làm điểm khởi đầu và càng thêm nhiều nhiễu khi `strength` càng cao. Số bước khử nhiễu phụ thuộc vào lượng nhiễu ban đầu được thêm vào. Khi `strength` là 1, nhiễu được thêm vào là tối đa và quá trình khử nhiễu chạy đủ số lần lặp được chỉ định trong `num_inference_steps`. Giá trị 1 về cơ bản sẽ bỏ qua `image`.

original_inference_steps (`int`, *optional*) : Số bước suy luận ban đầu được dùng để tạo lịch trình bước thời gian (timestep) phân bố tuyến tính, từ đó chúng ta sẽ lấy `num_inference_steps` bước thời gian phân bố đều làm lịch trình bước thời gian cuối cùng, theo phương pháp Skipping-Step trong bài báo (xem Mục 4.3). Nếu không được đặt, giá trị này sẽ mặc định là thuộc tính `original_inference_steps` của scheduler.

timesteps (`list[int]`, *optional*) : Các bước thời gian tùy chỉnh để sử dụng cho quá trình khử nhiễu. Nếu không được định nghĩa, các bước thời gian `num_inference_steps` cách đều trên lịch trình bước thời gian huấn luyện/chưng cất LCM gốc sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.

guidance_scale (`float`, *optional*, mặc định là 7.5) : Giá trị guidance scale cao hơn khuyến khích mô hình tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, với cái giá là chất lượng hình ảnh thấp hơn. Guidance scale được kích hoạt khi `guidance_scale > 1`. Lưu ý rằng bài báo gốc về latent consistency models sử dụng một công thức CFG khác, trong đó các guidance scale được giảm đi 1 (do đó, trong công thức của bài báo, CFG được kích hoạt khi `guidance_scale > 0`).

num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

ip_adapter_image : (`PipelineImageInput`, *tùy chọn*): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.

ip_adapter_image_embeds (`list[torch.Tensor]`, *tùy chọn*) : Các embedding ảnh đã tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng `(batch_size, num_images, emb_dim)`. Nó phải chứa embedding ảnh âm nếu `do_classifier_free_guidance` được đặt thành `True`. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào `ip_adapter_image`.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo ra. Chọn giữa `PIL.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) thay vì một tuple thông thường hay không.

cross_attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa trong [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

callback_on_step_end (`Callable`, *tùy chọn*) : Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

**Trả về:** [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) hoặc `tuple`

Nếu `return_dict` là `True`, [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) sẽ được trả về, ngược lại một `tuple` sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo và phần tử thứ hai là một danh sách các `bool` cho biết hình ảnh tương ứng có chứa nội dung "không an toàn" (nsfw) hay không.

Hàm gọi call của pipeline để tạo nội dung.

Ví dụ:
```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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L2267)

**Tham số:**

s1 (`float`) : Hệ số tỷ lệ cho giai đoạn 1 để làm suy giảm đóng góp của các đặc trưng skip. Việc này được thực hiện để giảm thiểu "hiệu ứng làm mịn quá mức" trong quá trình khử nhiễu được tăng cường.

s2 (`float`) : Hệ số tỷ lệ cho giai đoạn 2 để làm suy giảm đóng góp của các đặc trưng skip. Việc này được thực hiện để giảm thiểu "hiệu ứng làm mịn quá mức" trong quá trình khử nhiễu được tăng cường.

b1 (`float`) : Hệ số tỷ lệ cho giai đoạn 1 để khuếch đại đóng góp của các đặc trưng backbone.

b2 (`float`) : Hệ số tỷ lệ cho giai đoạn 2 để khuếch đại đóng góp của các đặc trưng backbone.

Bật cơ chế FreeU như trong https://huggingface.co/papers/2309.11497.

Các hậu tố sau các hệ số tỷ lệ đại diện cho các giai đoạn mà chúng được áp dụng.

Vui lòng tham khảo [kho mã nguồn chính thức](https://github.com/ChenyangSi/FreeU) để biết các tổ hợp giá trị được biết là hoạt động tốt cho các pipeline khác nhau như Stable Diffusion v1, v2 và Stable Diffusion XL.

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

```python
disable_freeu()
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L2289)

Tắt cơ chế FreeU nếu đang được bật.

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

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py#L241)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

device : (`torch.device`): thiết bị torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

lora_scale (`float`, *tuỳ chọn*) : Thang LoRA sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

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

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py#L576)

**Tham số:**

w (`torch.Tensor`) : Tạo các vector nhúng với thang độ dẫn hướng được chỉ định để sau đó làm phong phú các nhúng bước thời gian.

embedding_dim (`int`, *tuỳ chọn*, mặc định là 512) : Kích thước của các embedding cần tạo.

dtype (`torch.dtype`, *tùy chọn*, mặc định là `torch.float32`) : Kiểu dữ liệu của các embedding được tạo ra.

**Trả về:** `torch.Tensor`

Các vector nhúng có hình dạng `(len(w), embedding_dim)`.

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

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion/pipeline_output.py#L10)

**Tham số:**

images (`list[PIL.Image.Image]` hoặc `np.ndarray`) : danh sách các hình ảnh PIL đã khử nhiễu có độ dài `batch_size` hoặc mảng NumPy có hình dạng `(batch_size, height, width, num_channels)`.

nsfw_content_detected (`list[bool]`) : danh sách cho biết hình ảnh tương ứng có chứa nội dung "không an toàn cho công việc" (nsfw) hay không, hoặc `None` nếu không thể thực hiện kiểm tra an toàn.

Lớp đầu ra cho các pipeline Stable Diffusion.

