Diffusers documentation

LEDITS++

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

LEDITS++

LoRA

LEDITS++は、Manuel Brack、Felix Friedrich、Katharina Kornmeier、Linoy Tsaban、Patrick Schramowski、Kristian Kersting、Apolinário Passos による LEDITS++: Limitless Image Editing using Text-to-Image Models で提案されました。

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

テキストから画像を生成する拡散モデルは、テキスト入力のみから高忠実度の画像を生成する驚異的な能力により、最近ますます注目を集めています。その後の研究では、これらの能力を実際の画像編集に活用・適用することが目指されています。しかし、既存の画像から画像への手法は、非効率で不正確であり、汎用性にも限界があります。これらの手法は、時間のかかるファインチューニングを必要とするか、入力画像から不必要に大きく逸脱するか、あるいは複数の同時編集に対応していません。これらの問題を解決するために、効率的かつ汎用的で正確なテキストベースの画像操作手法であるLEDITS++を導入します。LEDITS++の新しいインバージョン手法は、チューニングや最適化を必要とせず、わずか数回の拡散ステップで高忠実度の結果を生成します。第二に、私たちの手法は複数の同時編集をサポートし、アーキテクチャに依存しません。第三に、変更を関連する画像領域に限定する新しい暗黙のマスキング手法を使用します。包括的な評価の一部として、新しいベンチマークであるTEdBench++を提案します。私たちの結果は、LEDITS++の能力と、従来の手法に対する改善を示しています。プロジェクトページはhttps://leditsplusplus-project.static.hf.spaceで利用可能です。

LEDITS++に関する追加情報はプロジェクトページで確認でき、デモで試すこともできます。

現在の DPMSolverMultistepScheduler の diffusers 実装には後方互換性の問題があるため、この LEdits++ の実装では完全なインバージョンを保証できなくなりました。 この問題は、実際の使用ケースにおいて目立った影響を及ぼす可能性は低いと考えられます。ただし、完全なインバージョンを保証する代替実装を、専用の GitHub リポジトリ で提供しています。

異なる事前学習済みモデルに基づいた2つの異なるパイプラインを提供しています。

LEditsPPPipelineStableDiffusion

class diffusers.LEditsPPPipelineStableDiffusion

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModelscheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepSchedulersafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilrequires_safety_checker: bool = True )

パラメータ

  • vae (AutoencoderKL) — 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ (VAE) モデル。
  • text_encoder (CLIPTextModel) — 凍結されたテキストエンコーダー。Stable Diffusion は CLIP のテキスト部分、具体的には clip-vit-large-patch14 バリアントを使用します。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer クラスのトークナイザー。
  • unet (UNet2DConditionModel) — エンコードされた画像の潜在変数をノイズ除去するための条件付き U-Net アーキテクチャ。
  • scheduler(DPMSolverMultistepScheduler または DDIMScheduler)— unet と組み合わせて、エンコードされた画像の潜変数(latents)からノイズを除去するために使用するスケジューラです。DPMSolverMultistepScheduler または DDIMScheduler のいずれかになります。それ以外のスケジューラが渡された場合は、自動的に DPMSolverMultistepScheduler に設定されます。
  • safety_checker (StableDiffusionSafetyChecker) — 生成された画像が攻撃的または有害とみなされる可能性を推定する分類モジュールです。 詳細については、モデルカードを参照してください。
  • feature_extractor (CLIPImageProcessor) — 生成された画像から特徴を抽出し、safety_checker の入力として使用するモデルです。

Stable Diffusion を用いた LEDits++ によるテキストベースの画像編集パイプライン。

このモデルは DiffusionPipeline を継承し、StableDiffusionPipeline をベースに構築されています。すべてのパイプラインに実装されている汎用的なメソッド(ダウンロード、保存、特定のデバイスでの実行など)については、スーパークラスのドキュメントを参照してください。

__call__

< >

