Latent Consistency Model (LCM) LoRA: SDv1-5
El modelo Latent Consistency Model (LCM) LoRA fue propuesto en LCM-LoRA: A universal Stable-Diffusion Acceleration Module por Simian Luo, Yiqin Tan, Suraj Patil, Daniel Gu et al. Es un adaptador de consistencia destilado para runwayml/stable-diffusion-v1-5 que permite reducir el número de pasos de inferencia a solo entre 2 y 8 pasos.
Como usar
LCM-LoRA es compatible con la biblioteca 🤗 Hugging Face Diffusers desde la versión v0.23.0. Para ejecutar el modelo, primero instale la última versión de la biblioteca Diffusers así como peft, accelerate y transformers.
pip install --upgrade pip
pip install --upgrade diffusers transformers accelerate peft
Text-to-Image
El adaptador se puede cargar con SDv1-5 o derivados. En este ejemplo usamos Lykon/dreamshaper-7. Luego, el scheduler debe cambiarse a LCMScheduler y podemos reducir el número de pasos de inferencia a solo 2-8 pasos.
import torch
from diffusers import LCMScheduler, AutoPipelineForText2Image
model_id = "Lykon/dreamshaper-7"
adapter_id = "latent-consistency/lcm-lora-sdv1-5"
pipe = AutoPipelineForText2Image.from_pretrained(model_id, torch_dtype=torch.float16, variant="fp16")
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
pipe.to("cuda")
# cargar y fusionar lcm lora
pipe.load_lora_weights(adapter_id)
pipe.fuse_lora()
prompt = "Self-portrait oil painting, a beautiful cyborg with golden hair, 8k"
# deshabilitar guidance_scale pasando 0
image = pipe(prompt=prompt, num_inference_steps=4, guidance_scale=0).images[0]
Image-to-Image
LCM-LoRA también se puede aplicar a tareas de imagen a imagen. En este ejemplo utilizaremos el modelo dreamshaper-7 y el LCM-LoRA para stable-diffusion-v1-5.
import torch
from diffusers import AutoPipelineForImage2Image, LCMScheduler
from diffusers.utils import make_image_grid, load_image
pipe = AutoPipelineForImage2Image.from_pretrained(
"Lykon/dreamshaper-7",
torch_dtype=torch.float16,
variant="fp16",
).to("cuda")
# configurar el scheduler
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
# cargar LCM-LoRA
pipe.load_lora_weights("latent-consistency/lcm-lora-sdv1-5")
pipe.fuse_lora()
# preparar imagen
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"
init_image = load_image(url)
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]
make_image_grid([init_image, image], rows=1, cols=2)
Inpainting
LCM-LoRA también puede ser utilizado para tareas de inpainting.
import torch
from diffusers import AutoPipelineForInpainting, LCMScheduler
from diffusers.utils import load_image, make_image_grid
pipe = AutoPipelineForInpainting.from_pretrained(
"runwayml/stable-diffusion-inpainting",
torch_dtype=torch.float16,
variant="fp16",
).to("cuda")
# configurar el scheduler
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
# cargar LCM-LoRA
pipe.load_lora_weights("latent-consistency/lcm-lora-sdv1-5")
pipe.fuse_lora()
# cargar imagen base y máscara
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")
generator = torch.manual_seed(0)
image = pipe(
prompt="concept art digital painting of an elven castle, inspired by lord of the rings, highly detailed, 8k",
image=init_image,
mask_image=mask_image,
generator=generator,
num_inference_steps=4,
guidance_scale=4,
).images[0]
make_image_grid([init_image, mask_image, image], rows=1, cols=3)
ControlNet
En este ejemplo, utilizaremos el modelo SD-v1-5 y el LCM-LoRA para SD-v1-5 con canny ControlNet.
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", torch_dtype=torch.float16)
pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
controlnet=controlnet,
torch_dtype=torch.float16,
safety_checker=None,
variant="fp16").to("cuda")
# configurar el scheduler
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
# cargar LCM-LoRA
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]
make_image_grid([canny_image, image], rows=1, cols=2)
Funcionalidades
- Reducción de pasos de inferencia a solo 2-8 pasos
- Soporte en la biblioteca 🤗 Hugging Face Diffusers desde la versión v0.23.0
- Compatible con Text-to-Image, Image-to-Image, Inpainting y ControlNet
Casos de uso
- Generación de texto a imagen
- Generación de imagen a imagen
- Inpainting
- ControlNet