#
# Được cấp phép theo Giấy phép Apache, Phiên bản 2.0 (gọi là "Giấy phép");
# bạn có thể không sử dụng tệp này ngoại trừ tuân thủ theo Giấy phép.
# Bạn có thể nhận được một bản sao của Giấy phép tại
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Trừ khi được yêu cầu bởi luật pháp có hiệu lực hoặc được thỏa thuận bằng văn bản, phần mềm
# được phân phối theo Giấy phép được phân phối trên cơ sở
# KHÔNG CÓ BẢO HÀNH HOẶC ĐIỀU KIỆN DƯỚI BẤT KỲ HÌNH THỨC NÀO, dù được nêu rõ hay ngụ ý.
# Xem Giấy phép để biết ngôn ngữ cụ thể điều chỉnh các quyền và
# các hạn chế theo Giấy phép.
-->

# VisualCloze

[VisualCloze: A Universal Image Generation Framework via Visual In-Context Learning](https://huggingface.co/papers/2504.07960) là một khung tạo ảnh phổ biến dựa trên học trong ngữ cảnh (in-context learning) mang tính đổi mới, cung cấp các khả năng chính:
1. Hỗ trợ cho các tác vụ trong miền khác nhau
2. Khả năng khái quát hóa sang các tác vụ chưa từng thấy thông qua học trong ngữ cảnh
3. Gộp nhiều tác vụ thành một bước và tạo ra cả hình ảnh đích lẫn các kết quả trung gian
4. Hỗ trợ suy ngược các điều kiện từ hình ảnh đích

## Tổng quan

Tóm tắt từ bài báo là:

*Những tiến bộ gần đây trong mô hình khuếch tán (diffusion models) đã thúc đẩy đáng kể nhiều tác vụ tạo ảnh khác nhau. Tuy nhiên, cách tiếp cận chính lưu hành hiện nay vẫn tập trung vào việc xây dựng các mô hình dành riêng cho từng tác vụ, dẫn đến hiệu quả hạn chế khi hỗ trợ một phạm vi rộng các nhu cầu khác nhau. Trong khi các mô hình phổ quát cố gắng giải quyết hạn chế này, chúng phải đối mặt với những thách thức quan trọng, bao gồm chỉ thị tác vụ có khả năng khái quát hóa, phân phối tác vụ phù hợp và thiết kế kiến trúc thống nhất. Để giải quyết những thách thức này, chúng tôi đề xuất VisualCloze, một khung tạo ảnh phổ quát, hỗ trợ một phạm vi rộng các tác vụ trong miền, khái quát hóa sang các tác vụ chưa từng thấy, thống nhất nhiều tác vụ chưa từng thấy và tạo ngược. Khác với các phương pháp hiện có dựa vào chỉ thị tác vụ dựa trên ngôn ngữ, dẫn đến sự mơ hồ về tác vụ và khả năng khái quát hóa yếu, chúng tôi tích hợp học trong ngữ cảnh trực quan (visual in-context learning), cho phép mô hình xác định tác vụ từ các minh họa trực quan. Đồng thời, tính thưa thớt vốn có của phân phối tác vụ trực quan cản trở việc học kiến thức có thể chuyển giao giữa các tác vụ. Vì mục đích này, chúng tôi giới thiệu Graph200K, một tập dữ liệu có cấu trúc đồ thị thiết lập các tác vụ liên quan lẫn nhau, tăng cường mật độ tác vụ và kiến thức có thể chuyển giao. Hơn nữa, chúng tôi phát hiện ra rằng công thức tạo ảnh thống nhất của chúng tôi chia sẻ một mục tiêu nhất quán với việc lấp đầy ảnh (image infilling), cho phép chúng tôi tận dụng các tiên nghiệm sinh mạnh mẽ của các mô hình lấp đầy được huấn luyện trước mà không cần sửa đổi kiến trúc. Mã nguồn, tập dữ liệu và các mô hình có sẵn tại https://visualcloze.github.io.*

## Suy luận

### Tải mô hình

VisualCloze là một pipeline cascade hai giai đoạn, bao gồm `VisualClozeGenerationPipeline` và `VisualClozeUpsamplingPipeline`.
- Trong `VisualClozeGenerationPipeline`, mỗi hình ảnh được giảm mẫu trước khi ghép các hình ảnh vào bố cục lưới, tránh độ phân giải quá cao. VisualCloze phát hành hai mô hình phù hợp với diffusers, cụ thể là [VisualClozePipeline-384](https://huggingface.co/VisualCloze/VisualClozePipeline-384) và [VisualClozePipeline-512](https://huggingface.co/VisualCloze/VisualClozePipeline-384), lần lượt giảm mẫu hình ảnh xuống độ phân giải 384 và 512.
- `VisualClozeUpsamplingPipeline` sử dụng [SDEdit](https://huggingface.co/papers/2108.01073) để cho phép tổng hợp ảnh độ phân giải cao.

`VisualClozePipeline` tích hợp cả hai giai đoạn để hỗ trợ lấy mẫu đầu-cuối thuận tiện, đồng thời cho phép người dùng sử dụng từng pipeline độc lập khi cần.

### Quy định đầu vào

#### Gợi ý nhiệm vụ và nội dung
- Yêu cầu của tác vụ: Bắt buộc phải mô tả ý định của tác vụ tạo
- Content prompt: Mô tả hoặc chú thích tùy chọn cho hình ảnh đích
- Khi không cần nội dung prompt, hãy truyền `None`
- Để suy luận theo lô, hãy truyền `List[str|None]`

#### Định dạng đầu vào hình ảnh
- Định dạng: `List[List[Image|None]]`
- Cấu trúc:
  - Tất cả các dòng ngoại trừ dòng cuối cùng đại diện cho các ví dụ trong ngữ cảnh
  - Dòng cuối cùng đại diện cho truy vấn hiện tại (bộ ảnh mục tiêu được đặt thành `None`)
- Để suy luận theo lô, hãy truyền `List[List[List[Image|None]]]`

#### Kiểm soát độ phân giải
- Hành vi mặc định:
  - Tạo ban đầu ở giai đoạn đầu tiên: diện tích ${pipe.resolution}^2$
  - Lấy mẫu lên ở giai đoạn thứ hai: hệ số 3x
- Độ phân giải tùy chỉnh: Điều chỉnh bằng các tham số `upsampling_height` và `upsampling_width`

### Ví dụ

Để xem các ví dụ toàn diện bao phủ nhiều loại tác vụ khác nhau, vui lòng tham khảo [Trình diễn trực tuyến](https://huggingface.co/spaces/VisualCloze/VisualCloze) và [Kho GitHub](https://github.com/lzyhha/VisualCloze). Dưới đây là các ví dụ đơn giản cho ba trường hợp: chuyển đổi từ mask sang ảnh, phát hiện biên và tạo hình theo chủ thể.

#### Ví dụ cho mask2image

```python
import torch
from diffusers import VisualClozePipeline
from diffusers.utils import load_image

pipe = VisualClozePipeline.from_pretrained("VisualCloze/VisualClozePipeline-384", resolution=384, dtype=torch.bfloat16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

# Load in-context images (make sure the paths are correct and accessible)
image_paths = [
    # in-context examples
    [
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_mask.jpg'),
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_image.jpg'),
    ],
    # query with the target image
    [
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_query_mask.jpg'),
        None, # No image needed for the target image
    ],
]

# Task and content prompt
task_prompt = "In each row, a logical task is demonstrated to achieve [IMAGE2] an aesthetically pleasing photograph based on [IMAGE1] sam 2-generated masks with rich color coding."
content_prompt = """Majestic photo of a golden eagle perched on a rocky outcrop in a mountainous landscape. 
The eagle is positioned in the right foreground, facing left, with its sharp beak and keen eyes prominently visible. 
Its plumage is a mix of dark brown and golden hues, with intricate feather details. 
The background features a soft-focus view of snow-capped mountains under a cloudy sky, creating a serene and grandiose atmosphere. 
The foreground includes rugged rocks and patches of green moss. Photorealistic, medium depth of field, 
soft natural lighting, cool color palette, high contrast, sharp focus on the eagle, blurred background, 
tranquil, majestic, wildlife photography."""

# Run the pipeline
image_result = pipe(
    task_prompt=task_prompt,
    content_prompt=content_prompt,
    image=image_paths,
    upsampling_width=1344,
    upsampling_height=768,
    upsampling_strength=0.4,
    guidance_scale=30,
    num_inference_steps=30,
    max_sequence_length=512,
    generator=torch.Generator("cpu").manual_seed(0)
).images[0][0]

# Save the resulting image
image_result.save("visualcloze.png")
```

#### Ví dụ về phát hiện biên

```python
import torch
from diffusers import VisualClozePipeline
from diffusers.utils import load_image

pipe = VisualClozePipeline.from_pretrained("VisualCloze/VisualClozePipeline-384", resolution=384, dtype=torch.bfloat16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

# Load in-context images (make sure the paths are correct and accessible)
image_paths = [
    # in-context examples
    [
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_edgedetection_incontext-example-1_image.jpg'),
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_edgedetection_incontext-example-1_edge.jpg'),
    ],
    [
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_edgedetection_incontext-example-2_image.jpg'),
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_edgedetection_incontext-example-2_edge.jpg'),
    ],
    # query with the target image
    [
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_edgedetection_query_image.jpg'),
        None, # No image needed for the target image
    ],
]

# Task and content prompt
task_prompt = "Each row illustrates a pathway from [IMAGE1] a sharp and beautifully composed photograph to [IMAGE2] edge map with natural well-connected outlines using a clear logical task."
content_prompt = ""

# Run the pipeline
image_result = pipe(
    task_prompt=task_prompt,
    content_prompt=content_prompt,
    image=image_paths,
    upsampling_width=864,
    upsampling_height=1152,
    upsampling_strength=0.4,
    guidance_scale=30,
    num_inference_steps=30,
    max_sequence_length=512,
    generator=torch.Generator("cpu").manual_seed(0)
).images[0][0]

# Save the resulting image
image_result.save("visualcloze.png")
```

#### Ví dụ về tạo nội dung theo chủ đề

```python
import torch
from diffusers import VisualClozePipeline
from diffusers.utils import load_image

pipe = VisualClozePipeline.from_pretrained("VisualCloze/VisualClozePipeline-384", resolution=384, dtype=torch.bfloat16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

# Load in-context images (make sure the paths are correct and accessible)
image_paths = [
    # in-context examples
    [
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-1_reference.jpg'),
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-1_depth.jpg'),
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-1_image.jpg'),
    ],
    [
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-2_reference.jpg'),
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-2_depth.jpg'),
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-2_image.jpg'),
    ],
    # query with the target image
    [
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_query_reference.jpg'),
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_query_depth.jpg'),
        None, # No image needed for the target image
    ],
]

# Task and content prompt
task_prompt = """Each row describes a process that begins with [IMAGE1] an image containing the key object, 
[IMAGE2] depth map revealing gray-toned spatial layers and results in 
[IMAGE3] an image with artistic qualitya high-quality image with exceptional detail."""
content_prompt = """A vintage porcelain collector's item. Beneath a blossoming cherry tree in early spring, 
this treasure is photographed up close, with soft pink petals drifting through the air and vibrant blossoms framing the scene."""

# Run the pipeline
image_result = pipe(
    task_prompt=task_prompt,
    content_prompt=content_prompt,
    image=image_paths,
    upsampling_width=1024,
    upsampling_height=1024,
    upsampling_strength=0.2,
    guidance_scale=30,
    num_inference_steps=30,
    max_sequence_length=512,
    generator=torch.Generator("cpu").manual_seed(0)
).images[0][0]

# Save the resulting image
image_result.save("visualcloze.png")
```

#### Sử dụng từng pipeline một cách độc lập 

```python
import torch
from diffusers import VisualClozeGenerationPipeline, FluxFillPipeline as VisualClozeUpsamplingPipeline
from diffusers.utils import load_image
from PIL import Image

pipe = VisualClozeGenerationPipeline.from_pretrained(
    "VisualCloze/VisualClozePipeline-384", resolution=384, dtype=torch.bfloat16
)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

image_paths = [
    # in-context examples
    [
        load_image(
            "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_mask.jpg"
        ),
        load_image(
            "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_image.jpg"
        ),
    ],
    # query with the target image
    [
        load_image(
            "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_query_mask.jpg"
        ),
        None,  # No image needed for the target image
    ],
]
task_prompt = "In each row, a logical task is demonstrated to achieve [IMAGE2] an aesthetically pleasing photograph based on [IMAGE1] sam 2-generated masks with rich color coding."
content_prompt = "Majestic photo of a golden eagle perched on a rocky outcrop in a mountainous landscape. The eagle is positioned in the right foreground, facing left, with its sharp beak and keen eyes prominently visible. Its plumage is a mix of dark brown and golden hues, with intricate feather details. The background features a soft-focus view of snow-capped mountains under a cloudy sky, creating a serene and grandiose atmosphere. The foreground includes rugged rocks and patches of green moss. Photorealistic, medium depth of field, soft natural lighting, cool color palette, high contrast, sharp focus on the eagle, blurred background, tranquil, majestic, wildlife photography."

# Stage 1: Generate initial image
image = pipe(
    task_prompt=task_prompt,
    content_prompt=content_prompt,
    image=image_paths,
    guidance_scale=30,
    num_inference_steps=30,
    max_sequence_length=512,
    generator=torch.Generator("cpu").manual_seed(0),
).images[0][0]

# Stage 2 (optional): Upsample the generated image
pipe_upsample = VisualClozeUpsamplingPipeline.from_pipe(pipe)
pipe_upsample.to("cuda")

mask_image = Image.new("RGB", image.size, (255, 255, 255))

image = pipe_upsample(
    image=image,
    mask_image=mask_image,
    prompt=content_prompt,
    width=1344,
    height=768,
    strength=0.4,
    guidance_scale=30,
    num_inference_steps=30,
    max_sequence_length=512,
    generator=torch.Generator("cpu").manual_seed(0),
).images[0]

image.save("visualcloze.png")
```

## VisualClozePipeline[[diffusers.VisualClozePipeline]]

#### diffusers.VisualClozePipeline[[diffusers.VisualClozePipeline]]

```python
diffusers.VisualClozePipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: FluxTransformer2DModel, resolution: int = 384)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_combined.py#L89)

**Tham số:**

transformer ([FluxTransformer2DModel](/docs/diffusers/main/vi/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : Kiến trúc Transformer điều kiện (MMDiT) để khử nhiễu các latents ảnh đã mã hóa.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/vi/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : Một trình lập lịch được sử dụng kết hợp với `transformer` để khử nhiễu các latent ảnh đã mã hóa.

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

text_encoder (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), cụ thể là biến thể [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14).

text_encoder_2 (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), cụ thể là biến thể [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl).

tokenizer (`CLIPTokenizer`) : Tokenizer của lớp [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).

tokenizer_2 (`T5TokenizerFast`) : Tokenizer thứ hai của lớp [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).

resolution (`int`, *tuỳ chọn*, mặc định là 384) : Độ phân giải của mỗi ảnh khi ghép các ảnh từ truy vấn và các ví dụ trong ngữ cảnh.

Pipeline VisualCloze cho việc tạo ảnh với ngữ cảnh trực quan. Tham khảo: https://github.com/lzyhha/VisualCloze/tree/main. Pipeline này được thiết kế để tạo ảnh dựa trên các ví dụ trong ngữ cảnh trực quan.

#### __call__[[diffusers.VisualClozePipeline.__call__]]

```python
__call__(task_prompt: str | list[str] = None, content_prompt: str | list[str] = None, image: typing.Optional[torch.FloatTensor] = None, upsampling_height: int | None = None, upsampling_width: int | None = None, num_inference_steps: int = 50, sigmas: list[float] | None = None, guidance_scale: float = 30.0, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list = ['latents'], max_sequence_length: int = 512, upsampling_strength: float = 1.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_combined.py#L252)

**Tham số:**

task_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để xác định ý định của tác vụ.

content_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để xác định nội dung hoặc chú thích của hình ảnh đích cần được tạo ra.

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, hoặc `list[np.ndarray]`) : `Image`, mảng numpy hoặc tensor đại diện cho một lô ảnh (image batch) được sử dụng làm điểm khởi đầu. Đối với cả mảng numpy và tensor pytorch, khoảng giá trị mong đợi nằm trong `[0, 1]` Nếu là tensor hoặc danh sách các tensor, hình dạng mong đợi nên là `(B, C, H, W)` hoặc `(C, H, W)`. Nếu là mảng numpy hoặc danh sách các mảng, hình dạng mong đợi nên là `(B, H, W, C)` hoặc `(H, W, C)`.

upsampling_height (`int`, *optional*, mặc định là self.unet.config.sample_size * self.vae_scale_factor) : Chiều cao tính bằng pixel của hình ảnh được tạo ra (tức là hình ảnh đầu ra) sau khi upsampling qua SDEdit. Mặc định, hình ảnh được upsampling với hệ số ba, và độ phân giải cơ bản được xác định bởi tham số độ phân giải của pipeline. Khi chỉ một trong `upsampling_height` hoặc `upsampling_width` được chỉ định, tham số còn lại sẽ được đặt tự động dựa trên tỷ lệ khung hình.

upsampling_width (`int`, *optional*, mặc định là self.unet.config.sample_size * self.vae_scale_factor) : Độ rộng tính bằng pixel của hình ảnh được tạo ra (tức là hình ảnh đầu ra) sau khi tăng kích thước qua SDEdit. Mặc định, hình ảnh được tăng kích thước lên ba lần, và độ phân giải cơ bản được xác định bởi tham số độ phân giải của pipeline. Khi chỉ một trong `upsampling_height` hoặc `upsampling_width` được chỉ định, tham số còn lại sẽ được đặt tự động dựa trên tỷ lệ khung hình.

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.

sigmas (`list[float]`, *optional*) : Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ tham số `sigmas` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng.

guidance_scale (`float`, *optional*, mặc định là 30.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.

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

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một 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.

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

prompt_embeds (`torch.FloatTensor`, *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ố của 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`.

pooled_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể 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 embedding văn bản đã pool sẽ được tạo ra từ đối số đầu vào `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.flux.FluxPipelineOutput` thay vì một tuple thông thường hay không.

joint_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).

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

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

max_sequence_length (`int` mặc định là 512) : Độ dài tối đa của chuỗi để sử dụng với `prompt`.

upsampling_strength (`float`, *optional*, mặc định là 1.0) : Chỉ định mức độ biến đổi ảnh tham chiếu `image` khi tăng mẫu (upsampling) kết quả. Giá trị phải nằm trong khoảng từ 0 đến 1. Ảnh được tạo ra được dùng làm điểm khởi đầu và càng thêm nhiều nhiễu khi `upsampling_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 `upsampling_strength` là 1, nhiễu được thêm vào là tối đa và quá trình khử nhiễu chạy đủ số lần lặp được chỉ định trong `num_inference_steps`. Giá trị 0 bỏ qua bước tăng mẫu và xuất kết quả ở độ phân giải của `self.resolution`.

**Trả về:** `~pipelines.flux.FluxPipelineOutput` hoặc `tuple`

`~pipelines.flux.FluxPipelineOutput` nếu `return_dict` là True, ngược lại là một `tuple`. Khi trả về tuple, phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo.

Hàm được gọi khi gọi pipeline VisualCloze để tạo.

Ví dụ:
```python
>>> import torch
>>> from diffusers import VisualClozePipeline
>>> from diffusers.utils import load_image

>>> image_paths = [
...     # in-context examples
...     [
...         load_image(
...             "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_mask.jpg"
...         ),
...         load_image(
...             "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_image.jpg"
...         ),
...     ],
...     # query with the target image
...     [
...         load_image(
...             "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_query_mask.jpg"
...         ),
...         None,  # No image needed for the target image
...     ],
... ]
>>> task_prompt = "In each row, a logical task is demonstrated to achieve [IMAGE2] an aesthetically pleasing photograph based on [IMAGE1] sam 2-generated masks with rich color coding."
>>> content_prompt = "Majestic photo of a golden eagle perched on a rocky outcrop in a mountainous landscape. The eagle is positioned in the right foreground, facing left, with its sharp beak and keen eyes prominently visible. Its plumage is a mix of dark brown and golden hues, with intricate feather details. The background features a soft-focus view of snow-capped mountains under a cloudy sky, creating a serene and grandiose atmosphere. The foreground includes rugged rocks and patches of green moss. Photorealistic, medium depth of field, soft natural lighting, cool color palette, high contrast, sharp focus on the eagle, blurred background, tranquil, majestic, wildlife photography."
>>> pipe = VisualClozePipeline.from_pretrained(
...     "VisualCloze/VisualClozePipeline-384", resolution=384, torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")

>>> image = pipe(
...     task_prompt=task_prompt,
...     content_prompt=content_prompt,
...     image=image_paths,
...     upsampling_width=1344,
...     upsampling_height=768,
...     upsampling_strength=0.4,
...     guidance_scale=30,
...     num_inference_steps=30,
...     max_sequence_length=512,
...     generator=torch.Generator("cpu").manual_seed(0),
... ).images[0][0]
>>> image.save("visualcloze.png")
```

## VisualClozeGenerationPipeline[[diffusers.VisualClozeGenerationPipeline]]

#### diffusers.VisualClozeGenerationPipeline[[diffusers.VisualClozeGenerationPipeline]]

```python
diffusers.VisualClozeGenerationPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: FluxTransformer2DModel, resolution: int = 384)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py#L118)

**Tham số:**

transformer ([FluxTransformer2DModel](/docs/diffusers/main/vi/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : Kiến trúc Transformer điều kiện (MMDiT) để khử nhiễu các latents ảnh đã mã hóa.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/vi/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : Một trình lập lịch được sử dụng kết hợp với `transformer` để khử nhiễu các latent ảnh đã mã hóa.

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

text_encoder (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), cụ thể là biến thể [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14).

text_encoder_2 (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), cụ thể là biến thể [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl).

tokenizer (`CLIPTokenizer`) : Tokenizer của lớp [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).

tokenizer_2 (`T5TokenizerFast`) : Tokenizer thứ hai của lớp [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).

resolution (`int`, *tuỳ chọn*, mặc định là 384) : Độ phân giải của mỗi ảnh khi ghép các ảnh từ truy vấn và các ví dụ trong ngữ cảnh.

Pipeline VisualCloze để tạo hình ảnh với ngữ cảnh trực quan. Tham khảo: https://github.com/lzyhha/VisualCloze/tree/main Pipeline này được thiết kế để tạo hình ảnh dựa trên các ví dụ trong ngữ cảnh trực quan.

#### __call__[[diffusers.VisualClozeGenerationPipeline.__call__]]

```python
__call__(task_prompt: str | list[str] = None, content_prompt: str | list[str] = None, image: typing.Optional[torch.FloatTensor] = None, num_inference_steps: int = 50, sigmas: list[float] | None = None, guidance_scale: float = 30.0, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list = ['latents'], max_sequence_length: int = 512)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py#L659)

**Tham số:**

task_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để xác định ý định của tác vụ.

content_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để xác định nội dung hoặc chú thích của hình ảnh đích cần được tạo ra.

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, hoặc `list[np.ndarray]`) : `Image`, mảng numpy hoặc tensor đại diện cho một lô ảnh (image batch) được sử dụng làm điểm khởi đầu. Đối với cả mảng numpy và tensor pytorch, khoảng giá trị mong đợi nằm trong `[0, 1]` Nếu là tensor hoặc danh sách các tensor, hình dạng mong đợi nên là `(B, C, H, W)` hoặc `(C, H, W)`. Nếu là mảng numpy hoặc danh sách các mảng, hình dạng mong đợi nên là `(B, H, W, C)` hoặc `(H, W, C)`.

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.

sigmas (`list[float]`, *optional*) : Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ tham số `sigmas` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng.

guidance_scale (`float`, *optional*, mặc định là 30.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.

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

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một 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.

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

prompt_embeds (`torch.FloatTensor`, *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ố của 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`.

pooled_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể 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 embedding văn bản đã pool sẽ được tạo ra từ đối số đầu vào `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](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image`), `"np"` (`np.array`) hoặc `"pt"` (`torch.Tensor`).

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.flux.FluxPipelineOutput` thay vì một tuple thông thường hay không.

joint_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).

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

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

max_sequence_length (`int` mặc định là 512) : Độ dài tối đa của chuỗi để sử dụng với `prompt`.

**Trả về:** `~pipelines.flux.FluxPipelineOutput` hoặc `tuple`

`~pipelines.flux.FluxPipelineOutput` nếu `return_dict` là True, ngược lại là một `tuple`. Khi trả về tuple, phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo.

Hàm được gọi khi gọi pipeline VisualCloze để tạo.

Ví dụ:
```python
>>> import torch
>>> from diffusers import VisualClozeGenerationPipeline, FluxFillPipeline as VisualClozeUpsamplingPipeline
>>> from diffusers.utils import load_image
>>> from PIL import Image

>>> image_paths = [
...     # in-context examples
...     [
...         load_image(
...             "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_mask.jpg"
...         ),
...         load_image(
...             "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_image.jpg"
...         ),
...     ],
...     # query with the target image
...     [
...         load_image(
...             "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_query_mask.jpg"
...         ),
...         None,  # No image needed for the target image
...     ],
... ]
>>> task_prompt = "In each row, a logical task is demonstrated to achieve [IMAGE2] an aesthetically pleasing photograph based on [IMAGE1] sam 2-generated masks with rich color coding."
>>> content_prompt = "Majestic photo of a golden eagle perched on a rocky outcrop in a mountainous landscape. The eagle is positioned in the right foreground, facing left, with its sharp beak and keen eyes prominently visible. Its plumage is a mix of dark brown and golden hues, with intricate feather details. The background features a soft-focus view of snow-capped mountains under a cloudy sky, creating a serene and grandiose atmosphere. The foreground includes rugged rocks and patches of green moss. Photorealistic, medium depth of field, soft natural lighting, cool color palette, high contrast, sharp focus on the eagle, blurred background, tranquil, majestic, wildlife photography."
>>> pipe = VisualClozeGenerationPipeline.from_pretrained(
...     "VisualCloze/VisualClozePipeline-384", resolution=384, torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")

>>> image = pipe(
...     task_prompt=task_prompt,
...     content_prompt=content_prompt,
...     image=image_paths,
...     guidance_scale=30,
...     num_inference_steps=30,
...     max_sequence_length=512,
...     generator=torch.Generator("cpu").manual_seed(0),
... ).images[0][0]

>>> # optional, upsampling the generated image
>>> pipe_upsample = VisualClozeUpsamplingPipeline.from_pipe(pipe)
>>> pipe_upsample.to("cuda")

>>> mask_image = Image.new("RGB", image.size, (255, 255, 255))

>>> image = pipe_upsample(
...     image=image,
...     mask_image=mask_image,
...     prompt=content_prompt,
...     width=1344,
...     height=768,
...     strength=0.4,
...     guidance_scale=30,
...     num_inference_steps=30,
...     max_sequence_length=512,
...     generator=torch.Generator("cpu").manual_seed(0),
... ).images[0]

>>> image.save("visualcloze.png")
```

#### encode_prompt[[diffusers.VisualClozeGenerationPipeline.encode_prompt]]

```python
encode_prompt(layout_prompt: str | list[str], task_prompt: str | list[str], content_prompt: str | list[str], device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, max_sequence_length: int = 512, lora_scale: float | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py#L292)

**Tham số:**

layout_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để xác định số lượng ví dụ trong ngữ cảnh và số lượng hình ảnh liên quan đến tác vụ.

task_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để xác định ý định của tác vụ.

content_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để xác định nội dung hoặc chú thích của hình ảnh đích cần được tạo ra.

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

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

prompt_embeds (`torch.FloatTensor`, *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ố của 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`.

pooled_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể 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 embedding văn bản đã pool sẽ được tạo ra từ đối số đầu vào `prompt`.

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

