Diffusers documentation
Mô hình nhất quán tiềm ẩn
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 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.
Một demo cho checkpoint SimianLuo/LCM_Dreamshaper_v7 có thể được tìm thấy tại đây.
Các pipeline được đóng góp bởi luosiallen, nagolinc và dg845.
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.
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 và thay thế scheduler bằng 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. Mặt hạn chế 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_scalelà [3., 13.] vì đó là khoảng mà UNet được huấn luyện. Tuy nhiên, việc vô hiệu hóaguidance_scalebằ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.
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 và tải trọng số LCM-LoRA bằng phương thức 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. Mặt hạn chế 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_scalecao 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 bằng bất kỳ model nào đã được finetune. Ví dụ, hãy thử dùng checkpoint animagine-xl để tạo ảnh anime với SDXL.
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 và thay thế scheduler bằng 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.
Thử nghiệm với các giá trị khác nhau của
num_inference_steps,strengthvàguidance_scaleđể đạt được kết quả tốt nhất.
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
Để sử dụng LCM-LoRAs cho image-to-image, bạn cần thay thế scheduler bằng LCMScheduler và tải trọng số LCM-LoRA bằng phương thức 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.
Thử nghiệm với các giá trị khác nhau của
num_inference_steps,strengthvàguidance_scaleđể đạt được kết quả tốt nhất.
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
Inpainting
Để sử dụng LCM-LoRAs cho inpainting, bạn cần thay thế scheduler bằng LCMScheduler và tải trọng số LCM-LoRA bằng phương thức 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.
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
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 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 và thay thế scheduler bằng LCMScheduler. Sau đó, bạn có thể sử dụng phương thức 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.
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. Sau đó, bạn có thể sử dụng phương thức 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.
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 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.
Tải một mô hình ControlNet được huấn luyện trên ảnh canny và truyền nó vào ControlNetModel. Sau đó, bạn có thể tải một mô hình LCM vào StableDiffusionControlNetPipeline và thay thế scheduler bằng LCMScheduler. Bây giờ, truyền ảnh canny vào pipeline và tạo một hình ảnh.
Thử nghiệm với các giá trị khác nhau của
num_inference_steps,controlnet_conditioning_scale,cross_attention_kwargsvàguidance_scaleđể đạt được kết quả tốt nhất.
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. Sau đó, bạn có thể tải một mô hình Stable Diffusion v1.5 vào StableDiffusionControlNetPipeline và thay thế scheduler bằng LCMScheduler. Sử dụng phương thức 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.
Thử nghiệm với các giá trị khác nhau của
num_inference_steps,controlnet_conditioning_scale,cross_attention_kwargsvàguidance_scaleđể đạt được kết quả tốt nhất.
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 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.
Tải một T2IAdapter được huấn luyện trên ảnh canny và truyền nó vào StableDiffusionXLAdapterPipeline. Sau đó, tải một checkpoint LCM vào UNet2DConditionModel và thay thế scheduler bằng LCMScheduler. Bây giờ, truyền ảnh canny vào pipeline và tạo một hình ảnh.
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. Thay thế scheduler bằng LCMScheduler, và sử dụng phương thức 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.
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 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 và truyền một MotionAdapter vào nó. Sau đó thay thế scheduler bằng 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.
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
lớp diffusers.LatentConsistencyModelPipeline
< source >( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModelscheduler: LCMSchedulersafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilimage_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection | None = Nonerequires_safety_checker: bool = True )
Tham số
- vae (AutoencoderKL) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh từ và sang các biểu diễn ẩn.
- text_encoder (CLIPTextModel) — Bộ mã hóa văn bản đóng băng (clip-vit-large-patch14).
- tokenizer (CLIPTokenizer) —
Một
CLIPTokenizerđể tách token cho văn bản. - unet (UNet2DConditionModel) —
Một
UNet2DConditionModelđể khử nhiễu các latents ảnh đã mã hóa. - scheduler (SchedulerMixin) —
Một scheduler đượ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. - safety_checker (
StableDiffusionSafetyChecker) — Module phân loại ước lượng xem hình ảnh được tạo ra có thể bị coi là khiêu dâm hoặc gây hại hay không. Vui lòng tham khảo model card để biết thêm chi tiết về các tác hại tiềm ẩn của model. - feature_extractor (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 chosafety_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. 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() để nạp các embedding textual inversion
- load_lora_weights() để nạp trọng số LoRA
- save_lora_weights() để lưu trọng số LoRA
- from_single_file() để tải các tệp
.ckpt - load_ip_adapter() để nạp IP Adapters
__call__
< source >( prompt: str | list[str] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 4original_inference_steps: int = Nonetimesteps: list = Noneguidance_scale: float = 8.5num_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']**kwargs ) → StableDiffusionPipelineOutput or tuple
Tham số
- prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn cần truyềnprompt_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) — Chiều rộng của hình ảnh được tạo ra, tính bằng pixel. - num_inference_steps (
int, tùy chọn, 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 chi phí là suy luận chậm hơn. - original_inference_steps (
int, tùy chọn) — Số bước suy luận ban đầu được dùng để tạo lịch trình timestep phân bố tuyến tính, từ đó chúng ta sẽ lấynum_inference_stepstimestep phân bố đều làm lịch trình timestep 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ị mặc định sẽ là thuộc tínhoriginal_inference_stepscủa scheduler. - timesteps (
list[int], tùy chọn) — 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 giannum_inference_stepscá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, tùy chọn, 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ớipromptvă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 khiguidance_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 khiguidance_scale > 0). - num_images_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng hình ảnh cần tạo cho mỗi prompt. - generator (
torch.Generatorhoặclist[torch.Generator], tùy chọn) — Mộttorch.Generatorđể làm cho quá trình sinh ra kết quả xác đị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ụnggeneratorngẫu nhiên được cung cấp. - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - 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 hình ảnh được 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 hình ảnh âm nếudo_classifier_free_guidanceđược đặt thànhTrue. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vàoip_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ữaPIL.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về một 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, nếu được chỉ định, sẽ được truyền đếnAttentionProcessornhư đã định nghĩa trongself.processor. - clip_skip (
int, tùy chọn) — Số lượng lớp được bỏ qua từ CLIP khi tính toán các embedding của prompt. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối sẽ được sử dụng để tính toán các embedding của prompt. - 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_kwargssẽ bao gồm danh sách tất cả các tensor như được chỉ định bởicallback_on_step_end_tensor_inputs. - callback_on_step_end_tensor_inputs (
list, optional) — Danh sách các tensor đầu vào cho hàmcallback_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_inputscủa lớp pipeline của bạn.
Trả về
StableDiffusionPipelineOutput hoặc tuple
Nếu return_dict là True, StableDiffusionPipelineOutput sẽ được trả về,
ngoài ra 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 được tạo và phần tử
thứ hai là một danh sách các bool cho biết hình ảnh được tạo 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ụ:
>>> 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
< source >( s1: floats2: floatb1: floatb2: float )
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 để 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.
Tắt cơ chế FreeU nếu đang được bật.
encode_prompt
< source >( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )
Tham số
- prompt (
strhoặclist[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 (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalenhỏ hơn1). - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầ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àonegative_prompt. - lora_scale (
float, tùy 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, tùy chọn) — Số lượng lớp được bỏ qua từ CLIP khi tính toán các embedding của prompt. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối sẽ được sử dụng để tính toán các embedding của prompt.
Mã hóa prompt thành các trạng thái ẩn của text encoder.
get_guidance_scale_embedding
< source >( w: Tensorembedding_dim: int = 512dtype: dtype = torch.float32 ) → torch.Tensor
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, tùy 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).
LatentConsistencyModelImg2ImgPipeline
lớp diffusers.LatentConsistencyModelImg2ImgPipeline
< source >( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModelscheduler: LCMSchedulersafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilimage_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection | None = Nonerequires_safety_checker: bool = True )
Tham số
- vae (AutoencoderKL) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh từ và sang các biểu diễn ẩn.
- text_encoder (CLIPTextModel) — Bộ mã hóa văn bản đóng băng (clip-vit-large-patch14).
- tokenizer (CLIPTokenizer) —
Một
CLIPTokenizerđể tách token cho văn bản. - unet (UNet2DConditionModel) —
Một
UNet2DConditionModelđể khử nhiễu các latents ảnh đã mã hóa. - scheduler (SchedulerMixin) —
Một scheduler đượ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. - safety_checker (
StableDiffusionSafetyChecker) — Module phân loại ước lượng xem hình ảnh được tạo ra có thể bị coi là khiêu dâm hoặc gây hại hay không. Vui lòng tham khảo model card để biết thêm chi tiết về các tác hại tiềm ẩn của model. - feature_extractor (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 chosafety_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. 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() để nạp các embedding textual inversion
- load_lora_weights() để nạp trọng số LoRA
- save_lora_weights() để lưu trọng số LoRA
- from_single_file() để tải các tệp
.ckpt - load_ip_adapter() để nạp IP Adapters
__call__
< source >( prompt: str | list[str] = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonenum_inference_steps: int = 4strength: float = 0.8original_inference_steps: int = Nonetimesteps: list = Noneguidance_scale: float = 8.5num_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']**kwargs ) → StableDiffusionPipelineOutput or tuple
Tham số
- prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn cần truyềnprompt_embeds. - image (
torch.Tensor,PIL.Image.Image,np.ndarray,list[torch.Tensor],list[PIL.Image.Image]hoặclist[np.ndarray]) —Imagehoặ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 các image latents dưới dạngimage, nhưng nếu truyền trực tiếp latents thì chúng sẽ không được mã hóa lại. - num_inference_steps (
int, tùy chọn, 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 chi phí là suy luận chậm hơn. - strength (
float, tùy chọn, mặc định là 0.8) — Chỉ ra mức độ biến đổi ảnh tham chiếuimage. 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 nhiều nhiễu được thêm vào khistrengthcàng cao. Số bước khử nhiễu phụ thuộc vào lượng nhiễu ban đầu được thêm vào. Khistrengthlà 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 trongnum_inference_steps. Giá trị 1 về cơ bản sẽ bỏ quaimage. - original_inference_steps (
int, tùy chọn) — Số bước suy luận ban đầu được dùng để tạo lịch trình timestep phân bố tuyến tính, từ đó chúng ta sẽ lấynum_inference_stepstimestep phân bố đều làm lịch trình timestep 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ị mặc định sẽ là thuộc tínhoriginal_inference_stepscủa scheduler. - timesteps (
list[int], tùy chọn) — 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 giannum_inference_stepscá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, tùy chọn, 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ớipromptvă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 khiguidance_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 khiguidance_scale > 0). - num_images_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng hình ảnh cần tạo cho mỗi prompt. - generator (
torch.Generatorhoặclist[torch.Generator], tùy chọn) — Mộttorch.Generatorđể làm cho quá trình sinh ra kết quả xác đị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ụnggeneratorngẫu nhiên được cung cấp. - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - 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 hình ảnh được 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 hình ảnh âm nếudo_classifier_free_guidanceđược đặt thànhTrue. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vàoip_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ữaPIL.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về một 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, nếu được chỉ định, sẽ được truyền đếnAttentionProcessornhư đã định nghĩa trongself.processor. - clip_skip (
int, tùy chọn) — Số lượng lớp được bỏ qua từ CLIP khi tính toán các embedding của prompt. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối sẽ được sử dụng để tính toán các embedding của prompt. - 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_kwargssẽ bao gồm danh sách tất cả các tensor như được chỉ định bởicallback_on_step_end_tensor_inputs. - callback_on_step_end_tensor_inputs (
list, optional) — Danh sách các tensor đầu vào cho hàmcallback_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_inputscủa lớp pipeline của bạn.
Trả về
StableDiffusionPipelineOutput hoặc tuple
Nếu return_dict là True, StableDiffusionPipelineOutput sẽ được trả về,
ngoài ra 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 được tạo và phần tử
thứ hai là một danh sách các bool cho biết hình ảnh được tạo 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ụ:
>>> 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
< source >( s1: floats2: floatb1: floatb2: float )
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 để 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.
Tắt cơ chế FreeU nếu đang được bật.
encode_prompt
< source >( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )
Tham số
- prompt (
strhoặclist[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 (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalenhỏ hơn1). - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầ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àonegative_prompt. - lora_scale (
float, tùy 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, tùy chọn) — Số lượng lớp được bỏ qua từ CLIP khi tính toán các embedding của prompt. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối sẽ được sử dụng để tính toán các embedding của prompt.
Mã hóa prompt thành các trạng thái ẩn của text encoder.
get_guidance_scale_embedding
< source >( w: Tensorembedding_dim: int = 512dtype: dtype = torch.float32 ) → torch.Tensor
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, tùy 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).
StableDiffusionPipelineOutput
lớp diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput
< source >( images: list[PIL.Image.Image] | numpy.ndarraynsfw_content_detected: list[bool] | None )
Tham số
- images (
list[PIL.Image.Image]hoặcnp.ndarray) — danh sách các hình ảnh PIL đã khử nhiễu có độ dàibatch_sizehoặ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” (nsfw) hay không, hoặcNonenếu không thể thực hiện kiểm tra an toàn.
Lớp đầu ra cho các pipeline Stable Diffusion.