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는 혁신적인 인컨텍스트 학습 기반 범용 이미지 생성 프레임워크로, 다음과 같은 핵심 기능을 제공합니다:

  1. 다양한 도메인 내 작업 지원
  2. 인컨텍스트 학습을 통한 미확인 작업으로의 일반화
  3. 여러 작업을 한 단계로 통합하여 대상 이미지와 중간 결과를 모두 생성합니다
  4. Support reverse-engineering conditions from target images

개요

해당 논문의 초록은 다음과 같습니다:

확산 모델의 최근 발전은 다양한 이미지 생성 작업을 크게 향상시켰습니다. 그러나 현재 주류 접근법은 여전히 작업별 전용 모델 구축에 초점을 맞추고 있어, 다양한 요구 사항을 지원할 때 효율성이 제한적입니다. 범용 모델은 이러한 한계를 해결하려는 시도를 하고 있지만, 일반화 가능한 작업 지시, 적절한 작업 분포, 통합된 아키텍처 설계라는 핵심적인 과제에 직면해 있습니다. 이러한 과제들을 해결하기 위해, 우리는 다양한 도메인 내 작업을 지원하고, 미확인 작업으로의 일반화, 여러 작업의 미확인 통합, 역방향 생성을 지원하는 범용 이미지 생성 프레임워크인 VisualCloze을 제안합니다. 기존 방법들은 언어 기반 작업 지시에 의존하여 작업의 모호함과 약한 일반화 문제를 야기하는 반면, 우리는 시각적 인컨텍스트 학습을 통합하여 모델이 시각적 데모스트레이션으로부터 작업을 식별할 수 있도록 합니다. 한편, 시각적 작업 분포의 본질적인 희소성은 작업 간 이전 가능한 지식의 학습을 저해합니다. 이를 위해, 우리는 다양한 상호 연관된 작업을 확립하여 작업 밀도와 이전 가능한 지식을 강화하는 그래프 구조의 데이터셋인 Graph200K를 소개합니다. 또한, 우리의 통합 이미지 생성 수식이 이미지 인필링과 일관된 목표를 공유한다는 점을 발견하여, 아키텍처를 수정하지 않고 사전 학습된 인필링 모델의 강력한 생성적 선験을 활용할 수 있게 되었습니다. 코드, 데이터셋, 모델은 https://visualcloze.github.io에서 사용할 수 있습니다.

추론

모델 로딩

VisualCloze는 VisualClozeGenerationPipeline과 VisualClozeUpsamplingPipeline을 포함하는 2단계 캐스케이드 파이프라인입니다.

  • VisualClozeGenerationPipeline에서는 그리드 레이아웃으로 이미지를 연결하기 전에 각 이미지를 다운샘플링하여 과도하게 높은 해상도를 방지합니다. VisualCloze은 diffusers에 적합한 두 가지 모델, 즉 VisualClozePipeline-384와 VisualClozePipeline-512를 제공하며, 각각 이미지를 384와 512 해상도로 다운샘플링합니다.
  • VisualClozeUpsamplingPipeline는 SDEdit을 사용하여 고해상도 이미지 합성을 지원합니다.

VisualClozePipeline는 두 단계를 통합하여 편리한 끝에서 끝(end-to-end) 샘플링을 지원하며, 필요에 따라 각 파이프라인을 독립적으로 사용할 수도 있습니다.

입력 사양

작업 및 콘텐츠 프롬프트

  • Task prompt: 생성 작업 의도를 설명하는 데 필수
  • Content prompt: 대상 이미지의 선택적 설명 또는 캡션
  • 콘텐츠 프롬프트가 필요하지 않은 경우 None을(를) 전달합니다.
  • 배치 추론을 위해 List[str|None]를 전달하세요

이미지 입력 형식

  • Format: List[List[Image|None]]
  • 구조:
    • 마지막 행을 제외한 모든 행은 컨텍스트 내 예시를 나타냅니다
    • 마지막 행은 현재 쿼리를 나타냅니다(대상 이미지가 None으로 설정됨)
  • 배치 추론을 위해 List[List[List[Image|None]]]를 전달하세요

해상도 제어

  • 기본 동작:
    • 첫 번째 단계의 초기 생성: 영역 pipe.resolution2{pipe.resolution}^2
    • 두 번째 단계의 업샘플링: 3배 배율
  • 사용자 지정 해상도: upsampling_height 및 upsampling_width 매개변수를 사용하여 조정

예시

다양한 작업을 포괄하는 종합적인 예제는 Online Demo와 GitHub Repository를 참고하세요. 아래에는 마스크-이미지 변환, 에지 감지, 주체 기반 생성의 세 가지 사례에 대한 간단한 예제를 제공합니다.

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

