#
# Apache License, Version 2.0（「ライセンス」）の下でライセンスされています。
# このファイルは、ライセンスに準拠した場合にのみ使用できます。
# ライセンスのコピーは以下から入手できます
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 適用される法律で要求される場合、または書面による合意がある場合を除き、ソフトウェア
# ライセンスに基づき配布される本ソフトウェアは、「現状のまま」
# 明示的または黙示的を問わず、いかなる種類の保証や条件も付随しません。
# 権限を管理する特定の言語については、ライセンスを参照してください。
# ライセンスの下での制限事項。
-->

# VisualCloze

[VisualCloze: A Universal Image Generation Framework via Visual In-Context Learning](https://huggingface.co/papers/2504.07960) は、インコンテキスト学習に基づく革新的な汎用画像生成フレームワークであり、以下の主要な機能を提供します。
1. 各種ドメイン内タスクへのサポート
2. インコンテキスト学習による未見タスクへの汎化
3. 複数のタスクを1つのステップに統合し、ターゲット画像と中間結果の両方を生成します
4. ターゲット画像から逆推定条件をサポート

## 概要

論文の抄録は以下の通りです：

*拡散モデルにおける最近の進歩により、さまざまな画像生成タスクが大幅に向上しています。しかし、現在の主流のアプローチは依然としてタスク固有のモデル構築に焦点を当てており、多様なニーズに対応する際の効率が限定的です。汎用モデルはこの限界に対処しようとしていますが、汎用可能なタスク指示、適切なタスク分布、統合的なアーキテクチャ設計といった重要な課題に直面しています。これらの課題に対処するため、我々は汎用画像生成フレームワークであるVisualClozeを提案します。VisualClozeは、ドメイン内の幅広いタスク、未見タスクへの汎化、複数タスクの未見統合、および逆方向生成をサポートします。既存の方法は言語ベースのタスク指示に依存しており、タスクの曖昧さや汎化性能の弱さにつながるため、我々は視覚的なインコンテキスト学習を統合し、モデルが視覚的なデモからタスクを識別できるようにしました。一方、視覚的タスク分布の本質的な疎性により、タスク間の移転可能な知識の学習が阻害されています。このため、我々はグラフ構造のデータセットGraph200Kを導入し、さまざまな相互関連するタスクを確立することで、タスク密度と移転可能な知識を強化しました。さらに、我々の統合画像生成の定式化が画像インフィルリングと一貫した目的を共有していることが判明し、アーキテクチャを変更せずに事前学習済みインフィルリングモデルの強力な生成事前知識を活用できるようになりました。コード、データセット、モデルは https://visualcloze.github.io で利用可能です。*

## 推論

### モデルの読み込み

VisualCloze は 2 段階のカスケードパイプラインであり、`VisualClozeGenerationPipeline` と `VisualClozeUpsamplingPipeline` を含みます。
- `VisualClozeGenerationPipeline`では、画像をグリッドレイアウトに連結する前に、各画像をダウンサンプリングして、解像度が過度に高くなることを回避します。VisualClozeは、diffusersに適した2つのモデル、[VisualClozePipeline-384](https://huggingface.co/VisualCloze/VisualClozePipeline-384)と[VisualClozePipeline-512](https://huggingface.co/VisualCloze/VisualClozePipeline-384)をリリースしており、それぞれ画像を384および512の解像度にダウンサンプリングします。
- `VisualClozeUpsamplingPipeline` は [SDEdit](https://huggingface.co/papers/2108.01073) を使用して、高解像度画像の合成を可能にします。

`VisualClozePipeline` は、両方のステージを統合して便利なエンドツーエンドのサンプリングをサポートするとともに、必要に応じて各パイプラインを独立して利用できるようにしています。

### 入力仕様

#### タスクとコンテンツのプロンプト
- タスクプロンプト: 生成タスクの意図を説明する必要があります
- Content prompt: 対象画像の任意の説明またはキャプション
- コンテンツプロンプトが不要な場合は、`None`を渡します。
- バッチ推論を行う場合は、`List[str|None]` を渡します。

#### 画像入力形式
- 形式: `List[List[Image|None]]`
- 構造:
  - 最後の行を除くすべての行は、インコンテキストの例を表します
  - 最後の行は現在のクエリを表しています（ターゲット画像は`None`に設定されています）。
- バッチ推論を行う場合は、`List[List[List[Image|None]]]` を渡します。

#### 解像度制御
- デフォルトの動作:
  - 最初の段階での初期生成：${pipe.resolution}^2$の領域
  - 2段階目のアップサンプリング: 3倍の係数
- カスタム解像度: `upsampling_height` と `upsampling_width` パラメータを調整して設定します

### 例

幅広いタスクを網羅した包括的な例については、[オンラインデモ](https://huggingface.co/spaces/VisualCloze/VisualCloze)および[GitHubリポジトリ](https://github.com/lzyhha/VisualCloze)を参照してください。以下に、マスクから画像への変換、エッジ検出、被写体駆動型生成の3つのケースにおけるシンプルな例を示します。

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

#### エッジ検出の例

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

#### サブジェクト駆動型生成の例

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

#### 各パイプラインを独立して利用します 

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

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_combined.py#L89)

**パラメータ:**

transformer ([FluxTransformer2DModel](/docs/diffusers/v0.43.0/ja/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : エンコードされた画像潜在変数をノイズ除去するための条件付き Transformer (MMDiT) アーキテクチャ。

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/ja/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ（VAE）モデル。

text_encoder (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)、具体的には [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)、具体的には [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) バリアントです。

tokenizer (`CLIPTokenizer`) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) の Tokenizer。

tokenizer_2 (`T5TokenizerFast`) : クラス [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) の2番目の Tokenizer。

resolution (`int`、*optional*、デフォルトは 384) : クエリとインコンテキスト例の画像を連結する際の、各画像の解像度。

視覚コンテキストを用いた画像生成のためのVisualClozeパイプライン。参考: https://github.com/lzyhha/VisualCloze/tree/main。このパイプラインは、視覚的なインコンテキスト例に基づいて画像を生成するように設計されています。

#### __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[str] = ['latents'], max_sequence_length: int = 512, upsampling_strength: float = 1.0)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_combined.py#L252)

**パラメータ:**

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]` です。テンソルまたはテンソルのリストの場合、想定される形状は `(B, C, H, W)` または `(C, H, W)` です。numpy 配列または配列のリストの場合、想定される形状は `(B, H, W, C)` または `(H, W, C)` です。

upsampling_height (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : SDEdit によるアップサンプリング後の生成画像（すなわち出力画像）のピクセル単位の縦幅です。デフォルトでは、画像は 3 倍の係数でアップサンプリングされ、ベースの解像度はパイプラインの解像度パラメータによって決定されます。`upsampling_height` または `upsampling_width` のいずれか一方のみが指定された場合、もう一方はアスペクト比に基づいて自動的に設定されます。

upsampling_width (`int`、*optional*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : SDEdit によるアップサンプリング後の生成画像（すなわち出力画像）のピクセル単位の幅です。デフォルトでは、画像は 3 倍の係数でアップサンプリングされ、ベースの解像度はパイプラインの解像度パラメータによって決定されます。`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](https://huggingface.co/papers/2207.12598)で定義されているガイダンススケールです。`guidance_scale` は、[Imagen Paper](https://huggingface.co/papers/2205.11487)の式 2 の `w` として定義されています。`guidance_scale > 1` を設定することでガイダンススケールが有効になります。ガイダンススケールを高くすると、`prompt` のテキストと密接に関連する画像の生成が促されますが、通常は画像の品質が低下する傾向があります。

num_images_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。

generator (`torch.Generator` または `list[torch.Generator]`、*任意*) : 生成を決定論的にするための [torch ジェネレーター](https://pytorch.org/docs/stable/generated/torch.Generator.html) 1 つまたはそのリスト。

latents (`torch.FloatTensor`, *任意*) : 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイズ付き潜在変数（latents）。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム`generator`を使用してサンプリングを行い、潜在変数テンソルが生成されます。

prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。

pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。

output_type (`str`、*任意*、デフォルトは `"pil"`) : 生成画像の出力形式。[PIL](https://pillow.readthedocs.io/en/stable/)（`PIL.Image.Image`）または `np.array` から選択します。

return_dict (`bool`、*任意*、デフォルトは`True`) : 通常のタプルではなく`~pipelines.flux.FluxPipelineOutput`を返すかどうか。

joint_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `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 の間の値である必要があります。生成された画像が起点として使用され、`upsampling_strength` の値が大きいほど、より多くのノイズが追加されます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。`upsampling_strength` が 1 の場合、追加されるノイズは最大となり、`num_inference_steps` で指定された全イテレーション数にわたってデノイジングプロセスが実行されます。0 の場合、アップサンプリングのステップがスキップされ、`self.resolution` の解像度で結果が出力されます。

**戻り値:** `~pipelines.flux.FluxPipelineOutput` または `tuple`

`return_dict` が True の場合は `~pipelines.flux.FluxPipelineOutput`、それ以外の場合は `tuple` を返します。tuple を返す場合、最初の要素は生成された画像のリストです。

VisualCloze パイプラインを呼び出して生成を行う際に実行される関数。

例:
```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)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py#L118)

**パラメータ:**

transformer ([FluxTransformer2DModel](/docs/diffusers/v0.43.0/ja/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : エンコードされた画像潜在変数をノイズ除去するための条件付き Transformer (MMDiT) アーキテクチャ。

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/ja/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ（VAE）モデル。

text_encoder (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)、具体的には [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)、具体的には [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) バリアントです。

tokenizer (`CLIPTokenizer`) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) の Tokenizer。

tokenizer_2 (`T5TokenizerFast`) : クラス [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) の2番目の Tokenizer。

resolution (`int`、*optional*、デフォルトは 384) : クエリとインコンテキスト例の画像を連結する際の、各画像の解像度。

視覚コンテキストを用いた画像生成のためのVisualClozeパイプライン。参考: https://github.com/lzyhha/VisualCloze/tree/main このパイプラインは、視覚的なインコンテキスト例に基づいて画像を生成するように設計されています。

#### __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[str] = ['latents'], max_sequence_length: int = 512)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py#L659)

**パラメータ:**

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]` です。テンソルまたはテンソルのリストの場合、想定される形状は `(B, C, H, W)` または `(C, H, W)` です。numpy 配列または配列のリストの場合、想定される形状は `(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](https://huggingface.co/papers/2207.12598)で定義されているガイダンススケールです。`guidance_scale` は、[Imagen Paper](https://huggingface.co/papers/2205.11487)の式 2 の `w` として定義されています。`guidance_scale > 1` を設定することでガイダンススケールが有効になります。ガイダンススケールを高くすると、`prompt` のテキストと密接に関連する画像の生成が促されますが、通常は画像の品質が低下する傾向があります。

num_images_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。

generator (`torch.Generator` または `list[torch.Generator]`、*任意*) : 生成を決定論的にするための [torch ジェネレーター](https://pytorch.org/docs/stable/generated/torch.Generator.html) 1 つまたはそのリスト。

latents (`torch.FloatTensor`, *任意*) : 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイズ付き潜在変数（latents）。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム`generator`を使用してサンプリングを行い、潜在変数テンソルが生成されます。

prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。

pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。

output_type (`str`、*任意*、デフォルトは `"pil"`) : 生成画像の出力形式。`"pil"` ([PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image`)、`"np"` (`np.array`)、または `"pt"` (`torch.Tensor`) から選択します。

return_dict (`bool`、*任意*、デフォルトは`True`) : 通常のタプルではなく`~pipelines.flux.FluxPipelineOutput`を返すかどうか。

joint_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `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 パイプラインを呼び出して生成を行う際に実行される関数。

例:
```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)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py#L292)

**パラメータ:**

layout_prompt (`str` または `list[str]`、*省略可能*) : タスクに関与するインコンテキスト例の数と画像の数を定義するためのプロンプトまたはプロンプトのリスト。

task_prompt (`str` または `list[str]`、*省略可能*) : タスクの意図を定義するためのプロンプトまたはプロンプトのリスト。

content_prompt (`str` または `list[str]`、*任意*) : 生成対象の画像の内容やキャプションを定義するためのプロンプト、またはプロンプトのリスト。

device : (`torch.device`): torch デバイス

num_images_per_prompt (`int`) : プロンプトごとに生成すべき画像の数

prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。

pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。

lora_scale (`float`、*任意*) : LoRAレイヤーが読み込まれている場合、テキストエンコーダーのすべてのLoRAレイヤーに適用されるLoRAスケールです。

