Diffusers documentation

InstructPix2Pix

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

InstructPix2Pix

LoRA

InstructPix2Pix: Learning to Follow Image Editing Instructionsは、Tim Brooks、Aleksander Holynski、Alexei A. Efros によるものです。

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

人間からの指示に基づいて画像を編集する手法を提案します。入力画像と、モデルに何をすべきかを伝える書面による指示が与えられた場合、当社のモデルはこれらの指示に従って画像を編集します。この問題の学習データを得るために、2つの大規模事前学習モデル、すなわち言語モデル(GPT-3)とテキストから画像を生成するモデル(Stable Diffusion)の知識を組み合わせ、画像編集の例からなる大規模なデータセットを生成しました。条件付き拡散モデルであるInstructPix2Pixは、この生成データで学習され、推論時には実際の画像やユーザーが作成した指示にも一般化します。編集をフォワードパスで実行し、例ごとのファインチューニングやインバージョンを必要としないため、当社のモデルは数秒で画像を編集できます。多様な入力画像と書面による指示に対して、説得力のある編集結果を示します。

InstructPix2Pixに関する追加情報は、論文、元のコードベース、およびデモで試すことができます。

スケジューラーのトレードオフ、すなわち速度と品質のバランスをどのように探求するかを学ぶには、ガイドを必ずご確認ください。また、同じコンポーネントを複数のパイプラインに効率的に読み込む方法については、パイプライン間でコンポーネントを再利用するセクションを参照してください。

StableDiffusionInstructPix2PixPipeline

クラス diffusers.StableDiffusionInstructPix2PixPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulerssafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilimage_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection | None = Nonerequires_safety_checker: bool = True )

