Diffusers documentation
LEDITS++
LEDITS++
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で利用可能です。
現在の DPMSolverMultistepScheduler の diffusers 実装には後方互換性の問題があるため、この LEdits++ の実装では完全なインバージョンを保証できなくなりました。 この問題は、実際の使用ケースにおいて目立った影響を及ぼす可能性は低いと考えられます。ただし、完全なインバージョンを保証する代替実装を、専用の GitHub リポジトリ で提供しています。
異なる事前学習済みモデルに基づいた2つの異なるパイプラインを提供しています。
LEditsPPPipelineStableDiffusion
class diffusers.LEditsPPPipelineStableDiffusion
< source >( 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__
< source >( 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
< source >( 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 toNone) -- The width in preprocessed. IfNone, 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
< source >( 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
< source >( 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: LEditsPPPipelineStableDiffusionXL.load_lora_weights()
- チェックポイント: loaders.FromSingleFileMixin.from_single_file()
また、以下の保存メソッドもサポートされています:
- LoRA:
loaders.StableDiffusionXLPipeline.save_lora_weights
__call__
< source >( 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 Flawedguidance_scaleis 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
< source >( 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
< source >( 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
< source >( w: Tensorembedding_dim: int = 512dtype: dtype = torch.float32 ) → torch.Tensor
LEditsPPDiffusionPipelineOutput
class diffusers.pipelines.LEditsPPDiffusionPipelineOutput
< source >( images: list[PIL.Image.Image] | numpy.ndarraynsfw_content_detected: list[bool] | None )
LEdits++ Diffusion パイプライン用の出力クラスです。
LEditsPPInversionPipelineOutput
class diffusers.pipelines.LEditsPPInversionPipelineOutput
< source >( 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 パイプライン用の出力クラスです。