Buckets:

hf-doc-build/doc / diffusers /main /vi /api /pipelines /deepfloyd_if.md
mishig's picture
|
download
raw
92.3 kB
# 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ột mô hình siêu phân giải 256x256 px => 1024x1024 px Stage 1 và Stage 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. Stage 3 là [mô hình x4 Upscaling của Stability AI](https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler). 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: 1. Hãy đảm bảo bạn có [tài khoản Hugging Face](https://huggingface.co/join) và đã đăng nhập. 2. Chấp nhận giấy phép trên thẻ mô hình của [DeepFloyd/IF-I-XL-v1.0](https://huggingface.co/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. 3. Hãy đảm bảo bạn đã đăng nhập cục bộ. Cài đặt `huggingface_hub`: ```sh pip install huggingface_hub --upgrade ``` chạy hàm đăng nhập trong một shell Python: ```py from huggingface_hub import login login() ``` và nhập [token truy cập Hugging Face Hub](https://huggingface.co/docs/hub/security-tokens#what-are-user-access-tokens) của bạn. Tiếp theo, chúng ta cài đặt `diffusers` và các phụ thuộc: ```sh 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](#text-to-image-generation) - [Đánh giá](#text-guided-image-to-image-generation) - [Inpainting](#text-guided-inpainting-generation) - [Tái sử dụng trọng số mô hình](#converting-between-different-pipelines) - [Tối ưu hóa tốc độ](#optimizing-for-speed) - [Tối ưu hóa bộ nhớ](#optimizing-for-memory) **Các checkpoint khả dụng** - *Giai đoạn 1* - [DeepFloyd/IF-I-XL-v1.0](https://huggingface.co/DeepFloyd/IF-I-XL-v1.0) - [DeepFloyd/IF-I-L-v1.0](https://huggingface.co/DeepFloyd/IF-I-L-v1.0) - [DeepFloyd/IF-I-M-v1.0](https://huggingface.co/DeepFloyd/IF-I-M-v1.0) - *Giai đoạn 2* - [DeepFloyd/IF-II-L-v1.0](https://huggingface.co/DeepFloyd/IF-II-L-v1.0) - [DeepFloyd/IF-II-M-v1.0](https://huggingface.co/DeepFloyd/IF-II-M-v1.0) - *Giai đoạn 3* - [stabilityai/stable-diffusion-x4-upscaler](https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler) **Google Colab** [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/deepfloyd_if_free_tier_google_colab.ipynb) ### Tạo hình ảnh từ văn bản Mặc định, diffusers sử dụng [model cpu offloading](../../optimization/memory#model-offloading) để chạy toàn bộ pipeline IF với chỉ 14 GB VRAM. ```python 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](/docs/diffusers/main/vi/api/pipelines/deepfloyd_if#diffusers.IFImg2ImgPipeline) và [IFImg2ImgSuperResolutionPipeline](/docs/diffusers/main/vi/api/pipelines/deepfloyd_if#diffusers.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](/docs/diffusers/main/vi/api/pipelines/overview#diffusers.DiffusionPipeline.components) như đã giải thích [tại đây](#converting-between-different-pipelines). ```python 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](/docs/diffusers/main/vi/api/pipelines/deepfloyd_if#diffusers.IFInpaintingPipeline) và [IFInpaintingSuperResolutionPipeline](/docs/diffusers/main/vi/api/pipelines/deepfloyd_if#diffusers.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](#converting-between-different-pipelines). ```python 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. ```python 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. ```py 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`: ```py pipe("<prompt>", num_inference_steps=30) ``` Hoặc với đối số `timesteps`: ```py 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 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. ```py 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).images ``` Bạn cũng có thể sử dụng [`torch.compile`](../../optimization/fp16#torchcompile). 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. ```py 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, ```py 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. ```py 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 ```py 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. ```py 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 | Các tác vụ | Colab |---|---|:---:| | [pipeline_if.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if.py) | *Đánh giá chất lượng hình ảnh* | - | | [pipeline_if_superresolution.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py) | *Đánh giá chất lượng hình ảnh* | - | | [pipeline_if_img2img.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py) | *Đánh giá* | - | | [pipeline_if_img2img_superresolution.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py) | *Đánh giá* | - | | [pipeline_if_inpainting.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py) | *Đánh giá* | - | | [pipeline_if_inpainting_superresolution.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py) | *Đánh giá* | - | ## IFPipeline[[diffusers.IFPipeline]] #### diffusers.IFPipeline[[diffusers.IFPipeline]] ```python diffusers.IFPipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, unet: UNet2DConditionModel, scheduler: DDPMScheduler, safety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None, watermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | None, requires_safety_checker: bool = True) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if.py#L96) #### __call__[[diffusers.IFPipeline.__call__]] ```python __call__(prompt: str | list[str] = None, num_inference_steps: int = 100, timesteps: list[int] = None, guidance_scale: float = 7.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, height: int | None = None, width: int | None = None, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, clean_caption: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if.py#L547) **Tham số:** prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế. num_inference_steps (`int`, *optional*, 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 cái giá là suy luận chậm hơn. timesteps (`list[int]`, *optional*) : Các bước thời gian tùy chỉnh để sử dụng cho quá trình khử nhiễu. Nếu không được định nghĩa, các bước thời gian `num_inference_steps` cách đều sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần. guidance_scale (`float`, *optional*, mặc định là 7.0) : Thang độ dẫn hướng như được định nghĩa trong [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` được định nghĩa là `w` của phương trình 2. trong [Imagen Paper](https://huggingface.co/papers/2205.11487). Thang độ dẫn hướng được kích hoạt bằng cách đặt `guidance_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ới `prompt` văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`). num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt. height (`int`, *tuỳ 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`, *tuỳ chọn*, mặc định là self.unet.config.sample_size) : Độ rộng tính bằng pixel của hình ảnh được tạo ra. eta (`float`, *optional*, 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](/docs/diffusers/main/vi/api/schedulers/ddim#diffusers.DDIMScheduler), sẽ bị bỏ qua với các trình lập lịch khác. generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một hoặc một danh sách [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định. prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`. negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`. 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](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`. return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.stable_diffusion.IFPipelineOutput` thay 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ỗi `callback_steps` bước trong quá trình suy luận. Hàm sẽ được gọi với các đối số sau: `callback(step: int, timestep: int, latents: torch.Tensor)`. callback_steps (`int`, *optional*, mặc định là 1) : Tần suất mà hàm `callback` sẽ được gọi. 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ó dọn dẹp chú thích trước khi tạo embeddings hay không. Yêu cầu `beautifulsoup4` và `ftfy` phả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 mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). **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 `bool`s 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ụ: ```py >>> 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[[diffusers.IFPipeline.encode_prompt]] ```python encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, negative_prompt: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, clean_caption: bool = False) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if.py#L168) **Tham số:** prompt (`str` hoặc `list[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 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay vào đó. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay vào đó. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`). prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`. negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`. clean_caption (bool, mặc định là `False`) : Nếu `True`, 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[[diffusers.IFSuperResolutionPipeline]] #### diffusers.IFSuperResolutionPipeline[[diffusers.IFSuperResolutionPipeline]] ```python diffusers.IFSuperResolutionPipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, unet: UNet2DConditionModel, scheduler: DDPMScheduler, image_noising_scheduler: DDPMScheduler, safety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None, watermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | None, requires_safety_checker: bool = True) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py#L82) #### __call__[[diffusers.IFSuperResolutionPipeline.__call__]] ```python __call__(prompt: str | list[str] = None, height: int = None, width: int = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor] = None, num_inference_steps: int = 50, timesteps: list[int] = None, guidance_scale: float = 4.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, cross_attention_kwargs: dict[str, typing.Any] | None = None, noise_level: int = 250, clean_caption: bool = True) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py#L614) **Tham số:** prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế. height (`int`, *tuỳ 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`, *tuỳ chọn*, mặc định là None) : Độ rộng của hình ảnh được tạo ra, tính bằng pixel. image (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`) : Ảnh cần được phóng to. num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn. timesteps (`list[int]`, *optional*, 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 gian `num_inference_steps` cách đều sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần. guidance_scale (`float`, *optional*, mặc định là 4.0) : Thang độ dẫn hướng như được định nghĩa trong [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` được định nghĩa là `w` của phương trình 2. trong [Imagen Paper](https://huggingface.co/papers/2205.11487). Thang độ dẫn hướng được kích hoạt bằng cách đặt `guidance_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ới `prompt` văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`). num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt. eta (`float`, *optional*, 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](/docs/diffusers/main/vi/api/schedulers/ddim#diffusers.DDIMScheduler), sẽ bị bỏ qua với các trình lập lịch khác. generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một hoặc một danh sách [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định. prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`. negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`. 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](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`. return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.stable_diffusion.IFPipelineOutput` thay 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ỗi `callback_steps` bước trong quá trình suy luận. Hàm sẽ được gọi với các đối số sau: `callback(step: int, timestep: int, latents: torch.Tensor)`. callback_steps (`int`, *optional*, mặc định là 1) : Tần suất mà hàm `callback` sẽ được gọi. 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 mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). noise_level (`int`, *optional*, 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ó dọn dẹp chú thích trước khi tạo embeddings hay không. Yêu cầu `beautifulsoup4` và `ftfy` phả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 `bool`s 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ụ: ```py >>> 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[[diffusers.IFSuperResolutionPipeline.encode_prompt]] ```python encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, negative_prompt: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, clean_caption: bool = False) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py#L302) **Tham số:** prompt (`str` hoặc `list[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 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay vào đó. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay vào đó. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`). prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`. negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`. clean_caption (bool, mặc định là `False`) : Nếu `True`, 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[[diffusers.IFImg2ImgPipeline]] #### diffusers.IFImg2ImgPipeline[[diffusers.IFImg2ImgPipeline]] ```python diffusers.IFImg2ImgPipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, unet: UNet2DConditionModel, scheduler: DDPMScheduler, safety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None, watermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | None, requires_safety_checker: bool = True) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py#L120) #### __call__[[diffusers.IFImg2ImgPipeline.__call__]] ```python __call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = None, strength: float = 0.7, num_inference_steps: int = 80, timesteps: list[int] = None, guidance_scale: float = 10.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, clean_caption: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py#L661) **Tham số:** prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế. image (`torch.Tensor` hoặc `PIL.Image.Image`) : `Image`, hoặc tensor đại diện cho một lô ảnh, sẽ được sử dụng làm điểm bắt đầu cho quy trình. strength (`float`, *optional*, 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ếu `image`. Giá trị phải nằm trong khoảng từ 0 đến 1. `image` sẽ đượ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 khi `strength` càng cao. Số bước khử nhiễu phụ thuộc vào lượng nhiễu ban đầu được thêm vào. Khi `strength` bằng 1, lượng nhiễu thêm vào sẽ đạt mức tối đa và quá trình khử nhiễu sẽ chạy đủ số lần lặp được chỉ định trong `num_inference_steps`. Do đó, giá trị 1 về cơ bản sẽ bỏ qua `image`. num_inference_steps (`int`, *optional*, 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 cái giá là suy luận chậm hơn. timesteps (`list[int]`, *optional*) : Các bước thời gian tùy chỉnh để sử dụng cho quá trình khử nhiễu. Nếu không được định nghĩa, các bước thời gian `num_inference_steps` cách đều sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần. guidance_scale (`float`, *optional*, mặc định là 10.0) : Thang độ dẫn hướng như được định nghĩa trong [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` được định nghĩa là `w` của phương trình 2. trong [Imagen Paper](https://huggingface.co/papers/2205.11487). Thang độ dẫn hướng được kích hoạt bằng cách đặt `guidance_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ới `prompt` văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`). num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt. eta (`float`, *optional*, 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](/docs/diffusers/main/vi/api/schedulers/ddim#diffusers.DDIMScheduler), sẽ bị bỏ qua với các trình lập lịch khác. generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một hoặc một danh sách [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định. prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`. negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`. 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](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`. return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.stable_diffusion.IFPipelineOutput` thay 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ỗi `callback_steps` bước trong quá trình suy luận. Hàm sẽ được gọi với các đối số sau: `callback(step: int, timestep: int, latents: torch.Tensor)`. callback_steps (`int`, *optional*, mặc định là 1) : Tần suất mà hàm `callback` sẽ được gọi. 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ó dọn dẹp chú thích trước khi tạo embeddings hay không. Yêu cầu `beautifulsoup4` và `ftfy` phả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 mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). **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 `bool`s 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ụ: ```py >>> 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[[diffusers.IFImg2ImgPipeline.encode_prompt]] ```python encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, negative_prompt: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, clean_caption: bool = False) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py#L192) **Tham số:** prompt (`str` hoặc `list[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 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay vào đó. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay vào đó. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`). prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`. negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`. clean_caption (bool, mặc định là `False`) : Nếu `True`, 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[[diffusers.IFImg2ImgSuperResolutionPipeline]] #### diffusers.IFImg2ImgSuperResolutionPipeline[[diffusers.IFImg2ImgSuperResolutionPipeline]] ```python diffusers.IFImg2ImgSuperResolutionPipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, unet: UNet2DConditionModel, scheduler: DDPMScheduler, image_noising_scheduler: DDPMScheduler, safety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None, watermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | None, requires_safety_checker: bool = True) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py#L124) #### __call__[[diffusers.IFImg2ImgSuperResolutionPipeline.__call__]] ```python __call__(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]] = None, strength: float = 0.8, prompt: str | list[str] = None, num_inference_steps: int = 50, timesteps: list[int] = None, guidance_scale: float = 4.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, cross_attention_kwargs: dict[str, typing.Any] | None = None, noise_level: int = 250, clean_caption: bool = True) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py#L744) **Tham số:** image (`torch.Tensor` hoặc `PIL.Image.Image`) : `Image`, hoặc tensor đại diện cho một lô ảnh, sẽ được sử dụng làm điểm bắt đầu cho quy trình. original_image (`torch.Tensor` hoặc `PIL.Image.Image`) : Ảnh gốc mà `image` được biến đổi từ đó. strength (`float`, *optional*, 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ếu `image`. Giá trị phải nằm trong khoảng từ 0 đến 1. `image` sẽ đượ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 khi `strength` càng cao. Số bước khử nhiễu phụ thuộc vào lượng nhiễu ban đầu được thêm vào. Khi `strength` bằng 1, lượng nhiễu thêm vào sẽ đạt mức tối đa và quá trình khử nhiễu sẽ chạy đủ số lần lặp được chỉ định trong `num_inference_steps`. Do đó, giá trị 1 về cơ bản sẽ bỏ qua `image`. prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế. num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn. timesteps (`list[int]`, *optional*) : Các bước thời gian tùy chỉnh để sử dụng cho quá trình khử nhiễu. Nếu không được định nghĩa, các bước thời gian `num_inference_steps` cách đều sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần. guidance_scale (`float`, *optional*, mặc định là 4.0) : Thang độ dẫn hướng như được định nghĩa trong [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` được định nghĩa là `w` của phương trình 2. trong [Imagen Paper](https://huggingface.co/papers/2205.11487). Thang độ dẫn hướng được kích hoạt bằng cách đặt `guidance_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ới `prompt` văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`). num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt. eta (`float`, *optional*, 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](/docs/diffusers/main/vi/api/schedulers/ddim#diffusers.DDIMScheduler), sẽ bị bỏ qua với các trình lập lịch khác. generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một hoặc một danh sách [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định. prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`. negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`. 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](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`. return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.stable_diffusion.IFPipelineOutput` thay 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ỗi `callback_steps` bước trong quá trình suy luận. Hàm sẽ được gọi với các đối số sau: `callback(step: int, timestep: int, latents: torch.Tensor)`. callback_steps (`int`, *optional*, mặc định là 1) : Tần suất mà hàm `callback` sẽ được gọi. 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 mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). noise_level (`int`, *optional*, 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ó dọn dẹp chú thích trước khi tạo embeddings hay không. Yêu cầu `beautifulsoup4` và `ftfy` phả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 `bool`s 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ụ: ```py >>> 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[[diffusers.IFImg2ImgSuperResolutionPipeline.encode_prompt]] ```python encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, negative_prompt: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, clean_caption: bool = False) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py#L344) **Tham số:** prompt (`str` hoặc `list[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 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay vào đó. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay vào đó. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`). prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`. negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`. clean_caption (bool, mặc định là `False`) : Nếu `True`, 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[[diffusers.IFInpaintingPipeline]] #### diffusers.IFInpaintingPipeline[[diffusers.IFInpaintingPipeline]] ```python diffusers.IFInpaintingPipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, unet: UNet2DConditionModel, scheduler: DDPMScheduler, safety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None, watermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | None, requires_safety_checker: bool = True) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py#L123) #### __call__[[diffusers.IFInpaintingPipeline.__call__]] ```python __call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = None, mask_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = None, strength: float = 1.0, num_inference_steps: int = 50, timesteps: list[int] = None, guidance_scale: float = 7.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, clean_caption: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py#L753) **Tham số:** prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế. image (`torch.Tensor` hoặc `PIL.Image.Image`) : `Image`, hoặc tensor đại diện cho một lô ảnh, sẽ được sử dụng làm điểm bắt đầu cho quy trình. mask_image (`PIL.Image.Image`) : `Image`, hoặc tensor đại diện cho một lô ảnh, dùng để tạo mặt nạ cho `image`. Các pixel trắng trong mặt nạ sẽ được tô lại, trong khi các pixel đen sẽ được giữ nguyên. Nếu `mask_image` là ảnh PIL, nó sẽ được chuyển đổi thành một kênh duy nhất (độ sáng) trước khi sử dụng. Nếu là tensor, nó phải 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`, *optional*, mặc định là 1.0) : Về mặt khái niệm, chỉ ra mức độ biến đổi hình ảnh tham chiếu `image`. Giá trị phải nằm trong khoảng từ 0 đến 1. `image` sẽ đượ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 khi `strength` càng cao. Số bước khử nhiễu phụ thuộc vào lượng nhiễu được thêm vào ban đầu. Khi `strength` bằng 1, lượng nhiễu thêm vào sẽ đạt mức tối đa và quá trình khử nhiễu sẽ chạy đủ số lần lặp được chỉ định trong `num_inference_steps`. Do đó, giá trị 1 về cơ bản sẽ bỏ qua `image`. num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn. timesteps (`list[int]`, *optional*) : Các bước thời gian tùy chỉnh để sử dụng cho quá trình khử nhiễu. Nếu không được định nghĩa, các bước thời gian `num_inference_steps` cách đều sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần. guidance_scale (`float`, *optional*, mặc định là 7.0) : Thang độ dẫn hướng như được định nghĩa trong [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` được định nghĩa là `w` của phương trình 2. trong [Imagen Paper](https://huggingface.co/papers/2205.11487). Thang độ dẫn hướng được kích hoạt bằng cách đặt `guidance_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ới `prompt` văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`). num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt. eta (`float`, *optional*, 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](/docs/diffusers/main/vi/api/schedulers/ddim#diffusers.DDIMScheduler), sẽ bị bỏ qua với các trình lập lịch khác. generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một hoặc một danh sách [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định. prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`. negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`. 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](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`. return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.stable_diffusion.IFPipelineOutput` thay 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ỗi `callback_steps` bước trong quá trình suy luận. Hàm sẽ được gọi với các đối số sau: `callback(step: int, timestep: int, latents: torch.Tensor)`. callback_steps (`int`, *optional*, mặc định là 1) : Tần suất mà hàm `callback` sẽ được gọi. 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ó dọn dẹp chú thích trước khi tạo embeddings hay không. Yêu cầu `beautifulsoup4` và `ftfy` phả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 mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). **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 `bool`s 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ụ: ```py >>> 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[[diffusers.IFInpaintingPipeline.encode_prompt]] ```python encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, negative_prompt: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, clean_caption: bool = False) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py#L195) **Tham số:** prompt (`str` hoặc `list[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 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay vào đó. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay vào đó. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`). prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`. negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`. clean_caption (bool, mặc định là `False`) : Nếu `True`, 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[[diffusers.IFInpaintingSuperResolutionPipeline]] #### diffusers.IFInpaintingSuperResolutionPipeline[[diffusers.IFInpaintingSuperResolutionPipeline]] ```python diffusers.IFInpaintingSuperResolutionPipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, unet: UNet2DConditionModel, scheduler: DDPMScheduler, image_noising_scheduler: DDPMScheduler, safety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None, watermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | None, requires_safety_checker: bool = True) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py#L126) #### __call__[[diffusers.IFInpaintingSuperResolutionPipeline.__call__]] ```python __call__(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]] = None, mask_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = None, strength: float = 0.8, prompt: str | list[str] = None, num_inference_steps: int = 100, timesteps: list[int] = None, guidance_scale: float = 4.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, cross_attention_kwargs: dict[str, typing.Any] | None = None, noise_level: int = 0, clean_caption: bool = True) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py#L832) **Tham số:** image (`torch.Tensor` hoặc `PIL.Image.Image`) : `Image`, hoặc tensor đại diện cho một lô ảnh, sẽ được sử dụng làm điểm bắt đầu cho quy trình. original_image (`torch.Tensor` hoặc `PIL.Image.Image`) : Ả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 lô ảnh, dùng để tạo mặt nạ cho `image`. Các pixel trắng trong mặt nạ sẽ được tô lại, trong khi các pixel đen sẽ được giữ nguyên. Nếu `mask_image` là ảnh PIL, nó sẽ được chuyển đổi thành một kênh duy nhất (độ sáng) trước khi sử dụng. Nếu là tensor, nó phải 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`, *optional*, 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ếu `image`. Giá trị phải nằm trong khoảng từ 0 đến 1. `image` sẽ đượ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 khi `strength` càng cao. Số bước khử nhiễu phụ thuộc vào lượng nhiễu ban đầu được thêm vào. Khi `strength` bằng 1, lượng nhiễu thêm vào sẽ đạt mức tối đa và quá trình khử nhiễu sẽ chạy đủ số lần lặp được chỉ định trong `num_inference_steps`. Do đó, giá trị 1 về cơ bản sẽ bỏ qua `image`. prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế. num_inference_steps (`int`, *optional*, 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 cái giá là suy luận chậm hơn. timesteps (`list[int]`, *optional*) : Các bước thời gian tùy chỉnh để sử dụng cho quá trình khử nhiễu. Nếu không được định nghĩa, các bước thời gian `num_inference_steps` cách đều sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần. guidance_scale (`float`, *optional*, mặc định là 4.0) : Thang độ dẫn hướng như được định nghĩa trong [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` được định nghĩa là `w` của phương trình 2. trong [Imagen Paper](https://huggingface.co/papers/2205.11487). Thang độ dẫn hướng được kích hoạt bằng cách đặt `guidance_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ới `prompt` văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`). num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt. eta (`float`, *optional*, 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](/docs/diffusers/main/vi/api/schedulers/ddim#diffusers.DDIMScheduler), sẽ bị bỏ qua với các trình lập lịch khác. generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một hoặc một danh sách [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định. prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`. negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`. 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](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`. return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.stable_diffusion.IFPipelineOutput` thay 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ỗi `callback_steps` bước trong quá trình suy luận. Hàm sẽ được gọi với các đối số sau: `callback(step: int, timestep: int, latents: torch.Tensor)`. callback_steps (`int`, *optional*, mặc định là 1) : Tần suất mà hàm `callback` sẽ được gọi. 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 mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). noise_level (`int`, *optional*, 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ó dọn dẹp chú thích trước khi tạo embeddings hay không. Yêu cầu `beautifulsoup4` và `ftfy` phả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 `bool`s 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ụ: ```py >>> 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[[diffusers.IFInpaintingSuperResolutionPipeline.encode_prompt]] ```python encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, negative_prompt: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, clean_caption: bool = False) ``` [Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py#L346) **Tham số:** prompt (`str` hoặc `list[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 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay vào đó. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay vào đó. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`). prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`. negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`. clean_caption (bool, mặc định là `False`) : Nếu `True`, 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.
# 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ột mô hình siêu phân giải 256x256 px => 1024x1024 px
Stage 1 và Stage 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. Stage 3 là [mô hình x4 Upscaling của Stability AI](https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler). 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:
1. Hãy đảm bảo bạn có [tài khoản Hugging Face](https://huggingface.co/join) và đã đăng nhập.
2. Chấp nhận giấy phép trên thẻ mô hình của [DeepFloyd/IF-I-XL-v1.0](https://huggingface.co/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.
3. Hãy đảm bảo bạn đã đăng nhập cục bộ. Cài đặt `huggingface_hub`:
```sh
pip install huggingface_hub --upgrade
```
chạy hàm đăng nhập trong một shell Python:
```py
from huggingface_hub import login
login()
```
và nhập [token truy cập Hugging Face Hub](https://huggingface.co/docs/hub/security-tokens#what-are-user-access-tokens) của bạn.
Tiếp theo, chúng ta cài đặt `diffusers` và các phụ thuộc:
```sh
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](#text-to-image-generation)
- [Đánh giá](#text-guided-image-to-image-generation)
- [Inpainting](#text-guided-inpainting-generation)
- [Tái sử dụng trọng số mô hình](#converting-between-different-pipelines)
- [Tối ưu hóa tốc độ](#optimizing-for-speed)
- [Tối ưu hóa bộ nhớ](#optimizing-for-memory)
**Các checkpoint khả dụng**
- *Giai đoạn 1*
- [DeepFloyd/IF-I-XL-v1.0](https://huggingface.co/DeepFloyd/IF-I-XL-v1.0)
- [DeepFloyd/IF-I-L-v1.0](https://huggingface.co/DeepFloyd/IF-I-L-v1.0)
- [DeepFloyd/IF-I-M-v1.0](https://huggingface.co/DeepFloyd/IF-I-M-v1.0)
- *Giai đoạn 2*
- [DeepFloyd/IF-II-L-v1.0](https://huggingface.co/DeepFloyd/IF-II-L-v1.0)
- [DeepFloyd/IF-II-M-v1.0](https://huggingface.co/DeepFloyd/IF-II-M-v1.0)
- *Giai đoạn 3*
- [stabilityai/stable-diffusion-x4-upscaler](https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler)
**Google Colab** [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/deepfloyd_if_free_tier_google_colab.ipynb)
### Tạo hình ảnh từ văn bản
Mặc định, diffusers sử dụng [model cpu offloading](../../optimization/memory#model-offloading) để chạy toàn bộ pipeline IF với chỉ 14 GB VRAM.
```python
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

Xet Storage Details

Size:
92.3 kB
·
Xet hash:
767cf3d6d910f32db4fc132bce4a348e1069da3425594ea3f038f9ae47ff68c3

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.