パラメータ

  • vae (AutoencoderKL) — 画像を潜在表現にエンコードし、潜在表現からデコードするための Variational Auto-Encoder (VAE) モデル。
  • text_encoder (CLIPTextModel) — 凍結されたテキストエンコーダー (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — テキストをトークン化するためのCLIPTokenizer。
  • unet (UNet2DConditionModel) — エンコードされた画像の潜在変数からノイズを除去するためのUNet2DConditionModel。
  • scheduler (SchedulerMixin) — unet と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。DDIMScheduler、LMSDiscreteScheduler、または PNDMScheduler のいずれかです。
  • safety_checker (StableDiffusionSafetyChecker) — 生成された画像が攻撃的または有害とみなされる可能性を推定する分類モジュールです。 モデルの潜在的な害に関する詳細については、モデルカードを参照してください。
  • feature_extractor (CLIPImageProcessor) — 生成された画像から特徴量を抽出するためのCLIPImageProcessor。safety_checkerの入力として使用されます。

テキスト指示に従ってピクセルレベルの画像編集を行うためのPipeline(Stable Diffusionベース)。

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

パイプラインは、以下の読み込みメソッドも継承します:

__call__

< >

( prompt: str | list[str] = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonenum_inference_steps: int = 100guidance_scale: float = 7.5image_guidance_scale: float = 1.5negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_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] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']cross_attention_kwargs: dict[str, typing.Any] | None = None**kwargs ) → StableDiffusionPipelineOutput or tuple

パラメータ

  • prompt (str または list[str]、任意) — 画像生成をガイドするためのプロンプトです。未定義の場合、prompt_embeds を渡す必要があります。
  • image (torch.Tensor np.ndarray、PIL.Image.Image、list[torch.Tensor]、list[PIL.Image.Image]、または list[np.ndarray]) — prompt に従って再描画される画像バッチを表す Image またはテンソル。画像の潜在変数も image として受け取れますが、潜在変数を直接渡す場合は再度エンコードされません。
  • num_inference_steps (int、任意、デフォルト値は 100) — デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • guidance_scale (float、任意、デフォルト値は 7.5) — guidance scale の値を高くすると、画像の品質が低下する代わりに、prompt と密接に関連した画像を生成するようモデルが促されます。guidance_scale > 1 の場合、guidance scale が有効になります。
  • image_guidance_scale (float、任意、デフォルト値は 1.5) — 生成される画像を初期の image に近づけます。Image guidance scale は、image_guidance_scale > 1 を設定することで有効になります。Image guidance scale を高くすると、ソースの image と密接に関連した生成画像が得られやすくなりますが、通常は画像品質の低下を伴います。このパイプラインでは、少なくとも 1 以上の値が必要です。
  • negative_prompt (str または list[str]、任意) — 画像生成において含めるべきでない内容を指定するためのプロンプトです。未定義の場合、代わりに negative_prompt_embeds を渡す必要があります。ガイダンスを使用していない場合(guidance_scale < 1)は無視されます。
  • num_images_per_prompt (int、任意、デフォルトは 1) — プロンプトごとに生成する画像の数。
  • eta (float、省略可、デフォルト値は 0.0) — DDIM論文のパラメータ eta (η) に対応します。DDIMSchedulerでのみ適用され、他のスケジューラーでは無視されます。
  • generator (torch.Generator、省略可) — 生成を決定論的にするためのtorch.Generator。
  • latents (torch.Tensor, 任意) — ガウス分布からサンプリングされた事前生成されたノイズ付き latents。画像生成のインプットとして使用します。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム generator を用いてサンプリングを行い、latents テンソルが生成されます。
  • prompt_embeds (torch.Tensor, 任意) — 事前に生成されたテキスト埋め込みです。テキスト入力(プロンプトの重み付けなど)を簡単に調整するために使用できます。指定されない場合、prompt 入力引数からテキスト埋め込みが生成されます。
  • negative_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなテキスト埋め込み。テキスト入力(プロンプトの重み付け)を簡単に調整するために使用できます。指定されない場合、negative_prompt_embeds は negative_prompt 入力引数から生成されます。
  • ip_adapter_image — (PipelineImageInput, 任意): IP Adapter と組み合わせて使用する任意の画像入力です。
  • ip_adapter_image_embeds (list[torch.Tensor], 任意) — IP-Adapter 用の事前生成された画像埋め込みです。IP-Adapter の数と同じ長さのリストである必要があります。各要素は、(batch_size, num_images, emb_dim) の形状を持つテンソルである必要があります。do_classifier_free_guidance が True に設定されている場合、負の画像埋め込みを含む必要があります。指定されない場合、ip_adapter_image 入力引数から埋め込みが計算されます。
  • output_type (str、任意、デフォルトは "pil") — 生成された画像の出力形式です。PIL.Image または np.array から選択します。
  • return_dict (bool、任意、デフォルトは True) — プレーンなタプルではなく StableDiffusionPipelineOutput を返すかどうかを指定します。
  • callback_on_step_end (Callable、PipelineCallback、MultiPipelineCallbacks、省略可) — 推論中の各デノイジングステップの終了時に呼び出される関数、またはPipelineCallbackまたはMultiPipelineCallbacksのサブクラスです。引数は以下の通りです: 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 属性にリストされている変数のみを、このリストに含めることができます。
  • cross_attention_kwargs (dict, 任意) — 指定された場合、self.processor で定義されている AttentionProcessor に渡される kwargs の辞書です。

戻り値

StableDiffusionPipelineOutput または tuple

If return_dict is True, StableDiffusionPipelineOutput is returned, otherwise a tuple is returned where the first element is a list with the generated images and the second element is a list of bools indicating whether the corresponding generated image contains “not-safe-for-work” (nsfw) content.

生成用の pipeline への呼び出し関数。

例:

>>> import PIL
>>> import requests
>>> import torch
>>> from io import BytesIO

>>> from diffusers import StableDiffusionInstructPix2PixPipeline


>>> def download_image(url):
...     response = requests.get(url)
...     return PIL.Image.open(BytesIO(response.content)).convert("RGB")


>>> img_url = "https://huggingface.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png"

>>> image = download_image(img_url).resize((512, 512))

>>> pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(
...     "timbrooks/instruct-pix2pix", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "make the mountains snowy"
>>> image = pipe(prompt=prompt, image=image).images[0]

load_textual_inversion

< >

( pretrained_model_name_or_path: str | list[str] | dict[str, torch.Tensor] | list[dict[str, torch.Tensor]]token: str | list[str] | None = Nonetokenizer: 'PreTrainedTokenizer' | None = Nonetext_encoder: 'PreTrainedModel' | None = None**kwargs )

パラメータ

  • pretrained_model_name_or_path (str または os.PathLike または list[str or os.PathLike] または Dict または list[Dict]) — 次のいずれか、またはそれらのリストを指定できます:
    • model id(例: sd-concepts-library/low-poly-hd-logos-icons)の文字列で、Hub上でホストされている事前学習済みモデルを指定します。
    • テキストインバージョンの重みを含むディレクトリへのパス(例: ./my_text_inversion_directory/)。
    • テキストインバージョンの重みを含むファイル(例: ./my_text_inversions.pt)へのパス。
    • torch state dictです。
  • token (str または list[str]、省略可) — テキスト反転の重みに使用するトークンを上書きします。pretrained_model_name_or_path がリストの場合、token も同じ長さのリストである必要があります。
  • text_encoder (CLIPTextModel、任意) — 凍結されたテキストエンコーダー(clip-vit-large-patch14)。 指定しない場合、関数は self.tokenizer を使用します。
  • tokenizer (CLIPTokenizer、任意) — テキストをトークン化するためのCLIPTokenizerです。指定しない場合、関数はself.tokenizerを使用します。
  • weight_name (str, 省略可) — カスタム重みファイルの名前。次の場合に使用します:
    • 保存されたテキストインバージョンファイルは🤗 Diffusers形式ですが、text_inv.binのような特定の重み名で保存されています。
    • 保存されたテキストインバージョンファイルは、Automatic1111形式です。
  • cache_dir (str | os.PathLike, 任意) — 標準のキャッシュを使用しない場合、ダウンロードした事前学習モデルの構成がキャッシュされるディレクトリのパス。
  • force_download (bool、任意、デフォルトは False) — モデルの重みおよび設定ファイルを(再)ダウンロードすることを強制するかどうか。キャッシュされたバージョンが存在する場合でも、それらを無視してダウンロードします。
  • proxies (dict[str, str]、省略可) — プロトコルまたはエンドポイントごとに使用するプロキシサーバーの辞書です。例えば、{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'} のように指定します。各リクエストでこれらのプロキシが使用されます。
  • local_files_only (bool、任意、デフォルトは False) — ローカルのモデル重みと設定ファイルのみを読み込むかどうかを指定します。True に設定すると、モデルは Hub からダウンロードされません。
  • hf_token (str または bool、省略可) — リモートファイルの HTTP ベアラ認証に使用するトークンです。True の場合、diffusers-cli login で生成されたトークン(~/.huggingface に保存されています)が使用されます。
  • revision (str、任意、デフォルトは"main") — 使用する特定のモデルのバージョンです。ブランチ名、タグ名、コミット ID、または Git によって許可される任意の識別子を使用できます。
  • subfolder (str、任意、デフォルトは"") — Hub またはローカル上のより大きなモデルリポジトリ内での、モデルファイルのサブフォルダの場所。
  • mirror (str, 任意) — 中国でモデルをダウンロードする際に、アクセシビリティの問題を解決するためのミラーソースです。ソースの鮮度や安全性を保証するものではなく、詳細についてはミラーサイトをご参照ください。

StableDiffusionPipelineのテキストエンコーダーにTextual Inversionの埋め込みを読み込みます(🤗 Diffusers形式とAutomatic1111形式の両方がサポートされています)。

例:

🤗 Diffusers形式でTextual Inversion埋め込みベクトルを読み込むには:

from diffusers import StableDiffusionPipeline
import torch

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("sd-concepts-library/cat-toy")

prompt = "A <cat-toy> backpack"

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("cat-backpack.png")

Automatic1111形式のTextual Inversion埋め込みベクトルを読み込むには、まずベクトルをダウンロードしてください(civitAIなどから)。その後、ベクトルを読み込みます。

ローカルで:

from diffusers import StableDiffusionPipeline
import torch

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")

prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("character.png")

load_lora_weights

< >

( pretrained_model_name_or_path_or_dict: str | dict[str, torch.Tensor]adapter_name: str | None = Nonehotswap: bool = False**kwargs )

パラメータ

  • pretrained_model_name_or_path_or_dict (str または os.PathLike または dict) — lora_state_dict()を参照してください。
  • adapter_name (str, 省略可) — 読み込まれたアダプターモデルを参照するために使用するアダプター名。指定しない場合、読み込まれるアダプターの総数を i として default_{i} が使用されます。
  • low_cpu_mem_usage (bool、省略可) — 事前学習済み LoRA 重みのみを読み込み、ランダム重みの初期化を行わないことで、モデルの読み込みを高速化します。
  • hotswap (bool, 省略可) — デフォルトは False. 既存の (LoRA) アダプターを、新しく読み込まれたアダプターでその場で置き換えるかどうか。つまり、追加のアダプターを読み込むのではなく、既存のアダプターの重みを新しいアダプターの重みで置き換えます。これにより、より高速かつメモリ効率の高い処理が可能になります。ただし、hotswap の主な利点は、モデルが torch.compile でコンパイルされている場合、新しいアダプターを読み込んでもモデルの再コンパイルが不要になる点です。hotswap を使用する場合は、渡す adapter_name は、すでに読み込まれているアダプターの名前である必要があります。

    新しいアダプターと古いアダプターでランクと/またはLoRA alpha(つまりスケーリング)が異なる場合、アダプターを読み込む前に追加のメソッドを呼び出す必要があります:

pretrained_model_name_or_path_or_dict で指定された LoRA の重みを self.unet および self.text_encoder に読み込みます。

すべてのkwargsはself.lora_state_dictに転送されます。

ステートディクティの読み込み方法の詳細については、lora_state_dict()を参照してください。

self.unet にステートディクトがどのように読み込まれるかについては、load_lora_into_unet() を参照してください。

self.text_encoder に state dict がどのように読み込まれるかについては、load_lora_into_text_encoder() を参照してください。

save_lora_weights

< >

( save_directory: str | os.PathLikeunet_lora_layers: dict = Nonetext_encoder_lora_layers: dict = Noneis_main_process: bool = Trueweight_name: str = Nonesave_function: typing.Callable = Nonesafe_serialization: bool = Trueunet_lora_adapter_metadata = Nonetext_encoder_lora_adapter_metadata = None )

パラメータ

  • save_directory (str または os.PathLike) — LoRA パラメータを保存するディレクトリ。存在しない場合は作成されます。
  • unet_lora_layers (dict[str, torch.nn.Module] または dict[str, torch.Tensor]) — unet に対応する LoRA レイヤーの state dict です。
  • text_encoder_lora_layers (dict[str, torch.nn.Module] または dict[str, torch.Tensor]) — text_encoder に対応する LoRA レイヤーの state dict です。🤗 Transformers から由来するため、テキストエンコーダーの LoRA state dict を明示的に渡す必要があります。
  • is_main_process (bool、任意、デフォルトは True) — この関数を呼び出しているプロセスがメインプロセスかどうかを示します。分散学習時に、この関数をすべてのプロセスで呼び出す必要がある場合に便利です。この場合、競合状態を避けるために、メインプロセスでのみ is_main_process=True を設定してください。
  • save_function (Callable) — 状態辞書を保存するために使用する関数です。分散学習時にtorch.saveを別のメソッドに置き換える必要がある場合に便利です。環境変数DIFFUSERS_SAVE_MODEで設定できます。
  • safe_serialization (bool、任意、デフォルトはTrue) — safetensorsを使用してモデルを保存するか、従来のpickleによるPyTorchの方式で保存するかどうかを指定します。
  • unet_lora_adapter_metadata — state dict と一緒にシリアライズされる、unet に関連付けられた LoRA アダプターのメタデータ。
  • text_encoder_lora_adapter_metadata — テキストエンコーダーに関連付けられたLoRAアダプターのメタデータ。ステートディクトとともにシリアライズされます。

UNetおよびテキストエンコーダーに対応するLoRAパラメータを保存します。

StableDiffusionXLInstructPix2PixPipeline

class diffusers.StableDiffusionXLInstructPix2PixPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulersforce_zeros_for_empty_prompt: bool = Trueadd_watermarker: bool | None = Noneis_cosxl_edit: bool | None = False )

パラメータ

  • 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 (SchedulerMixin) — unet と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。DDIMScheduler、LMSDiscreteScheduler、または PNDMScheduler のいずれかです。
  • requires_aesthetics_score (bool、省略可、デフォルトは "False") — unet が推論時に aesthetic_score 条件の受け渡しを必要とするかどうか。stabilityai/stable-diffusion-xl-refiner-1-0 の設定も参照してください。
  • force_zeros_for_empty_prompt (bool、省略可、デフォルトは "True") — ネガティブプロンプトの埋め込みを常に 0 に設定するかどうか。stabilityai/stable-diffusion-xl-base-1-0 の設定も参照してください。
  • add_watermarker (bool、省略可) — invisible_watermark ライブラリを使用して出力画像にウォーターマークを付与するかどうかを指定します。未定義の場合、パッケージがインストールされていれば True がデフォルトとなり、インストールされていなければウォーターマークは付与されません。
  • is_cosxl_edit (bool、省略可) — 設定すると、画像の潜在変数がスケーリングされます。

テキスト指示に従ってピクセルレベルの画像編集を行うPipeline。Stable Diffusion XLをベースとしています。

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

パイプラインは、以下の読み込みメソッドも継承します:

__call__

< >

( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 100denoising_end: float | None = Noneguidance_scale: float = 5.0image_guidance_scale: float = 1.5negative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1cross_attention_kwargs: dict[str, typing.Any] | None = Noneguidance_rescale: float = 0.0original_size: tuple = Nonecrops_coords_top_left: tuple = (0, 0)target_size: tuple = None ) → ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput or tuple

パラメータ

  • prompt (str または list[str]、省略可) — 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに prompt_embeds を渡す必要があります。
  • prompt_2 (str または list[str]、省略可) — tokenizer_2 および text_encoder_2 に送信するプロンプトです。定義されていない場合、両方のテキストエンコーダーに prompt が使用されます。
  • image (torch.Tensor または PIL.Image.Image または np.ndarray または list[torch.Tensor] または list[PIL.Image.Image] または list[np.ndarray]) — パイプラインで修正する画像です。
  • height (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) — 生成される画像の高さ(ピクセル単位)。
  • width (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) — 生成される画像の幅(ピクセル単位)。
  • num_inference_steps (int、任意、デフォルト値は 50)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • denoising_end (float, 省略可) — 指定した場合、デノイジング全体のどの割合(0.0 から 1.0 の間)で処理を意図的に早期終了させるかを決定します。その結果、スケジューラによって選択された離散タイムステップによって決定されるように、返されるサンプルには依然としてかなりの量のノイズが残ります。denoising_end パラメータは、画像出力の洗練 に詳述されている「Mixture of Denoisers」マルチパイプライン構成の一部としてこのパイプラインが使用される場合に、理想的には利用されるべきです。
  • guidance_scale (float、任意、デフォルト値は 5.0) — Classifier-Free Diffusion Guidance で定義されているガイダンススケールです。guidance_scale は、Imagen Paper の数式 2 の w として定義されています。guidance_scale > 1 を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、prompt のテキストと密接に関連する画像の生成が促されますが、通常は画像の品質が低下する傾向があります。
  • image_guidance_scale (float, 任意、デフォルト値は 1.5) — Image guidance scale は、生成される画像を初期画像 image に近づけるためのスケーリング係数です。image_guidance_scale > 1 を設定することで有効になります。Image guidance scale を高くすると、ソース画像 image と密接に関連した画像の生成が促されますが、通常は画像品質の低下を伴います。このパイプラインでは、少なくとも 1 以上の値が必要です。
  • 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_images_per_prompt (int、任意、デフォルトは 1) — プロンプトごとに生成する画像の数。
  • eta (float、省略可、デフォルト値は 0.0) — DDIM 論文におけるパラメータ eta (η) に相当します: https://huggingface.co/papers/2010.02502。 schedulers.DDIMScheduler にのみ適用され、それ以外の場合は無視されます。
  • generator (torch.Generator または list[torch.Generator]、省略可) — 生成を決定論的にするためのtorch ジェネレーター1つまたはリスト。
  • latents (torch.Tensor, 任意) — 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイズ付き潜在変数。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムgeneratorを使用してサンプリングを行い、潜在変数テンソルが生成されます。
  • prompt_embeds (torch.Tensor, 任意) — 事前に生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt 入力引数からテキスト埋め込みが生成されます。
  • negative_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなテキスト埋め込みです。テキスト入力の調整、例えばプロンプトの重み付けなどを簡単に実行できます。指定されない場合、negative_prompt 入力引数から negative_prompt_embeds が生成されます。
  • pooled_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたプールのテキスト埋め込みです。テキスト入力の調整、例えばプロンプトの重み付けなどに簡単に利用できます。 指定されない場合、prompt 入力引数からプールのテキスト埋め込みが生成されます。
  • negative_pooled_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなプーリング済みテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、negative_prompt 入力引数からプーリング済み negative_prompt_embeds が生成されます。
  • output_type (str、任意、デフォルトは "pil") — 画像生成の出力形式です。PIL: PIL.Image.Image または np.array から選択します。
  • return_dict (bool、任意、デフォルトは True) — ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput を返すか、それとも通常のタプルを返すかを指定します。
  • callback (Callable, 省略可) — 推論中に callback_steps ステップごとに呼び出される関数です。この関数は、以下の引数とともに呼び出されます: callback(step: int, timestep: int, latents: torch.Tensor)。
  • callback_steps (int、任意、デフォルトは 1) — callback 関数が呼び出される頻度です。指定しない場合、callback はすべてのステップで呼び出されます。
  • cross_attention_kwargs (dict、省略可) — 指定された場合、diffusers.models.attention_processor で定義されている self.processor 配下の AttentionProcessor に渡される kwargs の辞書です。
  • guidance_rescale (float, optional, defaults to 0.0) — 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.
  • original_size (tuple[int]、任意、デフォルト値は (1024, 1024)) — original_size が target_size と異なる場合、画像はダウンサンプリングまたはアップサンプリングされたように見えます。 指定されていない場合、original_size のデフォルト値は (height, width) です。これは https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロコンディショニングの一部です。
  • 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 は生成される画像の希望する高さおよび幅に設定すべきです。指定されない場合、デフォルトで (height, width) が使用されます。https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL の micro-conditioning の一部です。

戻り値

~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput または tuple

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

生成用のパイプラインを呼び出したときに実行される関数。

例:

>>> import torch
>>> from diffusers import StableDiffusionXLInstructPix2PixPipeline
>>> from diffusers.utils import load_image

>>> resolution = 768
>>> image = load_image(
...     "https://hf.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png"
... ).resize((resolution, resolution))
>>> edit_instruction = "Turn sky into a cloudy one"

>>> pipe = StableDiffusionXLInstructPix2PixPipeline.from_pretrained(
...     "diffusers/sdxl-instructpix2pix-768", torch_dtype=torch.float16
... ).to("cuda")

>>> edited_image = pipe(
...     prompt=edit_instruction,
...     image=image,
...     height=resolution,
...     width=resolution,
...     guidance_scale=3.0,
...     image_guidance_scale=1.5,
...     num_inference_steps=30,
... ).images[0]
>>> edited_image

encode_prompt

< >

( prompt: strprompt_2: str | None = Nonedevice: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1do_classifier_free_guidance: bool = Truenegative_prompt: str | None = Nonenegative_prompt_2: str | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = None )

パラメータ

  • prompt (str または list[str]、省略可能) — エンコードするプロンプト
  • prompt_2 (str または list[str]、省略可) — tokenizer_2 および text_encoder_2 に送信するプロンプトです。定義されていない場合、両方のテキストエンコーダーに prompt が使用されます。
  • device — (torch.device): torch デバイス
  • num_images_per_prompt (int) — 1つのプロンプトに対して生成する画像の数
  • do_classifier_free_guidance (bool) — classifier free guidance を使用するかどうか
  • negative_prompt (str または list[str]、省略可) — 画像生成をガイドしないプロンプトです。未定義の場合、代わりに negative_prompt_embeds を渡す必要があります。ガイダンスを使用していない場合は無視されます(guidance_scale が 1 未満の場合は無視されます)。
  • negative_prompt_2 (str または list[str]、省略可) — tokenizer_2 および text_encoder_2 に送信する、画像生成を導かないためのプロンプトです。未定義の場合、両方のテキストエンコーダーで negative_prompt が使用されます。
  • prompt_embeds (torch.Tensor, 任意) — 事前に生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt 入力引数からテキスト埋め込みが生成されます。
  • negative_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなテキスト埋め込みです。テキスト入力の調整、例えばプロンプトの重み付けなどを簡単に実行できます。指定されない場合、negative_prompt 入力引数から negative_prompt_embeds が生成されます。
  • pooled_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたプールのテキスト埋め込みです。テキスト入力の調整、例えばプロンプトの重み付けなどに簡単に利用できます。 指定されない場合、prompt 入力引数からプールのテキスト埋め込みが生成されます。
  • negative_pooled_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなプーリング済みテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、negative_prompt 入力引数からプーリング済み negative_prompt_embeds が生成されます。
  • lora_scale (float, 省略可) — LoRA レイヤーが読み込まれている場合、テキストエンコーダーのすべての LoRA レイヤーに適用される LoRA スケールです。

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

Update on GitHub