엣지 감지 예제

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

주제 기반 생성 예시

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

각 파이프라인을 독립적으로 활용

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

< >

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

매개변수

  • transformer (FluxTransformer2DModel) — 인코딩된 이미지 latents의 노이즈를 제거하기 위한 Conditional Transformer (MMDiT) 아키텍처입니다.
  • scheduler (FlowMatchEulerDiscreteScheduler) — transformer와 함께 사용하여 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러.
  • vae (AutoencoderKL) — 이미지를 잠재 표현으로 인코딩하고 디코딩하는 Variational Auto-Encoder (VAE) 모델.
  • text_encoder (CLIPTextModel) — 구체적으로 clip-vit-large-patch14 변형을 사용하는 CLIP입니다.
  • text_encoder_2 (T5EncoderModel) — 구체적으로 google/t5-v1_1-xxl 변형인 T5입니다.
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 클래스의 토크나이저.
  • tokenizer_2 (T5TokenizerFast) — T5TokenizerFast 클래스의 두 번째 Tokenizer.
  • resolution (int, 선택 사항, 기본값 384) — 쿼리와 컨텍스트 내 예시의 이미지를 연결할 때 각 이미지의 해상도입니다.

시각적 컨텍스트를 활용한 이미지 생성을 위한 VisualCloze 파이프라인입니다. 참고: https://github.com/lzyhha/VisualCloze/tree/main. 이 파이프라인은 시각적 인-컨텍스트 예시를 기반으로 이미지를 생성하도록 설계되었습니다.

__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

