Diffusers documentation
VisualCloze
VisualCloze
VisualCloze: A Universal Image Generation Framework via Visual In-Context Learning は、インコンテキスト学習に基づく革新的な汎用画像生成フレームワークであり、以下の主要な機能を提供します。
- 各種ドメイン内タスクへのサポート
- インコンテキスト学習による未見タスクへの汎化
- 複数のタスクを1つのステップに統合し、ターゲット画像と中間結果の両方を生成します
- ターゲット画像から逆推定条件をサポート
概要
論文の抄録は以下の通りです:
拡散モデルにおける最近の進歩により、さまざまな画像生成タスクが大幅に向上しています。しかし、現在の主流のアプローチは依然としてタスク固有のモデル構築に焦点を当てており、多様なニーズに対応する際の効率が限定的です。汎用モデルはこの限界に対処しようとしていますが、汎用可能なタスク指示、適切なタスク分布、統合的なアーキテクチャ設計といった重要な課題に直面しています。これらの課題に対処するため、私たちは汎用画像生成フレームワークであるVisualClozeを提案します。VisualClozeは、ドメイン内の幅広いタスク、未見タスクへの汎化、複数タスクの未見統合、および逆方向生成をサポートします。既存の方法は言語ベースのタスク指示に依存しており、タスクの曖昧さや汎化性能の弱さにつながるため、私たちは視覚的なインコンテキスト学習を統合し、モデルが視覚的なデモからタスクを識別できるようにしました。一方、視覚的タスク分布の本質的な疎性により、タスク間の移転可能な知識の学習が阻害されています。このため、私たちはGraph200Kを導入しました。これはグラフ構造のデータセットであり、さまざまな相互関連するタスクを確立することで、タスク密度と移転可能な知識を強化します。さらに、私たちの統合画像生成の定式化が画像インフィルリングと一貫した目的を共有していることが判明し、アーキテクチャを変更せずに事前学習済みインフィルリングモデルの強力な生成事前知識を活用できるようになりました。コード、データセット、モデルはhttps://visualcloze.github.ioで入手できます。
推論
モデルの読み込み
VisualCloze は 2 段階のカスケードパイプラインであり、VisualClozeGenerationPipeline と VisualClozeUpsamplingPipeline を含みます。
VisualClozeGenerationPipelineでは、画像をグリッドレイアウトに連結する前に、各画像をダウンサンプリングして、解像度が過度に高くなることを回避します。VisualClozeは、diffusersに適した2つのモデル、VisualClozePipeline-384とVisualClozePipeline-512をリリースしており、これらはそれぞれ画像を384および512の解像度にダウンサンプリングします。VisualClozeUpsamplingPipelineは SDEdit を使用して、高解像度画像の合成を可能にします。
VisualClozePipeline は、両方のステージを統合して便利なエンドツーエンドのサンプリングをサポートするとともに、必要に応じて各パイプラインを独立して利用できるようにしています。
入力仕様
タスクとコンテンツのプロンプト
- タスクプロンプト: 生成タスクの意図を説明する必要があります
- Content prompt: 対象画像の任意の説明またはキャプション
- コンテンツプロンプトが不要な場合は、
Noneを渡します。 - バッチ推論を行う場合は、
List[str|None]を渡します。
画像入力形式
- 形式:
List[List[Image|None]] - 構造:
- 最後の行を除くすべての行は、インコンテキストの例を表します
- 最後の行は現在のクエリを表しています(ターゲット画像は
Noneに設定されています)。
- バッチ推論を行う場合は、
List[List[List[Image|None]]]を渡します。
解像度制御
- デフォルトの動作:
- 第1段階の初期生成: 領域
- 2段階目のアップサンプリング: 3倍の係数
- カスタム解像度:
upsampling_heightとupsampling_widthパラメータを調整して設定します
例
幅広いタスクを網羅した包括的な例については、オンラインデモおよびGitHubリポジトリを参照してください。以下に、マスクから画像への変換、エッジ検出、被写体駆動型生成の3つのケースにおけるシンプルな例を示します。
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
class diffusers.VisualClozePipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizertext_encoder_2: T5EncoderModeltokenizer_2: T5Tokenizertransformer: FluxTransformer2DModelresolution: int = 384 )
パラメータ
- transformer (FluxTransformer2DModel) — エンコードされた画像の潜在変数からノイズを除去するための、条件付き Transformer (MMDiT) アーキテクチャ。
- scheduler (FlowMatchEulerDiscreteScheduler) —
transformerと組み合わせて、エンコードされた画像の潜在変数からノイズを除去するために使用するスケジューラ。 - vae (AutoencoderKL) — 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ (VAE) モデル。
- text_encoder (
CLIPTextModel) — CLIP、具体的には clip-vit-large-patch14 バリアントです。 - text_encoder_2 (
T5EncoderModel) — T5、具体的には google/t5-v1_1-xxl バリアントです。 - tokenizer (
CLIPTokenizer) — CLIPTokenizer クラスのトークナイザー。 - tokenizer_2 (
T5TokenizerFast) — クラス T5TokenizerFast の2番目の Tokenizer。 - resolution (
int、省略可能、デフォルトは 384) — クエリとインコンテキスト例の画像を連結する際の、各画像の解像度です。
視覚コンテキストを用いた画像生成のためのVisualClozeパイプライン。参考文献: https://github.com/lzyhha/VisualCloze/tree/main。このパイプラインは、視覚的なインコンテキスト例に基づいて画像を生成するように設計されています。
__call__
< source >( 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[str] = ['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]です。テンソルまたはテンソルのリストの場合、想定される形状は(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 倍の係数でアップサンプリングされ、ベースの解像度はパイプラインの 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 ジェネレーター1つまたはリスト。 - latents (
torch.FloatTensor, 任意) — 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイジーな潜在変数です。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムgeneratorを使用してサンプリングを行い、潜在変数テンソルが生成されます。 - 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 の間の値でなければなりません。- 生成された画像が起点として使用され、
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
class diffusers.VisualClozeGenerationPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizertext_encoder_2: T5EncoderModeltokenizer_2: T5Tokenizertransformer: FluxTransformer2DModelresolution: int = 384 )
パラメータ
- transformer (FluxTransformer2DModel) — エンコードされた画像の潜在変数からノイズを除去するための、条件付き Transformer (MMDiT) アーキテクチャ。
- scheduler (FlowMatchEulerDiscreteScheduler) —
transformerと組み合わせて、エンコードされた画像の潜在変数からノイズを除去するために使用するスケジューラ。 - vae (AutoencoderKL) — 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ (VAE) モデル。
- text_encoder (
CLIPTextModel) — CLIP、具体的には clip-vit-large-patch14 バリアントです。 - text_encoder_2 (
T5EncoderModel) — T5、具体的には google/t5-v1_1-xxl バリアントです。 - tokenizer (
CLIPTokenizer) — CLIPTokenizer クラスのトークナイザー。 - tokenizer_2 (
T5TokenizerFast) — クラス T5TokenizerFast の2番目の Tokenizer。 - resolution (
int、省略可能、デフォルトは 384) — クエリとインコンテキスト例の画像を連結する際の、各画像の解像度です。
視覚コンテキストを用いた画像生成のためのVisualClozeパイプライン。参考: https://github.com/lzyhha/VisualCloze/tree/main このパイプラインは、視覚的なインコンテキスト例に基づいて画像を生成するように設計されています。
__call__
< source >( 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[str] = ['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]です。テンソルまたはテンソルのリストの場合、想定される形状は(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 で定義されているガイダンススケールです。guidance_scaleは、Imagen Paper の数式 2 のwとして定義されています。guidance_scale > 1を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、promptのテキストと密接に関連した画像の生成が促されますが、通常は画像の品質が低下する傾向があります。 - num_images_per_prompt (
int、任意、デフォルトは 1) — プロンプトごとに生成する画像の数。 - generator (
torch.Generatorまたはlist[torch.Generator]、省略可) — 生成を決定論的にするためのtorch ジェネレーター1つまたはリスト。 - latents (
torch.FloatTensor, 任意) — 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイジーな潜在変数です。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムgeneratorを使用してサンプリングを行い、潜在変数テンソルが生成されます。 - 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
< source >( 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 デバイス - num_images_per_prompt (
int) — 1つのプロンプトに対して生成する画像の数 - prompt_embeds (
torch.FloatTensor, 任意) — 事前に生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt入力引数からテキスト埋め込みが生成されます。 - pooled_prompt_embeds (
torch.FloatTensor, 任意) — 事前に生成されたプールのテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどに簡単に使用できます。 指定されない場合、prompt入力引数からプールのテキスト埋め込みが生成されます。 - lora_scale (
float, 省略可) — LoRA レイヤーが読み込まれている場合、テキストエンコーダーのすべての LoRA レイヤーに適用される LoRA スケールです。