( negative_prompt: str | list[str] | None = Nonegenerator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueediting_prompt: str | list[str] | None = Noneediting_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonereverse_editing_direction: bool | list[bool] | None = Falseedit_guidance_scale: float | list[float] | None = 5edit_warmup_steps: int | list[int] | None = 0edit_cooldown_steps: int | list[int] | None = Noneedit_threshold: float | list[float] | None = 0.9user_mask: typing.Optional[torch.Tensor] = Nonesem_guidance: list[torch.Tensor] | None = Noneuse_cross_attn_mask: bool = Falseuse_intersect_mask: bool = Trueattn_store_steps: list[int] | None = []store_averaged_over_steps: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneguidance_rescale: float = 0.0clip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']**kwargs ) → LEditsPPDiffusionPipelineOutput or tuple

パラメータ

  • negative_prompt (str または list[str]、省略可) — 画像生成をガイドしないプロンプトです。ガイダンスを使用していない場合は無視されます(guidance_scale が 1 未満の場合は無視されます)。
  • generator (torch.Generator、省略可) — 生成を決定論的にするためのtorch ジェネレーター1つまたはリスト。
  • output_type (str、任意、デフォルトは "pil") — 画像生成の出力形式です。PIL: PIL.Image.Image または np.array から選択します。
  • return_dict (bool、任意、デフォルトはTrue) — プレーンなタプルではなく、LEditsPPDiffusionPipelineOutputを返すかどうかを指定します。
  • editing_prompt (str または list[str]、省略可) — 画像生成をガイドするためのプロンプトです。editing_prompt = None を設定することで、画像が再構築されます。プロンプトのガイダンス方向は、reverse_editing_direction を介して指定する必要があります。
  • editing_prompt_embeds (torch.Tensor>、任意) — 画像生成をガイドするために使用する事前計算済みエンベディング。エンベディングのガイダンス方向は、reverse_editing_directionで指定する必要があります。
  • negative_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなテキスト埋め込み。テキスト入力(プロンプトの重み付け)を簡単に調整するために使用できます。指定されない場合、negative_prompt_embeds は negative_prompt 入力引数から生成されます。
  • reverse_editing_direction (bool または list[bool]、任意、デフォルトは False) — editing_prompt 内の対応するプロンプトを増加させるか減少させるかを指定します。
  • edit_guidance_scale (float または list[float]、任意、デフォルト値は 5) — 画像生成を導くためのガイダンススケールです。リストとして指定する場合、値は editing_prompt と対応する必要があります。edit_guidance_scale は、LEDITS++ Paper の数式 12 の s_e として定義されています。
  • edit_warmup_steps (float または list[float]、任意、デフォルト値は 10) — ガイダンスを適用しない拡散ステップ数(プロンプトごと)。
  • edit_cooldown_steps (float または list[float]、任意、デフォルトは None) — ガイダンスが適用されなくなるまでの拡散ステップ数(プロンプトごと)。
  • edit_threshold (float または list[float]、任意、デフォルト値は 0.9) — ガイダンスのマスクング閾値です。閾値は、変更される画像領域に比例する値である必要があります。 ‘edit_threshold’ は、LEDITS++ Paper の数式 12 の ‘λ’ として定義されています。
  • user_mask (torch.Tensor, 任意) — 編集プロセスをより正確に制御するためにユーザーが指定するマスクです。LEDITS++の暗黙的なマスクがユーザーの希望を満たさない場合に役立ちます。
  • sem_guidance (list[torch.Tensor]、任意) — 生成時に適用する事前生成されたガイダンスベクトルのリストです。リストの長さはnum_inference_stepsと一致する必要があります。
  • use_cross_attn_mask (bool、デフォルトはFalse) — クロスアテンションマスクを使用するかどうか。LEDITS++ 論文の式12の‘M^1’として定義されるクロスアテンションマスクは、use_intersect_maskがtrueに設定されている場合は常に使用されます。
  • use_intersect_mask (bool、デフォルトは True) — マスキング項を、クロスアテンションマスクとノイズ推定から導出されたマスクの交差として計算するかどうかを指定します。クロスアテンションマスクは LEDITS++ 論文 の数式 12 の ‘M^1’、ノイズ推定から導出されたマスクは ‘M^2’ と定義されています。
  • attn_store_steps (list[int]、省略可) — AttentionStore にアテンションマップを保存するステップです。可視化目的でのみ使用されます。
  • store_averaged_over_steps (bool、デフォルトはTrue) — ‘attn_store_steps’のattention mapが、diffusionステップにわたって平均化して保存されるかどうかを指定します。Falseの場合、各ステップのattention mapは個別に保存されます。可視化目的でのみ使用されます。
  • cross_attention_kwargs (dict, 任意) — 指定された場合、self.processor で定義されている AttentionProcessor に渡される kwargs の辞書です。
  • guidance_rescale (float、任意、デフォルト値は 0.0) — Common Diffusion Noise Schedules and Sample Steps are Flawed に記載されている guidance rescale 係数です。zero terminal SNR を使用する場合の露出過多を修正するために、guidance rescale 係数を使用します。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。
  • 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 属性にリストされている変数のみを、このリストに含めることができます。

戻り値

LEditsPPDiffusionPipelineOutput または tuple

LEditsPPDiffusionPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) content, according to the safety_checker`.

編集用の pipeline の呼び出し関数です。invert() メソッドを事前に呼び出す必要があります。編集は、最後に invert された画像に対して常に実行されます。

例:

>>> import torch

>>> from diffusers import LEditsPPPipelineStableDiffusion
>>> from diffusers.utils import load_image

>>> pipe = LEditsPPPipelineStableDiffusion.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe.vae.enable_tiling()
>>> pipe = pipe.to("cuda")

>>> img_url = "https://www.aiml.informatik.tu-darmstadt.de/people/mbrack/cherry_blossom.png"
>>> image = load_image(img_url).resize((512, 512))

>>> _ = pipe.invert(image=image, num_inversion_steps=50, skip=0.1)

>>> edited_image = pipe(
...     editing_prompt=["cherry blossom"], edit_guidance_scale=10.0, edit_threshold=0.75
... ).images[0]

invert

< >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]source_prompt: str = ''source_guidance_scale: float = 3.5num_inversion_steps: int = 30skip: float = 0.15generator: typing.Optional[torch.Generator] = Nonecross_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int | None = Noneheight: int | None = Nonewidth: int | None = Noneresize_mode: str | None = 'default'crops_coords: tuple[int, int, int, int] | None = None ) → LEditsPPInversionPipelineOutput

パラメータ

  • image (PipelineImageInput) — 編集対象の画像の入力です。複数の入力画像を指定する場合は、アスペクト比が同じである必要があります。
  • source_prompt (str、デフォルトは "") — インバージョン中のガイダンスに使用される、入力画像を説明するプロンプトです。source_prompt が "" の場合、ガイダンスは無効になります。
  • source_guidance_scale (float、デフォルト値は3.5) — インバージョン中のガイダンスの強さ。
  • num_inversion_steps (int、デフォルトは30) — 初期のskipステップを除外した後に実行されるインバージョンステップの総数。
  • skip (float、デフォルトは 0.15) — インバージョンおよびその後の生成において無視される初期ステップの割合です。値を下げると、入力画像に対する変化が強くなります。skip は 0 と 1 の間でなければなりません。
  • generator (torch.Generator, 省略可) — 反転を決定論的にするための torch.Generator。
  • cross_attention_kwargs (dict, 任意) — 指定された場合、self.processor で定義されている AttentionProcessor に渡される kwargs の辞書です。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。
  • height (int、任意、デフォルトは None) — 前処理済み画像の高さ。None の場合、get_default_height_width() を使用してデフォルトの高さを取得します。
  • width (int, optional, defaults to None) -- The width in preprocessed. If None, will use get_default_height_width() to get the default width.
  • resize_mode (str, 任意、デフォルトは default) — リサイズモードです。default または fill のいずれかになります。default の場合、指定された幅と高さに収まるように画像をリサイズしますが、元の縦横比が維持されない場合があります。fill の場合、指定された幅と高さに収まるように、縦横比を維持したまま画像をリサイズし、その後、寸法内で画像を中央揃えにし、空いた部分を画像のデータで埋めます。crop の場合、指定された幅と高さに収まるように、縦横比を維持したまま画像をリサイズし、その後、寸法内で画像を中央揃えにし、余分な部分を切り取ります。なお、resize_mode の fill および crop は、PIL 画像のインプットのみサポートされています。
  • crops_coords (list[tuple[int, int, int, int]]、任意、デフォルトはNone) — バッチ内の各画像のクロップ座標です。Noneの場合、画像はクロップされません。

出力には、リサイズされた入力画像と、それに対応するVAE再構成画像が含まれます。

LEDITS++ Paper に記載されている画像反転を行うための pipeline 関数です。スケジューラが DDIMScheduler に設定されている場合、代わりに edit-friendly DPDM で提案された反転が実行されます。

encode_prompt

< >

( devicenum_images_per_promptenable_edit_guidancenegative_prompt = Noneediting_prompt = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneediting_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

パラメータ

  • device — (torch.device): torch デバイス
  • num_images_per_prompt (int) — 1つのプロンプトに対して生成する画像の数
  • enable_edit_guidance (bool) — 編集を実行するか、それとも入力画像を再構築するかどうか
  • negative_prompt (str または list[str]、省略可) — 画像生成をガイドしないプロンプトです。未定義の場合、代わりに negative_prompt_embeds を渡す必要があります。ガイダンスを使用していない場合は無視されます(guidance_scale が 1 未満の場合は無視されます)。
  • editing_prompt (str または list[str]、省略可) — エンコード対象の編集プロンプトです。未定義の場合、代わりに editing_prompt_embeds を渡す必要があります。
  • editing_prompt_embeds (torch.Tensor, 省略可) — 事前に生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを簡単に実行できます。指定されない場合、prompt 引数からテキスト埋め込みが生成されます。
  • negative_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなテキスト埋め込みです。テキスト入力の調整、例えばプロンプトの重み付けなどを簡単に実行できます。指定されない場合、negative_prompt 入力引数から negative_prompt_embeds が生成されます。
  • lora_scale (float, 任意) — LoRA レイヤーが読み込まれている場合、テキストエンコーダーのすべての LoRA レイヤーに適用される LoRA スケールです。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。

プロンプトをテキストエンコーダーの隠れ状態にエンコードします。

LEditsPPPipelineStableDiffusionXL

class diffusers.LEditsPPPipelineStableDiffusionXL

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: UNet2DConditionModelscheduler: diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler | diffusers.schedulers.scheduling_ddim.DDIMSchedulerimage_encoder: CLIPVisionModelWithProjection = Nonefeature_extractor: CLIPImageProcessorPil = Noneforce_zeros_for_empty_prompt: bool = Trueadd_watermarker: bool | None = None )

パラメータ

  • vae (AutoencoderKL) — 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ (VAE) モデル。
  • text_encoder (CLIPTextModel) — 凍結されたテキストエンコーダー。Stable Diffusion XL は CLIP のテキスト部分、具体的には clip-vit-large-patch14 バリアントを使用します。
  • text_encoder_2 (CLIPTextModelWithProjection) — 2番目の凍結されたテキストエンコーダー。Stable Diffusion XL は CLIP のテキストおよびプール部分を使用しており、具体的には laion/CLIP-ViT-bigG-14-laion2B-39B-b160k バリアントです。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer クラスのトークナイザー。
  • tokenizer_2 (CLIPTokenizer) — クラス CLIPTokenizer の2番目の Tokenizer。
  • unet (UNet2DConditionModel) — エンコードされた画像の潜在変数をノイズ除去するための条件付き U-Net アーキテクチャ。
  • scheduler(DPMSolverMultistepScheduler または DDIMScheduler)— unet と組み合わせて、エンコードされた画像の潜変数(latents)からノイズを除去するために使用するスケジューラです。DPMSolverMultistepScheduler または DDIMScheduler のいずれかになります。それ以外のスケジューラが渡された場合は、自動的に DPMSolverMultistepScheduler に設定されます。
  • force_zeros_for_empty_prompt (bool、省略可、デフォルトは "True") — ネガティブプロンプトの埋め込みを常に 0 に設定するかどうか。stabilityai/stable-diffusion-xl-base-1-0 の設定も参照してください。
  • add_watermarker (bool、省略可) — invisible_watermark ライブラリを使用して出力画像にウォーターマークを付与するかどうかを指定します。未定義の場合、パッケージがインストールされていれば True がデフォルトとなり、インストールされていなければウォーターマークは付与されません。

Stable Diffusion XL を用いた LEDits++ によるテキストベースの画像編集パイプライン。

このモデルは DiffusionPipeline を継承し、StableDiffusionXLPipeline をベースに構築されています。すべてのパイプラインに実装されている汎用的なメソッド(ダウンロード、保存、特定のデバイスでの実行など)については、スーパークラスのドキュメントを参照してください。

さらに、pipelineは以下の読み込みメソッドを継承します:

また、以下の保存メソッドもサポートされています:

  • LoRA: loaders.StableDiffusionXLPipeline.save_lora_weights

__call__

< >

( denoising_end: float | None = Nonenegative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneguidance_rescale: float = 0.0crops_coords_top_left: tuple = (0, 0)target_size: tuple[int, int] | None = Noneediting_prompt: str | list[str] | None = Noneediting_prompt_embeddings: typing.Optional[torch.Tensor] = Noneediting_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonereverse_editing_direction: bool | list[bool] | None = Falseedit_guidance_scale: float | list[float] | None = 5edit_warmup_steps: int | list[int] | None = 0edit_cooldown_steps: int | list[int] | None = Noneedit_threshold: float | list[float] | None = 0.9sem_guidance: list[torch.Tensor] | None = Noneuse_cross_attn_mask: bool = Falseuse_intersect_mask: bool = Falseuser_mask: typing.Optional[torch.Tensor] = Noneattn_store_steps: list[int] | None = []store_averaged_over_steps: bool = Trueclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']**kwargs ) → LEditsPPDiffusionPipelineOutput or tuple

パラメータ

  • denoising_end (float, 任意) — 指定された場合、デノイジング全体のどの割合(0.0 から 1.0 の間)まで完了した時点で、意図的に処理を早期に終了させるかを決定します。その結果、スケジューラによって選択された離散タイムステップによって決定されるように、返されるサンプルには依然としてかなりの量のノイズが残ります。denoising_end パラメータは、このパイプラインが [**Refining the Image
  • negative_prompt (str または list[str]、省略可) — 画像生成をガイドしないプロンプトです。未定義の場合、代わりに negative_prompt_embeds を渡す必要があります。ガイダンスを使用していない場合は無視されます(guidance_scale が 1 未満の場合は無視されます)。
  • negative_prompt_2 (str または list[str]、省略可) — tokenizer_2 および text_encoder_2 に送信する、画像生成を導かないためのプロンプトです。未定義の場合、両方のテキストエンコーダーで negative_prompt が使用されます。
  • negative_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなテキスト埋め込みです。テキスト入力の調整、例えばプロンプトの重み付けなどを簡単に実行できます。指定されない場合、negative_prompt 入力引数から negative_prompt_embeds が生成されます。
  • negative_pooled_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなプーリング済みテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、negative_prompt 入力引数からプーリング済み negative_prompt_embeds が生成されます。
  • ip_adapter_image — (PipelineImageInput, 任意): IP Adapter と組み合わせて使用する任意の画像入力です。
  • output_type (str、任意、デフォルトは "pil") — 画像生成の出力形式です。PIL: PIL.Image.Image または np.array から選択します。
  • return_dict (bool、省略可能、デフォルトは True) — ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput を返すかどうか。プレーンなタプルを返すこともできます。
  • cross_attention_kwargs (dict、省略可) — 指定された場合、diffusers.models.attention_processor で定義されている self.processor 配下の AttentionProcessor に渡される kwargs の辞書です。
  • guidance_rescale (float, optional, defaults to 0.7) — Guidance rescale factor proposed by Common Diffusion Noise Schedules and Sample Steps are Flawed guidance_scale is defined as φ in equation 16. of Common Diffusion Noise Schedules and Sample Steps are Flawed. Guidance rescale factor should fix overexposure when using zero terminal SNR.
  • crops_coords_top_left (tuple[int]、任意、デフォルト値は (0, 0)) — crops_coords_top_left は、crops_coords_top_left の位置から下方向に「切り抜かれた」ように見える画像を生成するために使用できます。適切に中央が揃った良好な画像は、通常、crops_coords_top_left を (0, 0) に設定することで得られます。https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。
  • target_size (tuple[int]、任意、デフォルト値は (1024, 1024)) — ほとんどの場合、target_size は生成される画像の希望する高さおよび幅に設定すべきです。指定されない場合、デフォルトで (width, height) が使用されます。https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。
  • editing_prompt (str または list[str]、省略可) — 画像生成をガイドするためのプロンプトです。editing_prompt = None を設定することで、画像が再構築されます。プロンプトのガイダンス方向は、reverse_editing_direction を介して指定する必要があります。
  • editing_prompt_embeddings (torch.Tensor, 任意) — 事前に生成された編集テキストの埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどに簡単に使用できます。 指定されない場合、editing_prompt 入力引数から editing_prompt_embeddings が生成されます。
  • editing_pooled_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたプールの編集テキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを簡単に実行できます。指定されない場合、editing_prompt 入力引数から editing_prompt_embeddings が生成されます。
  • reverse_editing_direction (bool または list[bool]、任意、デフォルトは False) — editing_prompt 内の対応するプロンプトを増加させるか減少させるかを指定します。
  • edit_guidance_scale (float または list[float]、任意、デフォルト値は 5) — 画像生成を導くためのガイダンススケールです。リストとして指定する場合、値は editing_prompt と対応する必要があります。edit_guidance_scale は、LEDITS++ Paper の数式 12 の s_e として定義されています。
  • edit_warmup_steps (float または list[float]、任意、デフォルト値は 10)— ガイダンスを適用しない拡散ステップの数(プロンプトごと)です。
  • edit_cooldown_steps (float または list[float]、任意、デフォルトは None) — ガイダンスを適用しなくなるまでの拡散ステップ数(プロンプトごと)。
  • edit_threshold (float または list[float]、任意、デフォルト値は 0.9) — ガイダンスのマスクング閾値です。閾値は、変更される画像領域に比例する値である必要があります。 ‘edit_threshold’ は、LEDITS++ Paper の数式 12 の ‘λ’ として定義されています。
  • sem_guidance (list[torch.Tensor]、任意) — 生成時に適用する事前生成されたガイダンスベクトルのリストです。リストの長さはnum_inference_stepsと一致する必要があります。
  • use_cross_attn_mask — クロスアテンションマスクを使用するかどうか。LEDITS++ 論文の式12の ‘M^1’ で定義されるクロスアテンションマスクは、use_intersect_mask が true に設定されている場合、常に使用されます。
  • use_intersect_mask — マスキング項を、クロスアテンションマスクとノイズ推定から導出されたマスクの交差として計算するかどうかを指定します。クロスアテンションマスクは LEDITS++ 論文 の式 12 の ‘M^1’ として、ノイズ推定から導出されたマスクは ‘M^2’ として定義されています。
  • user_mask — 編集プロセスをより正確に制御するために、ユーザーが指定するマスクです。LEDITS++の暗黙的なマスクがユーザーの希望に合わない場合に役立ちます。
  • attn_store_steps — AttentionStore にアテンションマップを保存するステップ数です。可視化目的でのみ使用されます。
  • store_averaged_over_steps — 「attn_store_steps」のアテンションマップを、拡散ステップにわたって平均化して保存するかどうかを指定します。False の場合、各ステップのアテンションマップは個別に保存されます。可視化目的でのみ使用されます。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。
  • 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 属性にリストされている変数のみを、このリストに含めることができます。

戻り値

LEditsPPDiffusionPipelineOutput または tuple

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

編集用の pipeline の呼び出し関数です。invert() メソッドを事前に呼び出す必要があります。編集は、最後に invert された画像に対して常に実行されます。

例:

>>> import torch

>>> from diffusers import LEditsPPPipelineStableDiffusionXL
>>> from diffusers.utils import load_image

>>> pipe = LEditsPPPipelineStableDiffusionXL.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe.vae.enable_tiling()
>>> pipe = pipe.to("cuda")

>>> img_url = "https://www.aiml.informatik.tu-darmstadt.de/people/mbrack/tennis.jpg"
>>> image = load_image(img_url).resize((1024, 1024))

>>> _ = pipe.invert(image=image, num_inversion_steps=50, skip=0.2)

>>> edited_image = pipe(
...     editing_prompt=["tennis ball", "tomato"],
...     reverse_editing_direction=[True, False],
...     edit_guidance_scale=[5.0, 10.0],
...     edit_threshold=[0.9, 0.85],
... ).images[0]

invert

< >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]source_prompt: str = ''source_guidance_scale = 3.5negative_prompt: str = Nonenegative_prompt_2: str = Nonenum_inversion_steps: int = 50skip: float = 0.15generator: typing.Optional[torch.Generator] = Nonecrops_coords_top_left: tuple = (0, 0)num_zero_noise_steps: int = 3cross_attention_kwargs: dict[str, typing.Any] | None = Noneheight: int | None = Nonewidth: int | None = Noneresize_mode: str | None = 'default'crops_coords: tuple[int, int, int, int] | None = None ) → LEditsPPInversionPipelineOutput

パラメータ

  • image (PipelineImageInput) — 編集対象の画像の入力です。複数の入力画像を指定する場合は、アスペクト比が同じである必要があります。
  • source_prompt (str、デフォルトは "") — インバージョン中のガイダンスに使用される、入力画像を説明するプロンプトです。source_prompt が "" の場合、ガイダンスは無効になります。
  • source_guidance_scale (float、デフォルト値は3.5) — インバージョン中のガイダンスの強さ。
  • negative_prompt (str または list[str]、省略可) — 画像生成をガイドしないプロンプトです。未定義の場合、代わりに negative_prompt_embeds を渡す必要があります。ガイダンスを使用していない場合は無視されます(guidance_scale が 1 未満の場合は無視されます)。
  • negative_prompt_2 (str または list[str]、省略可) — tokenizer_2 および text_encoder_2 に送信する、画像生成を導かないためのプロンプトです。未定義の場合、両方のテキストエンコーダーで negative_prompt が使用されます。
  • num_inversion_steps (int、デフォルトは 50) — 初期の skip ステップを除外した後に実行されるインバージョンステップの総数。
  • skip (float、デフォルトは 0.15) — インバージョンおよびその後の生成において無視される初期ステップの割合です。値を下げると、入力画像に対する変化が強くなります。skip は 0 と 1 の間でなければなりません。
  • generator (torch.Generator, 省略可) — 反転を決定論的にするための torch.Generator。
  • crops_coords_top_left (tuple[int]、任意、デフォルト値は (0, 0)) — crops_coords_top_left は、crops_coords_top_left の位置から下方向に「切り抜かれた」ように見える画像を生成するために使用できます。適切に中央が揃った良好な画像は、通常、crops_coords_top_left を (0, 0) に設定することで得られます。https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。
  • num_zero_noise_steps (int、デフォルト値は3) — 現在の画像を再ノイズ化しない、最後の拡散ステップの数を指定します。ステップがゼロに設定されていない場合、DPMSolverMultistepSchedulerと組み合わせた SD-XL ではノイズアーティファクトが発生します。
  • cross_attention_kwargs (dict、省略可) — 指定された場合、diffusers.models.attention_processor で定義されている self.processor 配下の AttentionProcessor に渡される kwargs の辞書です。

出力には、リサイズされた入力画像と、それに対応するVAE再構成画像が含まれます。

LEDITS++ Paper に記載されている画像反転を行うための pipeline 関数です。スケジューラが DDIMScheduler に設定されている場合、代わりに edit-friendly DPDM で提案された反転が実行されます。

encode_prompt

< >

( device: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1negative_prompt: str | None = Nonenegative_prompt_2: str | None = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = Noneenable_edit_guidance: bool = Trueediting_prompt: str | None = Noneediting_prompt_embeds: typing.Optional[torch.Tensor] = Noneediting_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None )

パラメータ

  • device — (torch.device): torch デバイス
  • num_images_per_prompt (int) — 1つのプロンプトに対して生成する画像の数
  • negative_prompt (str または list[str]、省略可) — 画像生成をガイドしないプロンプトです。未定義の場合、代わりに negative_prompt_embeds を渡す必要があります。
  • negative_prompt_2 (str または list[str]、省略可) — tokenizer_2 および text_encoder_2 に送信する、画像生成を導かないためのプロンプトです。未定義の場合、両方のテキストエンコーダーで negative_prompt が使用されます。
  • negative_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなテキスト埋め込みです。テキスト入力の調整、例えばプロンプトの重み付けなどを簡単に実行できます。指定されない場合、negative_prompt 入力引数から negative_prompt_embeds が生成されます。
  • negative_pooled_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなプーリング済みテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、negative_prompt 入力引数からプーリング済み negative_prompt_embeds が生成されます。
  • lora_scale (float, 省略可) — LoRA レイヤーが読み込まれている場合、テキストエンコーダーのすべての LoRA レイヤーに適用される LoRA スケールです。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。
  • enable_edit_guidance (bool) — 編集プロンプトへのガイダンスを有効にするかどうか。
  • editing_prompt (str または list[str]、省略可) — エンコード対象の編集プロンプトです。未定義かつ ‘enable_edit_guidance’ が True の場合、代わりに editing_prompt_embeds を渡す必要があります。
  • editing_prompt_embeds (torch.Tensor, 任意) — 事前に生成された編集テキストの埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを簡単に実行できます。 指定されず、かつ ‘enable_edit_guidance’ が True の場合、editing_prompt 入力引数から editing_prompt_embeds が生成されます。
  • editing_pooled_prompt_embeds (torch.Tensor, 任意) — 事前に生成された編集用のプーリング済みテキスト埋め込み。テキスト入力を簡単に調整するために使用できます。例えば、プロンプトの重み付けなどです。指定されない場合、editing_prompt 入力引数からプーリングされた editing_pooled_prompt_embeds が生成されます。

プロンプトをテキストエンコーダーの隠れ状態にエンコードします。

get_guidance_scale_embedding

< >

( w: Tensorembedding_dim: int = 512dtype: dtype = torch.float32 ) → torch.Tensor

パラメータ

  • w (torch.Tensor) — 指定されたガイダンススケールで埋め込みベクトルを生成し、タイムステップ埋め込みを後で強化するために使用します。
  • embedding_dim (int, 任意、デフォルトは 512) — 生成する埋め込みの次元数。
  • dtype (torch.dtype、任意、デフォルトは torch.float32) — 生成される埋め込みのデータ型です。

戻り値

torch.Tensor

(len(w), embedding_dim) の形状を持つ埋め込みベクトル。

https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 を参照してください。

LEditsPPDiffusionPipelineOutput

class diffusers.pipelines.LEditsPPDiffusionPipelineOutput

< >

( images: list[PIL.Image.Image] | numpy.ndarraynsfw_content_detected: list[bool] | None )

パラメータ

  • images (list[PIL.Image.Image] または np.ndarray) — batch_size 個のノイズ除去済み PIL 画像のリスト、または形状が (batch_size, height, width, num_channels) の NumPy 配列。
  • nsfw_content_detected (list[bool]) — 対応する生成画像に「不適切なコンテンツ」(nsfw) が含まれるかどうかを示すリスト。安全チェックを実行できなかった場合は None。

LEdits++ Diffusion パイプライン用の出力クラスです。

LEditsPPInversionPipelineOutput

class diffusers.pipelines.LEditsPPInversionPipelineOutput

< >

( images: list[PIL.Image.Image] | numpy.ndarrayvae_reconstruction_images: list[PIL.Image.Image] | numpy.ndarray )

パラメータ

  • input_images (list[PIL.Image.Image] または np.ndarray) — 長さ batch_size の PIL 画像のリスト、または形状 (batch_size, height, width, num_channels) の NumPy 配列として、切り出しとリサイズ済みの入力画像のリスト。
  • vae_reconstruction_images (list[PIL.Image.Image] または np.ndarray) — batch_size 個の PIL 画像からなる、すべての入力画像の VAE 再構築のリスト、または形状が (batch_size, height, width, num_channels) の NumPy 配列。

LEdits++ Diffusion パイプライン用の出力クラスです。

Update on GitHub