매개변수

  • task_prompt (str 또는 list[str], 선택 사항) — 작업 의도를 정의하기 위한 프롬프트입니다.
  • content_prompt (str 또는 list[str], 선택) — 생성할 대상 이미지의 콘텐츠나 캡션을 정의하기 위한 프롬프트입니다.
  • image (torch.Tensor, PIL.Image.Image, np.ndarray, list[torch.Tensor], list[PIL.Image.Image] 또는 list[np.ndarray]) — 시작점으로 사용할 이미지 배치의 Image, numpy 배열 또는 텐서를 나타냅니다. numpy 배열과 pytorch 텐서 모두에서 예상 값 범위는 [0, 1]입니다. 텐서 또는 텐서 목록인 경우 예상 shape은 (B, C, H, W) 또는 (C, H, W)여야 합니다. numpy 배열 또는 배열 목록인 경우 예상 shape은 (B, H, W, C) 또는 (H, W, C)여야 합니다.
  • upsampling_height (int, 선택 사항, 기본값은 self.unet.config.sample_size * self.vae_scale_factor) — SDEdit를 통해 업샘플링된 생성 이미지(즉, 출력 이미지)의 픽셀 단위 높이입니다. 기본적으로 이미지는 3배로 업샘플링되며, 기본 해상도는 파이프라인의 resolution 파라미터에 의해 결정됩니다. upsampling_height 또는 upsampling_width 중 하나만 지정된 경우, 다른 하나는 종횡비에 따라 자동으로 설정됩니다.
  • upsampling_width (int, 선택 사항, 기본값은 self.unet.config.sample_size * self.vae_scale_factor) — SDEdit를 통해 업샘플링된 생성 이미지(즉, 출력 이미지)의 픽셀 단위 너비입니다. 기본적으로 이미지는 3배로 업샘플링되며, 기본 해상도는 파이프라인의 resolution 파라미터에 의해 결정됩니다. upsampling_height 또는 upsampling_width 중 하나만 지정된 경우, 다른 하나는 종횡비에 따라 자동으로 설정됩니다.
  • num_inference_steps (int, 선택 사항, 기본값 50) — 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 더 높은 품질의 이미지를 생성하지만, 추론 속도가 느려집니다.
  • sigmas (list[float], 선택 사항) — set_timesteps 메서드에 sigmas 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 시그마입니다. 정의되지 않은 경우, num_inference_steps가 전달될 때의 기본 동작이 사용됩니다.
  • guidance_scale (float, 선택 사항, 기본값 30.0) — Classifier-Free Diffusion Guidance에서 정의한 가이던스 스케일입니다. guidance_scale은 Imagen Paper의 2번 식의 w로 정의됩니다. guidance_scale > 1로 설정하면 가이던스 스케일이 활성화됩니다. 가이던스 스케일이 높을수록 prompt 텍스트와 밀접하게 연결된 이미지를 생성하도록 유도하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다.
  • num_images_per_prompt (int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지의 수입니다.
  • generator (torch.Generator 또는 list[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한 torch generator 하나 또는 목록
  • latents (torch.FloatTensor, 선택 사항) — 이미지 생성의 입력으로 사용할 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents입니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 무작위 generator를 사용하여 샘플링하여 latents 텐서가 생성됩니다.
  • prompt_embeds (torch.FloatTensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • pooled_prompt_embeds (torch.FloatTensor, 선택) — 미리 생성된 풀링된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 풀링된 텍스트 임베딩이 생성됩니다.
  • output_type (str, 선택 사항, 기본값 "pil") — 이미지 생성의 출력 형식입니다. PIL: PIL.Image.Image 또는 np.array 중 하나를 선택합니다.
  • return_dict (bool, 선택 사항, 기본값 True) — 일반 튜플 대신 ~pipelines.flux.FluxPipelineOutput를 반환할지 여부.
  • joint_attention_kwargs (dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의 self.processor에서 정의된 AttentionProcessor로 전달되는 kwargs 사전입니다.
  • callback_on_step_end (Callable, 선택 사항) — 추론 중 각 디노이징 단계의 끝에서 호출되는 함수입니다. 이 함수는 다음 인수를 받아 호출됩니다: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs에는 callback_on_step_end_tensor_inputs로 지정된 모든 텐서 목록이 포함됩니다.
  • callback_on_step_end_tensor_inputs (list, 선택 사항) — callback_on_step_end 함수의 텐서 입력 목록입니다. 목록에 지정된 텐서는 callback_kwargs 인수로 전달됩니다. 파이프라인 클래스의 ._callback_tensor_inputs 속성에 나열된 변수만 포함할 수 있습니다.
  • max_sequence_length (int, 기본값 512) — prompt에 사용할 최대 시퀀스 길이입니다.
  • upsampling_strength (float, 선택 사항, 기본값 1.0) — 결과를 업샘플링할 때 참조 image 를 변환하는 정도를 나타냅니다. 0과 1 사이여야 합니다.
    1. 생성된 이미지는 시작점으로 사용되며, upsampling_strength 값이 높을수록 더 많은 노이즈가 추가됩니다. 디노이징 단계의 수는 초기에 추가된 노이즈의 양에 따라 결정됩니다. upsampling_strength가 1이면 추가되는 노이즈가 최대가 되며, num_inference_steps에 지정된 전체 반복 횟수만큼 디노이징 프로세스가 실행됩니다. 0이면 업샘플링 단계를 건너뛰고 self.resolution 해상도로 결과를 출력합니다.

반환값

~pipelines.flux.FluxPipelineOutput 또는 tuple

return_dict가 True인 경우 ~pipelines.flux.FluxPipelineOutput, 그렇지 않으면 tuple입니다. tuple을 반환할 경우 첫 번째 요소는 생성된 이미지의 목록입니다.

생성을 위해 VisualCloze 파이프라인을 호출할 때 호출되는 함수입니다.

예:

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

< >

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

매개변수

  • transformer (FluxTransformer2DModel) — 인코딩된 이미지 latents의 노이즈를 제거하기 위한 Conditional Transformer (MMDiT) 아키텍처입니다.
  • scheduler (FlowMatchEulerDiscreteScheduler) — transformer와 함께 사용하여 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러.
  • vae (AutoencoderKL) — 이미지를 잠재 표현으로 인코딩하고 디코딩하는 Variational Auto-Encoder (VAE) 모델.
  • text_encoder (CLIPTextModel) — 구체적으로 clip-vit-large-patch14 변형을 사용하는 CLIP입니다.
  • text_encoder_2 (T5EncoderModel) — 구체적으로 google/t5-v1_1-xxl 변형인 T5입니다.
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 클래스의 토크나이저.
  • tokenizer_2 (T5TokenizerFast) — T5TokenizerFast 클래스의 두 번째 Tokenizer.
  • resolution (int, 선택 사항, 기본값 384) — 쿼리와 컨텍스트 내 예시의 이미지를 연결할 때 각 이미지의 해상도입니다.

시각적 컨텍스트를 활용한 이미지 생성을 위한 VisualCloze 파이프라인. 참고: https://github.com/lzyhha/VisualCloze/tree/main 이 파이프라인은 시각적 인-컨텍스트 예시를 기반으로 이미지를 생성하도록 설계되었습니다.

__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

매개변수

  • task_prompt (str 또는 list[str], 선택 사항) — 작업 의도를 정의하기 위한 프롬프트입니다.
  • content_prompt (str 또는 list[str], 선택) — 생성할 대상 이미지의 콘텐츠나 캡션을 정의하기 위한 프롬프트입니다.
  • image (torch.Tensor, PIL.Image.Image, np.ndarray, list[torch.Tensor], list[PIL.Image.Image] 또는 list[np.ndarray]) — 시작점으로 사용할 이미지 배치의 Image, numpy 배열 또는 텐서를 나타냅니다. numpy 배열과 pytorch 텐서 모두에서 예상 값 범위는 [0, 1]입니다. 텐서 또는 텐서 목록인 경우 예상 shape은 (B, C, H, W) 또는 (C, H, W)여야 합니다. numpy 배열 또는 배열 목록인 경우 예상 shape은 (B, H, W, C) 또는 (H, W, C)여야 합니다.
  • num_inference_steps (int, 선택 사항, 기본값 50) — 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 더 높은 품질의 이미지를 생성하지만, 추론 속도가 느려집니다.
  • sigmas (list[float], 선택 사항) — set_timesteps 메서드에 sigmas 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 시그마입니다. 정의되지 않은 경우, num_inference_steps가 전달될 때의 기본 동작이 사용됩니다.
  • guidance_scale (float, 선택 사항, 기본값 30.0) — Classifier-Free Diffusion Guidance에서 정의한 가이던스 스케일입니다. guidance_scale은 Imagen Paper의 2번 식의 w로 정의됩니다. guidance_scale > 1로 설정하면 가이던스 스케일이 활성화됩니다. 가이던스 스케일이 높을수록 prompt 텍스트와 밀접하게 연결된 이미지를 생성하도록 유도하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다.
  • num_images_per_prompt (int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지의 수입니다.
  • generator (torch.Generator 또는 list[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한 torch generator 하나 또는 목록
  • latents (torch.FloatTensor, 선택 사항) — 이미지 생성의 입력으로 사용할 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents입니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 무작위 generator를 사용하여 샘플링하여 latents 텐서가 생성됩니다.
  • prompt_embeds (torch.FloatTensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • pooled_prompt_embeds (torch.FloatTensor, 선택) — 미리 생성된 풀링된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 풀링된 텍스트 임베딩이 생성됩니다.
  • output_type (str, 선택 사항, 기본값 "pil") — 이미지 생성의 출력 형식입니다. "pil" (PIL: PIL.Image.Image), "np" (np.array) 또는 "pt" (torch.Tensor) 중 하나를 선택합니다.
  • return_dict (bool, 선택 사항, 기본값 True) — 일반 튜플 대신 ~pipelines.flux.FluxPipelineOutput를 반환할지 여부.
  • joint_attention_kwargs (dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의 self.processor에서 정의된 AttentionProcessor로 전달되는 kwargs 사전입니다.
  • callback_on_step_end (Callable, 선택 사항) — 추론 중 각 디노이징 단계의 끝에서 호출되는 함수입니다. 이 함수는 다음 인수를 받아 호출됩니다: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs에는 callback_on_step_end_tensor_inputs로 지정된 모든 텐서 목록이 포함됩니다.
  • callback_on_step_end_tensor_inputs (list, 선택 사항) — callback_on_step_end 함수의 텐서 입력 목록입니다. 목록에 지정된 텐서는 callback_kwargs 인수로 전달됩니다. 파이프라인 클래스의 ._callback_tensor_inputs 속성에 나열된 변수만 포함할 수 있습니다.
  • max_sequence_length (int, 기본값 512) — prompt에 사용할 최대 시퀀스 길이입니다.

반환값

~pipelines.flux.FluxPipelineOutput 또는 tuple

return_dict가 True인 경우 ~pipelines.flux.FluxPipelineOutput, 그렇지 않으면 tuple입니다. tuple을 반환할 경우 첫 번째 요소는 생성된 이미지의 목록입니다.

생성을 위해 VisualCloze 파이프라인을 호출할 때 호출되는 함수입니다.

예:

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

매개변수

  • layout_prompt (str 또는 list[str], 선택 사항) — 태스크에 포함된 인컨텍스트 예시의 수와 이미지의 수를 정의하는 프롬프트입니다.
  • task_prompt (str 또는 list[str], 선택 사항) — 작업 의도를 정의하기 위한 프롬프트입니다.
  • content_prompt (str 또는 list[str], 선택) — 생성할 대상 이미지의 콘텐츠나 캡션을 정의하기 위한 프롬프트입니다.
  • device — (torch.device): torch device
  • num_images_per_prompt (int) — 프롬프트당 생성할 이미지 수
  • prompt_embeds (torch.FloatTensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • pooled_prompt_embeds (torch.FloatTensor, 선택) — 미리 생성된 풀링된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 풀링된 텍스트 임베딩이 생성됩니다.
  • lora_scale (float, 선택 사항) — LoRA 레이어가 로드된 경우 텍스트 인코더의 모든 LoRA 레이어에 적용될 LoRA 스케일입니다.
Update on GitHub