Diffusers documentation
DeepFloyd IF
DeepFloyd IF
Tổng quan
DeepFloyd IF là một mô hình text-to-image mã nguồn mở tiên tiến mới với mức độ chân thực cao và khả năng hiểu ngôn ngữ. Mô hình này có cấu trúc mô-đun, bao gồm một text encoder đóng băng và ba mô-đun pixel diffusion nối tiếp:
- Giai đoạn 1: một mô hình cơ bản tạo ra hình ảnh 64x64 px dựa trên câu lệnh văn bản,
- Giai đoạn 2: một mô hình siêu phân giải 64x64 px => 256x256 px, và
- Giai đoạn 3: mô hình siêu phân giải 256x256 px => 1024x1024 px Giai đoạn 1 và Giai đoạn 2 sử dụng text encoder đóng băng dựa trên transformer T5 để trích xuất text embeddings, sau đó các embeddings này được đưa vào kiến trúc UNet được tăng cường với cross-attention và attention pooling. Giai đoạn 3 là mô hình x4 Upscaling của Stability AI. Kết quả là một mô hình cực kỳ hiệu quả, vượt trội hơn các mô hình state-of-the-art hiện tại, đạt điểm FID zero-shot là 6.66 trên bộ dữ liệu COCO. Công việc của chúng tôi nhấn mạnh tiềm năng của các kiến trúc UNet lớn hơn trong giai đoạn đầu tiên của các mô hình diffusion dạng cascaded và phác thảo một tương lai đầy hứa hẹn cho việc tổng hợp ảnh từ văn bản.
Cách sử dụng
Trước khi bạn có thể sử dụng IF, bạn cần chấp nhận các điều khoản sử dụng. Để thực hiện:
- Hãy đảm bảo bạn có tài khoản Hugging Face và đã đăng nhập.
- Chấp nhận giấy phép trên thẻ mô hình của DeepFloyd/IF-I-XL-v1.0. Việc chấp nhận giấy phép trên thẻ mô hình của giai đoạn I sẽ tự động chấp nhận cho các mô hình IF khác.
- Hãy đảm bảo bạn đã đăng nhập cục bộ. Cài đặt
huggingface_hub:
pip install huggingface_hub --upgrade
chạy hàm đăng nhập trong một shell Python:
from huggingface_hub import login
login()và nhập token truy cập Hugging Face Hub của bạn.
Tiếp theo, chúng ta cài đặt diffusers và các phụ thuộc:
pip install -q diffusers accelerate transformers
Các phần dưới đây cung cấp các ví dụ chi tiết hơn về cách sử dụng IF. Cụ thể:
- Đánh giá chất lượng hình ảnh
- Đánh giá
- Inpainting
- Tái sử dụng trọng số mô hình
- Tối ưu hóa tốc độ
- Tối ưu hóa bộ nhớ
Các checkpoint khả dụng
Giai đoạn 1
Giai đoạn 2
Giai đoạn 3
Tạo hình ảnh từ văn bản
Mặc định, diffusers sử dụng model cpu offloading để chạy toàn bộ pipeline IF với chỉ 14 GB VRAM.
from diffusers import DiffusionPipeline
from diffusers.utils import pt_to_pil, make_image_grid
import torch
# stage 1
stage_1 = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
stage_1.enable_model_cpu_offload()
# stage 2
stage_2 = DiffusionPipeline.from_pretrained(
"DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", dtype=torch.float16
)
stage_2.enable_model_cpu_offload()
# stage 3
safety_modules = {
"feature_extractor": stage_1.feature_extractor,
"safety_checker": stage_1.safety_checker,
"watermarker": stage_1.watermarker,
}
stage_3 = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-x4-upscaler", **safety_modules, dtype=torch.float16
)
stage_3.enable_model_cpu_offload()
prompt = 'a photo of a kangaroo wearing an orange hoodie and blue sunglasses standing in front of the eiffel tower holding a sign that says "very deep learning"'
generator = torch.manual_seed(1)
# text embeds
prompt_embeds, negative_embeds = stage_1.encode_prompt(prompt)
# stage 1
stage_1_output = stage_1(
prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, generator=generator, output_type="pt"
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_I.png")
# stage 2
stage_2_output = stage_2(
image=stage_1_output,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
generator=generator,
output_type="pt",
).images
#pt_to_pil(stage_2_output)[0].save("./if_stage_II.png")
# stage 3
stage_3_output = stage_3(prompt=prompt, image=stage_2_output, noise_level=100, generator=generator).images
#stage_3_output[0].save("./if_stage_III.png")
make_image_grid([pt_to_pil(stage_1_output)[0], pt_to_pil(stage_2_output)[0], stage_3_output[0]], rows=1, rows=3)Tạo ảnh từ ảnh có hướng dẫn bằng văn bản
Cùng một bộ trọng số mô hình IF có thể được sử dụng cho việc dịch chuyển ảnh sang ảnh có hướng dẫn bằng văn bản hoặc tạo biến thể ảnh. Trong trường hợp này, hãy đảm bảo tải trọng số bằng cách sử dụng các pipeline IFImg2ImgPipeline và IFImg2ImgSuperResolutionPipeline.
Lưu ý: Bạn cũng có thể di chuyển trực tiếp trọng số của các pipeline text-to-image sang các pipeline image-to-image mà không cần nạp chúng hai lần bằng cách sử dụng đối số components như đã giải thích tại đây.
from diffusers import IFImg2ImgPipeline, IFImg2ImgSuperResolutionPipeline, DiffusionPipeline
from diffusers.utils import pt_to_pil, load_image, make_image_grid
import torch
# download image
url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
original_image = load_image(url)
original_image = original_image.resize((768, 512))
# stage 1
stage_1 = IFImg2ImgPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
stage_1.enable_model_cpu_offload()
# stage 2
stage_2 = IFImg2ImgSuperResolutionPipeline.from_pretrained(
"DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", dtype=torch.float16
)
stage_2.enable_model_cpu_offload()
# stage 3
safety_modules = {
"feature_extractor": stage_1.feature_extractor,
"safety_checker": stage_1.safety_checker,
"watermarker": stage_1.watermarker,
}
stage_3 = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-x4-upscaler", **safety_modules, dtype=torch.float16
)
stage_3.enable_model_cpu_offload()
prompt = "A fantasy landscape in style minecraft"
generator = torch.manual_seed(1)
# text embeds
prompt_embeds, negative_embeds = stage_1.encode_prompt(prompt)
# stage 1
stage_1_output = stage_1(
image=original_image,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
generator=generator,
output_type="pt",
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_I.png")
# stage 2
stage_2_output = stage_2(
image=stage_1_output,
original_image=original_image,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
generator=generator,
output_type="pt",
).images
#pt_to_pil(stage_2_output)[0].save("./if_stage_II.png")
# stage 3
stage_3_output = stage_3(prompt=prompt, image=stage_2_output, generator=generator, noise_level=100).images
#stage_3_output[0].save("./if_stage_III.png")
make_image_grid([original_image, pt_to_pil(stage_1_output)[0], pt_to_pil(stage_2_output)[0], stage_3_output[0]], rows=1, rows=4)Tạo Inpainting có hướng dẫn bằng văn bản
Cùng một bộ trọng số mô hình IF có thể được sử dụng cho việc dịch chuyển ảnh sang ảnh có hướng dẫn bằng văn bản hoặc tạo biến thể ảnh. Trong trường hợp này, hãy đảm bảo tải trọng số bằng cách sử dụng các pipeline IFInpaintingPipeline và IFInpaintingSuperResolutionPipeline.
Lưu ý: Bạn cũng có thể di chuyển trực tiếp trọng số của các pipeline text-to-image sang các pipeline image-to-image mà không cần nạp chúng hai lần bằng cách sử dụng hàm ~DiffusionPipeline.components() như đã giải thích tại đây.
from diffusers import IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, DiffusionPipeline
from diffusers.utils import pt_to_pil, load_image, make_image_grid
import torch
# download image
url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/person.png"
original_image = load_image(url)
# download mask
url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/glasses_mask.png"
mask_image = load_image(url)
# stage 1
stage_1 = IFInpaintingPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
stage_1.enable_model_cpu_offload()
# stage 2
stage_2 = IFInpaintingSuperResolutionPipeline.from_pretrained(
"DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", dtype=torch.float16
)
stage_2.enable_model_cpu_offload()
# stage 3
safety_modules = {
"feature_extractor": stage_1.feature_extractor,
"safety_checker": stage_1.safety_checker,
"watermarker": stage_1.watermarker,
}
stage_3 = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-x4-upscaler", **safety_modules, dtype=torch.float16
)
stage_3.enable_model_cpu_offload()
prompt = "blue sunglasses"
generator = torch.manual_seed(1)
# text embeds
prompt_embeds, negative_embeds = stage_1.encode_prompt(prompt)
# stage 1
stage_1_output = stage_1(
image=original_image,
mask_image=mask_image,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
generator=generator,
output_type="pt",
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_I.png")
# stage 2
stage_2_output = stage_2(
image=stage_1_output,
original_image=original_image,
mask_image=mask_image,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
generator=generator,
output_type="pt",
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_II.png")
# stage 3
stage_3_output = stage_3(prompt=prompt, image=stage_2_output, generator=generator, noise_level=100).images
#stage_3_output[0].save("./if_stage_III.png")
make_image_grid([original_image, mask_image, pt_to_pil(stage_1_output)[0], pt_to_pil(stage_2_output)[0], stage_3_output[0]], rows=1, rows=5)Chuyển đổi giữa các pipeline khác nhau
Ngoài việc được nạp bằng from_pretrained, Pipelines cũng có thể được nạp trực tiếp từ các Pipeline khác.
from diffusers import IFPipeline, IFSuperResolutionPipeline
pipe_1 = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0")
pipe_2 = IFSuperResolutionPipeline.from_pretrained("DeepFloyd/IF-II-L-v1.0")
from diffusers import IFImg2ImgPipeline, IFImg2ImgSuperResolutionPipeline
pipe_1 = IFImg2ImgPipeline(**pipe_1.components)
pipe_2 = IFImg2ImgSuperResolutionPipeline(**pipe_2.components)
from diffusers import IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline
pipe_1 = IFInpaintingPipeline(**pipe_1.components)
pipe_2 = IFInpaintingSuperResolutionPipeline(**pipe_2.components)Tối ưu hóa cho tốc độ
Tối ưu hóa đơn giản nhất để chạy IF nhanh hơn là di chuyển tất cả các thành phần của mô hình sang GPU.
pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.to("cuda") # or "mps", "xpu", "cpu"Bạn cũng có thể chạy quá trình khuếch tán với số bước thời gian ngắn hơn.
Điều này có thể được thực hiện bằng cách sử dụng đối số num_inference_steps:
pipe("<prompt>", num_inference_steps=30)Hoặc với đối số timesteps:
from diffusers.pipelines.deepfloyd_if import fast27_timesteps
pipe("<prompt>", timesteps=fast27_timesteps)Khi thực hiện tạo biến thể ảnh hoặc inpainting, bạn cũng có thể giảm số lượng bước thời gian (timesteps) bằng đối số strength. Đối số strength là lượng nhiễu được thêm vào ảnh đầu vào, đồng thời xác định số bước cần chạy trong quá trình khử nhiễu. Giá trị nhỏ hơn sẽ làm thay đổi ảnh ít hơn nhưng chạy nhanh hơn.
pipe = IFImg2ImgPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
image = pipe(image=image, prompt="<prompt>", strength=0.3).imagesBạn cũng có thể sử dụng torch.compile. Lưu ý rằng chúng tôi chưa kiểm tra torch.compile một cách đầy đủ với IF và nó có thể không cho kết quả như mong đợi.
from diffusers import DiffusionPipeline
import torch
pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
pipe.text_encoder = torch.compile(pipe.text_encoder, mode="reduce-overhead", fullgraph=True)
pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)Tối ưu hóa cho bộ nhớ
Khi tối ưu hóa bộ nhớ GPU, chúng ta có thể sử dụng các API offloading CPU chuẩn của diffusers.
Hoặc việc offload CPU dựa trên model,
pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.enable_model_cpu_offload()hoặc phương pháp offload CPU dựa trên lớp (layer) mang tính quyết liệt hơn.
pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.enable_sequential_cpu_offload()Ngoài ra, T5 có thể được nạp ở độ chính xác 8bit
from transformers import T5EncoderModel
text_encoder = T5EncoderModel.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0", subfolder="text_encoder", device_map="auto", load_in_8bit=True, variant="8bit"
)
from diffusers import DiffusionPipeline
pipe = DiffusionPipeline.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0",
text_encoder=text_encoder, # pass the previously instantiated 8bit text encoder
unet=None,
device_map="auto",
)
prompt_embeds, negative_embeds = pipe.encode_prompt("<prompt>")Đối với các máy bị giới hạn RAM CPU như Google Colab free tier, nơi chúng ta không thể nạp tất cả các thành phần của mô hình vào CPU cùng lúc, chúng ta có thể chỉ nạp thủ công pipeline với text encoder hoặc UNet khi các thành phần mô hình tương ứng được cần đến.
from diffusers import IFPipeline, IFSuperResolutionPipeline
import torch
import gc
from transformers import T5EncoderModel
from diffusers.utils import pt_to_pil, make_image_grid
text_encoder = T5EncoderModel.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0", subfolder="text_encoder", device_map="auto", load_in_8bit=True, variant="8bit"
)
# text to image
pipe = DiffusionPipeline.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0",
text_encoder=text_encoder, # pass the previously instantiated 8bit text encoder
unet=None,
device_map="auto",
)
prompt = 'a photo of a kangaroo wearing an orange hoodie and blue sunglasses standing in front of the eiffel tower holding a sign that says "very deep learning"'
prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
# Remove the pipeline so we can re-load the pipeline with the unet
del text_encoder
del pipe
gc.collect()
torch.cuda.empty_cache()
pipe = IFPipeline.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0", text_encoder=None, variant="fp16", dtype=torch.float16, device_map="auto"
)
generator = torch.Generator().manual_seed(0)
stage_1_output = pipe(
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
output_type="pt",
generator=generator,
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_I.png")
# Remove the pipeline so we can load the super-resolution pipeline
del pipe
gc.collect()
torch.cuda.empty_cache()
# First super resolution
pipe = IFSuperResolutionPipeline.from_pretrained(
"DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", dtype=torch.float16, device_map="auto"
)
generator = torch.Generator().manual_seed(0)
stage_2_output = pipe(
image=stage_1_output,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
output_type="pt",
generator=generator,
).images
#pt_to_pil(stage_2_output)[0].save("./if_stage_II.png")
make_image_grid([pt_to_pil(stage_1_output)[0], pt_to_pil(stage_2_output)[0]], rows=1, rows=2)Các Pipeline khả dụng:
| Pipeline | Nhiệm vụ | Colab |
|---|---|---|
| pipeline_if.py | Đánh giá chất lượng hình ảnh | - |
| pipeline_if_superresolution.py | Đánh giá chất lượng hình ảnh | - |
| pipeline_if_img2img.py | Đánh giá | - |
| pipeline_if_img2img_superresolution.py | Đánh giá | - |
| pipeline_if_inpainting.py | Đánh giá | - |
| pipeline_if_inpainting_superresolution.py | Đánh giá | - |
IFPipeline
lớp diffusers.IFPipeline
< source >( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_safety_checker: bool = True )
__call__
< source >( prompt: str | list[str] = Nonenum_inference_steps: int = 100timesteps: list = Noneguidance_scale: float = 7.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1height: int | None = Nonewidth: int | None = Noneeta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1clean_caption: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = None ) → ~pipelines.stable_diffusion.IFPipelineOutput 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 phải truyềnprompt_embedsthay thế. - num_inference_steps (
int, tùy chọn, mặc định là 100) — 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. - 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 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.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ vớipromptvăn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. - 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). - 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. - height (
int, tùy chọn, mặc định là self.unet.config.sample_size) — 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) — Chiều rộng của hình ảnh được tạo ra, tính bằng pixel. - eta (
float, tùy chọn, mặc định là 0.0) — Tương ứng với tham số eta (η) trong bài báo DDIM: https://huggingface.co/papers/2010.02502. Chỉ áp dụng cho schedulers.DDIMScheduler, sẽ bị bỏ qua với các scheduler khác. - generator (
torch.Generatorhoặclist[torch.Generator], tuỳ chọn) — Một hoặc một danh sách torch generator để đảm bảo quá trình sinh là tất định. - 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. - 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. Chọn giữa PIL:PIL.Image.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về một~pipelines.stable_diffusion.IFPipelineOutputthay vì một tuple thông thường hay không. - callback (
Callable, tùy chọn) — Một hàm sẽ được gọi mỗicallback_stepsbước trong quá trình suy luận. Hàm này sẽ được gọi với các đối số sau:callback(step: int, timestep: int, latents: torch.Tensor). - callback_steps (
int, tùy chọn, mặc định là 1) — Tần suất gọi hàmcallback. Nếu không được chỉ định, callback sẽ được gọi ở mỗi bước. - clean_caption (
bool, tùy chọn, mặc định làTrue) — Có nên làm sạch caption trước khi tạo embeddings hay không. Yêu cầubeautifulsoup4vàftfyphải được cài đặt. Nếu các phụ thuộc này không được cài đặt, embeddings sẽ được tạo từ prompt thô. - 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 dướiself.processortrong diffusers.models.attention_processor.
Trả về
~pipelines.stable_diffusion.IFPipelineOutput hoặc tuple
~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.
Hàm được gọi khi gọi pipeline cho việc sinh.
Ví dụ:
>>> from diffusers import IFPipeline, IFSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> pipe = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
>>> pipe.enable_model_cpu_offload()
>>> prompt = 'a photo of a kangaroo wearing an orange hoodie and blue sunglasses standing in front of the eiffel tower holding a sign that says "very deep learning"'
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, output_type="pt").images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, output_type="pt"
... ).images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> safety_modules = {
... "feature_extractor": pipe.feature_extractor,
... "safety_checker": pipe.safety_checker,
... "watermarker": pipe.watermarker,
... }
>>> super_res_2_pipe = DiffusionPipeline.from_pretrained(
... "stabilityai/stable-diffusion-x4-upscaler", **safety_modules, torch_dtype=torch.float16
... )
>>> super_res_2_pipe.enable_model_cpu_offload()
>>> image = super_res_2_pipe(
... prompt=prompt,
... image=image,
... ).images
>>> image[0].save("./if_stage_II.png")encode_prompt
< source >( prompt: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — có sử dụng classifier free guidance hay không - num_images_per_prompt (
int, tùy chọn, mặc định là 1) — số lượng hình ảnh cần được tạo cho mỗi prompt - device — (
torch.device, tùy chọn): thiết bị torch để đặt các embedding kết quả lên - 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, bạn phải truyềnnegative_prompt_embedsthay thế. Nếu không được định nghĩa, bạn phải truyềnnegative_prompt_embedsthay thế. Bị 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. - clean_caption (bool, mặc định là
False) — NếuTrue, hàm sẽ tiền xử lý và làm sạch chú thích được cung cấp trước khi mã hóa.
Mã hóa prompt thành các trạng thái ẩn của text encoder.
IFSuperResolutionPipeline
lớp diffusers.IFSuperResolutionPipeline
< source >( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulerimage_noising_scheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_safety_checker: bool = True )
__call__
< source >( prompt: str | list[str] = Noneheight: int = Nonewidth: int = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor] = Nonenum_inference_steps: int = 50timesteps: list = Noneguidance_scale: float = 4.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1cross_attention_kwargs: dict[str, typing.Any] | None = Nonenoise_level: int = 250clean_caption: bool = True ) → ~pipelines.stable_diffusion.IFPipelineOutput 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 phải truyềnprompt_embedsthay thế. - height (
int, tùy chọn, mặc định là None) — 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à None) — Chiều rộng của hình ảnh được tạo ra, tính bằng pixel. - image (
PIL.Image.Image,np.ndarray,torch.Tensor) — Hình ảnh cần được tăng độ phân giả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. - timesteps (
list[int], tùy chọn, mặc định là None) — 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 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à 4.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ vớipromptvăn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. - 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). - 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. - eta (
float, tùy chọn, mặc định là 0.0) — Tương ứng với tham số eta (η) trong bài báo DDIM: https://huggingface.co/papers/2010.02502. Chỉ áp dụng cho schedulers.DDIMScheduler, sẽ bị bỏ qua với các scheduler khác. - generator (
torch.Generatorhoặclist[torch.Generator], tuỳ chọn) — Một hoặc một danh sách torch generator để đảm bảo quá trình sinh là tất định. - 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. - 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. Chọn giữa PIL:PIL.Image.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về một~pipelines.stable_diffusion.IFPipelineOutputthay vì một tuple thông thường hay không. - callback (
Callable, tùy chọn) — Một hàm sẽ được gọi mỗicallback_stepsbước trong quá trình suy luận. Hàm này sẽ được gọi với các đối số sau:callback(step: int, timestep: int, latents: torch.Tensor). - callback_steps (
int, tùy chọn, mặc định là 1) — Tần suất gọi hàmcallback. Nếu không được chỉ định, callback sẽ được gọi ở mỗi bước. - 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 dướiself.processortrong diffusers.models.attention_processor. - noise_level (
int, tùy chọn, mặc định là 250) — Lượng nhiễu cần thêm vào ảnh đã được phóng to. Phải nằm trong khoảng[0, 1000) - clean_caption (
bool, tùy chọn, mặc định làTrue) — Có nên làm sạch caption trước khi tạo embeddings hay không. Yêu cầubeautifulsoup4vàftfyphải được cài đặt. Nếu các phụ thuộc này không được cài đặt, embeddings sẽ được tạo từ prompt thô.
Trả về
~pipelines.stable_diffusion.IFPipelineOutput hoặc tuple
~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.
Hàm được gọi khi gọi pipeline cho việc sinh.
Ví dụ:
>>> from diffusers import IFPipeline, IFSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> pipe = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
>>> pipe.enable_model_cpu_offload()
>>> prompt = 'a photo of a kangaroo wearing an orange hoodie and blue sunglasses standing in front of the eiffel tower holding a sign that says "very deep learning"'
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, output_type="pt").images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds
... ).images
>>> image[0].save("./if_stage_II.png")encode_prompt
< source >( prompt: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — có sử dụng classifier free guidance hay không - num_images_per_prompt (
int, tùy chọn, mặc định là 1) — số lượng hình ảnh cần được tạo cho mỗi prompt - device — (
torch.device, tùy chọn): thiết bị torch để đặt các embedding kết quả lên - 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, bạn phải truyềnnegative_prompt_embedsthay thế. Nếu không được định nghĩa, bạn phải truyềnnegative_prompt_embedsthay thế. Bị 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. - clean_caption (bool, mặc định là
False) — NếuTrue, hàm sẽ tiền xử lý và làm sạch chú thích được cung cấp trước khi mã hóa.
Mã hóa prompt thành các trạng thái ẩn của text encoder.
IFImg2ImgPipeline
lớp diffusers.IFImg2ImgPipeline
< source >( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_safety_checker: bool = True )
__call__
< source >( prompt: str | list[str] = Noneimage: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonestrength: float = 0.7num_inference_steps: int = 80timesteps: list = Noneguidance_scale: float = 10.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1clean_caption: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = None ) → ~pipelines.stable_diffusion.IFPipelineOutput 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 phải truyềnprompt_embedsthay thế. - image (
torch.TensororPIL.Image.Image) —Image, or tensor representing an image batch, that will be used as the starting point for the process. - strength (
float, tùy chọn, mặc định là 0.7) — Về mặt khái niệm, chỉ ra mức độ biến đổi hình ảnh tham chiếuimage. Giá trị phải nằm trong khoảng từ 0 đến 1.imagesẽ được dùng làm điểm khởi đầu, với lượng nhiễu được thêm vào càng lớn khistrengthcàng cao. Số bước khử nhiễu phụ thuộc vào lượng nhiễu được thêm vào ban đầu. Khistrengthbằng 1, lượng nhiễu thêm vào sẽ là tối đa và quá trình khử nhiễu sẽ chạy đủ số lần lặp được chỉ định trongnum_inference_steps. Do đó, giá trị 1 về cơ bản sẽ bỏ quaimage. - num_inference_steps (
int, tùy chọn, mặc định là 80) — 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. - 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 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à 10.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ vớipromptvăn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. - 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). - 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. - eta (
float, tùy chọn, mặc định là 0.0) — Tương ứng với tham số eta (η) trong bài báo DDIM: https://huggingface.co/papers/2010.02502. Chỉ áp dụng cho schedulers.DDIMScheduler, sẽ bị bỏ qua với các scheduler khác. - generator (
torch.Generatorhoặclist[torch.Generator], tuỳ chọn) — Một hoặc một danh sách torch generator để đảm bảo quá trình sinh là tất định. - 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. - 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. Chọn giữa PIL:PIL.Image.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về một~pipelines.stable_diffusion.IFPipelineOutputthay vì một tuple thông thường hay không. - callback (
Callable, tùy chọn) — Một hàm sẽ được gọi mỗicallback_stepsbước trong quá trình suy luận. Hàm này sẽ được gọi với các đối số sau:callback(step: int, timestep: int, latents: torch.Tensor). - callback_steps (
int, tùy chọn, mặc định là 1) — Tần suất gọi hàmcallback. Nếu không được chỉ định, callback sẽ được gọi ở mỗi bước. - clean_caption (
bool, tùy chọn, mặc định làTrue) — Có nên làm sạch caption trước khi tạo embeddings hay không. Yêu cầubeautifulsoup4vàftfyphải được cài đặt. Nếu các phụ thuộc này không được cài đặt, embeddings sẽ được tạo từ prompt thô. - 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 dướiself.processortrong diffusers.models.attention_processor.
Trả về
~pipelines.stable_diffusion.IFPipelineOutput hoặc tuple
~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.
Hàm được gọi khi gọi pipeline cho việc sinh.
Ví dụ:
>>> from diffusers import IFImg2ImgPipeline, IFImg2ImgSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> from PIL import Image
>>> import requests
>>> from io import BytesIO
>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
>>> response = requests.get(url)
>>> original_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> original_image = original_image.resize((768, 512))
>>> pipe = IFImg2ImgPipeline.from_pretrained(
... "DeepFloyd/IF-I-XL-v1.0",
... variant="fp16",
... torch_dtype=torch.float16,
... )
>>> pipe.enable_model_cpu_offload()
>>> prompt = "A fantasy landscape in style minecraft"
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(
... image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... output_type="pt",
... ).images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFImg2ImgSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0",
... text_encoder=None,
... variant="fp16",
... torch_dtype=torch.float16,
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image,
... original_image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... ).images
>>> image[0].save("./if_stage_II.png")encode_prompt
< source >( prompt: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — có sử dụng classifier free guidance hay không - num_images_per_prompt (
int, tùy chọn, mặc định là 1) — số lượng hình ảnh cần được tạo cho mỗi prompt - device — (
torch.device, tùy chọn): thiết bị torch để đặt các embedding kết quả lên - 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, bạn phải truyềnnegative_prompt_embedsthay thế. Nếu không được định nghĩa, bạn phải truyềnnegative_prompt_embedsthay thế. Bị 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. - clean_caption (bool, mặc định là
False) — NếuTrue, hàm sẽ tiền xử lý và làm sạch chú thích được cung cấp trước khi mã hóa.
Mã hóa prompt thành các trạng thái ẩn của text encoder.
IFImg2ImgSuperResolutionPipeline
class diffusers.IFImg2ImgSuperResolutionPipeline
< source >( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulerimage_noising_scheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_safety_checker: bool = True )
__call__
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor]original_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonestrength: float = 0.8prompt: str | list[str] = Nonenum_inference_steps: int = 50timesteps: list = Noneguidance_scale: float = 4.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1cross_attention_kwargs: dict[str, typing.Any] | None = Nonenoise_level: int = 250clean_caption: bool = True ) → ~pipelines.stable_diffusion.IFPipelineOutput or tuple
Tham số
- image (
torch.TensororPIL.Image.Image) —Image, or tensor representing an image batch, that will be used as the starting point for the process. - original_image (
torch.TensorhoặcPIL.Image.Image) — Hình ảnh gốc màimageđược biến đổi từ đó. - strength (
float, tùy chọn, mặc định là 0.8) — Về mặt khái niệm, chỉ ra mức độ biến đổi hình ảnh tham chiếuimage. Giá trị phải nằm trong khoảng từ 0 đến 1.imagesẽ được dùng làm điểm khởi đầu, với lượng nhiễu được thêm vào càng lớn khistrengthcàng cao. Số bước khử nhiễu phụ thuộc vào lượng nhiễu được thêm vào ban đầu. Khistrengthbằng 1, lượng nhiễu thêm vào sẽ là tối đa và quá trình khử nhiễu sẽ chạy đủ số lần lặp được chỉ định trongnum_inference_steps. Do đó, giá trị 1 về cơ bản sẽ bỏ quaimage. - 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 phải truyềnprompt_embedsthay thế. - 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. - 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 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à 4.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ vớipromptvăn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. - 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). - 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. - eta (
float, tùy chọn, mặc định là 0.0) — Tương ứng với tham số eta (η) trong bài báo DDIM: https://huggingface.co/papers/2010.02502. Chỉ áp dụng cho schedulers.DDIMScheduler, sẽ bị bỏ qua với các scheduler khác. - generator (
torch.Generatorhoặclist[torch.Generator], tuỳ chọn) — Một hoặc một danh sách torch generator để đảm bảo quá trình sinh là tất định. - 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. - 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. Chọn giữa PIL:PIL.Image.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về một~pipelines.stable_diffusion.IFPipelineOutputthay vì một tuple thông thường hay không. - callback (
Callable, tùy chọn) — Một hàm sẽ được gọi mỗicallback_stepsbước trong quá trình suy luận. Hàm này sẽ được gọi với các đối số sau:callback(step: int, timestep: int, latents: torch.Tensor). - callback_steps (
int, tùy chọn, mặc định là 1) — Tần suất gọi hàmcallback. Nếu không được chỉ định, callback sẽ được gọi ở mỗi bước. - 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 dướiself.processortrong diffusers.models.attention_processor. - noise_level (
int, tùy chọn, mặc định là 250) — Lượng nhiễu cần thêm vào ảnh đã được phóng to. Phải nằm trong khoảng[0, 1000) - clean_caption (
bool, tùy chọn, mặc định làTrue) — Có nên làm sạch caption trước khi tạo embeddings hay không. Yêu cầubeautifulsoup4vàftfyphải được cài đặt. Nếu các phụ thuộc này không được cài đặt, embeddings sẽ được tạo từ prompt thô.
Trả về
~pipelines.stable_diffusion.IFPipelineOutput hoặc tuple
~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.
Hàm được gọi khi gọi pipeline cho việc sinh.
Ví dụ:
>>> from diffusers import IFImg2ImgPipeline, IFImg2ImgSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> from PIL import Image
>>> import requests
>>> from io import BytesIO
>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
>>> response = requests.get(url)
>>> original_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> original_image = original_image.resize((768, 512))
>>> pipe = IFImg2ImgPipeline.from_pretrained(
... "DeepFloyd/IF-I-XL-v1.0",
... variant="fp16",
... torch_dtype=torch.float16,
... )
>>> pipe.enable_model_cpu_offload()
>>> prompt = "A fantasy landscape in style minecraft"
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(
... image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... output_type="pt",
... ).images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFImg2ImgSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0",
... text_encoder=None,
... variant="fp16",
... torch_dtype=torch.float16,
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image,
... original_image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... ).images
>>> image[0].save("./if_stage_II.png")encode_prompt
< source >( prompt: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — có sử dụng classifier free guidance hay không - num_images_per_prompt (
int, tùy chọn, mặc định là 1) — số lượng hình ảnh cần được tạo cho mỗi prompt - device — (
torch.device, tùy chọn): thiết bị torch để đặt các embedding kết quả lên - 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, bạn phải truyềnnegative_prompt_embedsthay thế. Nếu không được định nghĩa, bạn phải truyềnnegative_prompt_embedsthay thế. Bị 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. - clean_caption (bool, mặc định là
False) — NếuTrue, hàm sẽ tiền xử lý và làm sạch chú thích được cung cấp trước khi mã hóa.
Mã hóa prompt thành các trạng thái ẩn của text encoder.
IFInpaintingPipeline
lớp diffusers.IFInpaintingPipeline
< source >( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_safety_checker: bool = True )
__call__
< source >( prompt: str | list[str] = Noneimage: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonemask_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonestrength: float = 1.0num_inference_steps: int = 50timesteps: list = Noneguidance_scale: float = 7.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1clean_caption: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = None ) → ~pipelines.stable_diffusion.IFPipelineOutput 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 phải truyềnprompt_embedsthay thế. - image (
torch.TensororPIL.Image.Image) —Image, or tensor representing an image batch, that will be used as the starting point for the process. - mask_image (
PIL.Image.Image) —Image, hoặc tensor đại diện cho một batch ảnh, dùng để cheimage. Các pixel trắng trong mask sẽ được vẽ lại, trong khi các pixel đen sẽ được giữ nguyên. Nếumask_imagelà ảnh PIL, nó sẽ được chuyển sang một kênh duy nhất (độ sáng) trước khi sử dụng. Nếu là tensor, nó nên chứa một kênh màu (L) thay vì 3, do đó hình dạng mong đợi sẽ là(B, H, W, 1). - strength (
float, tùy chọn, mặc định là 1.0) — Về mặt khái niệm, chỉ ra mức độ biến đổi ảnh tham chiếuimage. Giá trị phải nằm trong khoảng từ 0 đến 1.imagesẽ được dùng làm điểm khởi đầu, với lượng nhiễu được thêm vào càng lớn khistrengthcàng cao. Số bước khử nhiễu phụ thuộc vào lượng nhiễu được thêm vào ban đầu. Khistrengthbằng 1, lượng nhiễu thêm vào sẽ là tối đa và quá trình khử nhiễu sẽ chạy đủ số lần lặp được chỉ định trongnum_inference_steps. Do đó, giá trị 1 về cơ bản sẽ bỏ quaimage. - 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. - 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 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.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ vớipromptvăn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. - 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). - 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. - eta (
float, tùy chọn, mặc định là 0.0) — Tương ứng với tham số eta (η) trong bài báo DDIM: https://huggingface.co/papers/2010.02502. Chỉ áp dụng cho schedulers.DDIMScheduler, sẽ bị bỏ qua với các scheduler khác. - generator (
torch.Generatorhoặclist[torch.Generator], tuỳ chọn) — Một hoặc một danh sách torch generator để đảm bảo quá trình sinh là tất định. - 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. - 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. Chọn giữa PIL:PIL.Image.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về một~pipelines.stable_diffusion.IFPipelineOutputthay vì một tuple thông thường hay không. - callback (
Callable, tùy chọn) — Một hàm sẽ được gọi mỗicallback_stepsbước trong quá trình suy luận. Hàm này sẽ được gọi với các đối số sau:callback(step: int, timestep: int, latents: torch.Tensor). - callback_steps (
int, tùy chọn, mặc định là 1) — Tần suất gọi hàmcallback. Nếu không được chỉ định, callback sẽ được gọi ở mỗi bước. - clean_caption (
bool, tùy chọn, mặc định làTrue) — Có nên làm sạch caption trước khi tạo embeddings hay không. Yêu cầubeautifulsoup4vàftfyphải được cài đặt. Nếu các phụ thuộc này không được cài đặt, embeddings sẽ được tạo từ prompt thô. - 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 dướiself.processortrong diffusers.models.attention_processor.
Trả về
~pipelines.stable_diffusion.IFPipelineOutput hoặc tuple
~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.
Hàm được gọi khi gọi pipeline cho việc sinh.
Ví dụ:
>>> from diffusers import IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> from PIL import Image
>>> import requests
>>> from io import BytesIO
>>> url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/person.png"
>>> response = requests.get(url)
>>> original_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> original_image = original_image
>>> url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/glasses_mask.png"
>>> response = requests.get(url)
>>> mask_image = Image.open(BytesIO(response.content))
>>> mask_image = mask_image
>>> pipe = IFInpaintingPipeline.from_pretrained(
... "DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe.enable_model_cpu_offload()
>>> prompt = "blue sunglasses"
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(
... image=original_image,
... mask_image=mask_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... output_type="pt",
... ).images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFInpaintingSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image,
... mask_image=mask_image,
... original_image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... ).images
>>> image[0].save("./if_stage_II.png")encode_prompt
< source >( prompt: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — có sử dụng classifier free guidance hay không - num_images_per_prompt (
int, tùy chọn, mặc định là 1) — số lượng hình ảnh cần được tạo cho mỗi prompt - device — (
torch.device, tùy chọn): thiết bị torch để đặt các embedding kết quả lên - 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, bạn phải truyềnnegative_prompt_embedsthay thế. Nếu không được định nghĩa, bạn phải truyềnnegative_prompt_embedsthay thế. Bị 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. - clean_caption (bool, mặc định là
False) — NếuTrue, hàm sẽ tiền xử lý và làm sạch chú thích được cung cấp trước khi mã hóa.
Mã hóa prompt thành các trạng thái ẩn của text encoder.
IFInpaintingSuperResolutionPipeline
class diffusers.IFInpaintingSuperResolutionPipeline
< source >( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulerimage_noising_scheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_safety_checker: bool = True )
__call__
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor]original_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonemask_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonestrength: float = 0.8prompt: str | list[str] = Nonenum_inference_steps: int = 100timesteps: list = Noneguidance_scale: float = 4.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1cross_attention_kwargs: dict[str, typing.Any] | None = Nonenoise_level: int = 0clean_caption: bool = True ) → ~pipelines.stable_diffusion.IFPipelineOutput or tuple
Tham số
- image (
torch.TensororPIL.Image.Image) —Image, or tensor representing an image batch, that will be used as the starting point for the process. - original_image (
torch.TensorhoặcPIL.Image.Image) — Hình ảnh gốc màimageđược biến đổi từ đó. - mask_image (
PIL.Image.Image) —Image, hoặc tensor đại diện cho một batch ảnh, dùng để cheimage. Các pixel trắng trong mask sẽ được vẽ lại, trong khi các pixel đen sẽ được giữ nguyên. Nếumask_imagelà ảnh PIL, nó sẽ được chuyển sang một kênh duy nhất (độ sáng) trước khi sử dụng. Nếu là tensor, nó nên chứa một kênh màu (L) thay vì 3, do đó hình dạng mong đợi sẽ là(B, H, W, 1). - strength (
float, tùy chọn, mặc định là 0.8) — Về mặt khái niệm, chỉ ra mức độ biến đổi hình ảnh tham chiếuimage. Giá trị phải nằm trong khoảng từ 0 đến 1.imagesẽ được dùng làm điểm khởi đầu, với lượng nhiễu được thêm vào càng lớn khistrengthcàng cao. Số bước khử nhiễu phụ thuộc vào lượng nhiễu được thêm vào ban đầu. Khistrengthbằng 1, lượng nhiễu thêm vào sẽ là tối đa và quá trình khử nhiễu sẽ chạy đủ số lần lặp được chỉ định trongnum_inference_steps. Do đó, giá trị 1 về cơ bản sẽ bỏ quaimage. - 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 phải truyềnprompt_embedsthay thế. - num_inference_steps (
int, tùy chọn, mặc định là 100) — 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. - 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 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à 4.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ vớipromptvăn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. - 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). - 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. - eta (
float, tùy chọn, mặc định là 0.0) — Tương ứng với tham số eta (η) trong bài báo DDIM: https://huggingface.co/papers/2010.02502. Chỉ áp dụng cho schedulers.DDIMScheduler, sẽ bị bỏ qua với các scheduler khác. - generator (
torch.Generatorhoặclist[torch.Generator], tuỳ chọn) — Một hoặc một danh sách torch generator để đảm bảo quá trình sinh là tất định. - 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. - 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. Chọn giữa PIL:PIL.Image.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về một~pipelines.stable_diffusion.IFPipelineOutputthay vì một tuple thông thường hay không. - callback (
Callable, tùy chọn) — Một hàm sẽ được gọi mỗicallback_stepsbước trong quá trình suy luận. Hàm này sẽ được gọi với các đối số sau:callback(step: int, timestep: int, latents: torch.Tensor). - callback_steps (
int, tùy chọn, mặc định là 1) — Tần suất gọi hàmcallback. Nếu không được chỉ định, callback sẽ được gọi ở mỗi bước. - 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 dướiself.processortrong diffusers.models.attention_processor. - noise_level (
int, tùy chọn, mặc định là 0) — Lượng nhiễu cần thêm vào ảnh đã được phóng to. Phải nằm trong khoảng[0, 1000) - clean_caption (
bool, tùy chọn, mặc định làTrue) — Có nên làm sạch caption trước khi tạo embeddings hay không. Yêu cầubeautifulsoup4vàftfyphải được cài đặt. Nếu các phụ thuộc này không được cài đặt, embeddings sẽ được tạo từ prompt thô.
Trả về
~pipelines.stable_diffusion.IFPipelineOutput hoặc tuple
~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.
Hàm được gọi khi gọi pipeline cho việc sinh.
Ví dụ:
>>> from diffusers import IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> from PIL import Image
>>> import requests
>>> from io import BytesIO
>>> url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/person.png"
>>> response = requests.get(url)
>>> original_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> original_image = original_image
>>> url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/glasses_mask.png"
>>> response = requests.get(url)
>>> mask_image = Image.open(BytesIO(response.content))
>>> mask_image = mask_image
>>> pipe = IFInpaintingPipeline.from_pretrained(
... "DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe.enable_model_cpu_offload()
>>> prompt = "blue sunglasses"
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(
... image=original_image,
... mask_image=mask_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... output_type="pt",
... ).images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFInpaintingSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image,
... mask_image=mask_image,
... original_image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... ).images
>>> image[0].save("./if_stage_II.png")encode_prompt
< source >( prompt: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — có sử dụng classifier free guidance hay không - num_images_per_prompt (
int, tùy chọn, mặc định là 1) — số lượng hình ảnh cần được tạo cho mỗi prompt - device — (
torch.device, tùy chọn): thiết bị torch để đặt các embedding kết quả lên - 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, bạn phải truyềnnegative_prompt_embedsthay thế. Nếu không được định nghĩa, bạn phải truyềnnegative_prompt_embedsthay thế. Bị 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. - clean_caption (bool, mặc định là
False) — NếuTrue, hàm sẽ tiền xử lý và làm sạch chú thích được cung cấp trước khi mã hóa.
Mã hóa prompt thành các trạng thái ẩn của text encoder.