Diffusers documentation

VisualCloze

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.42.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

VisualCloze

VisualCloze: A Universal Image Generation Framework via Visual In-Context Learning 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 suất 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 làm việc 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 ví dụ 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 và VisualClozePipeline-512, 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 để 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:
    • Sinh lần đầu ở giai đoạn đầu tiên: vùng có kích thước pipe.resolution2{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 và Kho GitHub. 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

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

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ủ đề

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

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

lớp diffusers.VisualClozePipeline

< >

( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizertext_encoder_2: T5EncoderModeltokenizer_2: T5Tokenizertransformer: FluxTransformer2DModelresolution: int = 384 )

Tham số

  • transformer (FluxTransformer2DModel) — Kiến trúc Transformer có điều kiện (MMDiT) để khử nhiễu các latents ảnh đã mã hóa.
  • scheduler (FlowMatchEulerDiscreteScheduler) — Một scheduler được sử dụng kết hợp với transformer để khử nhiễu các latents ảnh đã được mã hóa.
  • vae (AutoencoderKL) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh từ và sang các biểu diễn ẩn.
  • text_encoder (CLIPTextModel) — CLIP, cụ thể là biến thể clip-vit-large-patch14.
  • text_encoder_2 (T5EncoderModel) — T5, cụ thể là biến thể google/t5-v1_1-xxl.
  • tokenizer (CLIPTokenizer) — Tokenizer của lớp CLIPTokenizer.
  • tokenizer_2 (T5TokenizerFast) — Tokenizer thứ hai của lớp T5TokenizerFast.
  • resolution (int, tùy chọn, mặc định là 384) — Độ phân giải của từng ả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ụ trực quan trong ngữ cảnh.

__call__

< >

( task_prompt: str | list[str] = Nonecontent_prompt: str | list[str] = Noneimage: typing.Optional[torch.FloatTensor] = Noneupsampling_height: int | None = Noneupsampling_width: int | None = Nonenum_inference_steps: int = 50sigmas: list[float] | None = Noneguidance_scale: float = 30.0num_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512upsampling_strength: float = 1.0 ) → ~pipelines.flux.FluxPipelineOutput or tuple

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 phải 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 phải là (B, H, W, C) hoặc (H, W, C).
  • upsampling_height (int, tùy chọn, 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, tùy chọn, mặc định là self.unet.config.sample_size * self.vae_scale_factor) — Chiều 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 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.
  • num_inference_steps (int, tùy chọn, mặc định là 50) — Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn với chi phí là suy luận chậm hơn.
  • sigmas (list[float], tùy chọn) — 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ợ đối 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 sẽ được sử dụng.
  • guidance_scale (float, tùy chọn, mặc định là 30.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance. guidance_scale được định nghĩa là w của phương trình 2. trong Imagen Paper. 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, tùy chọn, mặc định là 1) — Số lượng hình ảnh cần tạo cho mỗi prompt.
  • generator (torch.Generator hoặc list[torch.Generator], tuỳ chọn) — Một hoặc một danh sách torch generator để đảm bảo quá trình sinh là tất định.
  • latents (torch.FloatTensor, tùy chọn) — Các latents nhiễu đã được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng generator ngẫu nhiên được cung cấp.
  • prompt_embeds (torch.FloatTensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vào prompt.
  • pooled_prompt_embeds (torch.FloatTensor, tùy chọn) — Các embedding văn bản đã được gộp (pooled) sẵn. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã gộp sẽ được tạo 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.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, nếu được chỉ định, sẽ được truyền đến AttentionProcessor như đã định nghĩa dưới self.processor trong diffusers.models.attention_processor.
  • 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 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 tensor đầu vào 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, tuỳ chọn, mặc định là 1.0) — Chỉ ra mức độ biến đổi ảnh tham chiếu image khi upsampling kết quả. Phải nằm trong khoảng từ 0 đến
    1. Hình ảnh được tạo ra được dùng làm điểm khởi đầu và lượng nhiễu được thêm vào càng lớn khi upsampling_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 upsampling_strength bằng 1, lượng nhiễu 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 upsampling 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 được tạo.

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

Ví dụ:

>>> 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

lớp diffusers.VisualClozeGenerationPipeline

< >

( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizertext_encoder_2: T5EncoderModeltokenizer_2: T5Tokenizertransformer: FluxTransformer2DModelresolution: int = 384 )

Tham số

  • transformer (FluxTransformer2DModel) — Kiến trúc Transformer có điều kiện (MMDiT) để khử nhiễu các latents ảnh đã mã hóa.
  • scheduler (FlowMatchEulerDiscreteScheduler) — Một scheduler được sử dụng kết hợp với transformer để khử nhiễu các latents ảnh đã được mã hóa.
  • vae (AutoencoderKL) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh từ và sang các biểu diễn ẩn.
  • text_encoder (CLIPTextModel) — CLIP, cụ thể là biến thể clip-vit-large-patch14.
  • text_encoder_2 (T5EncoderModel) — T5, cụ thể là biến thể google/t5-v1_1-xxl.
  • tokenizer (CLIPTokenizer) — Tokenizer của lớp CLIPTokenizer.
  • tokenizer_2 (T5TokenizerFast) — Tokenizer thứ hai của lớp T5TokenizerFast.
  • resolution (int, tùy chọn, mặc định là 384) — Độ phân giải của từng ả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ụ trực quan trong ngữ cảnh.

__call__

< >

( task_prompt: str | list[str] = Nonecontent_prompt: str | list[str] = Noneimage: typing.Optional[torch.FloatTensor] = Nonenum_inference_steps: int = 50sigmas: list[float] | None = Noneguidance_scale: float = 30.0num_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput or tuple

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 phải 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 phải là (B, H, W, C) hoặc (H, W, C).
  • num_inference_steps (int, tùy chọn, mặc định là 50) — Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn với chi phí là suy luận chậm hơn.
  • sigmas (list[float], tùy chọn) — 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ợ đối 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 sẽ được sử dụng.
  • guidance_scale (float, tùy chọn, mặc định là 30.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance. guidance_scale được định nghĩa là w của phương trình 2. trong Imagen Paper. 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, tùy chọn, mặc định là 1) — Số lượng hình ảnh cần tạo cho mỗi prompt.
  • generator (torch.Generator hoặc list[torch.Generator], tuỳ chọn) — Một hoặc một danh sách torch generator để đảm bảo quá trình sinh là tất định.
  • latents (torch.FloatTensor, tùy chọn) — Các latents nhiễu đã được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng generator ngẫu nhiên được cung cấp.
  • prompt_embeds (torch.FloatTensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vào prompt.
  • pooled_prompt_embeds (torch.FloatTensor, tùy chọn) — Các embedding văn bản đã được gộp (pooled) sẵn. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã gộp sẽ được tạo 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: 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, nếu được chỉ định, sẽ được truyền đến AttentionProcessor như đã định nghĩa dưới self.processor trong diffusers.models.attention_processor.
  • 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 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 tensor đầu vào 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 được tạo.

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

Ví dụ:

>>> 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

< >

( layout_prompt: str | list[str]task_prompt: str | list[str]content_prompt: str | list[str]device: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1prompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonemax_sequence_length: int = 512lora_scale: float | None = None )

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 embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vào prompt.
  • pooled_prompt_embeds (torch.FloatTensor, tùy chọn) — Các embedding văn bản đã được gộp (pooled) sẵn. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã gộp sẽ được tạo từ đối số đầu vào prompt.
  • lora_scale (float, tùy chọn) — 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.
Update on GitHub