Diffusers documentation

Perturbed-Attention Guidance

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

Perturbed-Attention Guidance

LoRA

Perturbed-Attention Guidance (PAG)は、無条件設定および条件付き設定の両方でサンプル品質を向上させる新しい拡散サンプリングガイダンスです。追加の学習や外部モジュールの統合を必要とせずに、この品質向上を実現します。

PAGは、Donghoon Ahn、Hyoungwon Cho、Jaewon Min、Wooseok Jang、Jungwoo Kim、SeonHwa Kim、Hyun Hee Park、Kyong Hwan Jin、Seungryong Kim による Self-Rectifying Diffusion Sampling with Perturbed-Attention Guidance で紹介されました。

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

最近の研究により、拡散モデルは高品質なサンプルを生成できることが示されていますが、その品質は、Classifier Guidance (CG) や Classifier-Free Guidance (CFG) などのサンプリングガイダンス手法に大きく依存しています。これらの手法は、無条件生成や画像復元などのさまざまな下流タスクでは適用できないことがよくあります。本論文では、無条件設定および条件付き設定の両方で拡散サンプルの品質を向上させる新しいサンプリングガイダンス、Perturbed-Attention Guidance (PAG) を提案します。PAG は、追加の学習や外部モジュールの統合を必要とせずにこの向上を実現します。PAG は、デノイジングプロセス全体を通じてサンプルの構造を段階的に強化するように設計されています。具体的には、自己注意機構が構造情報を捕捉する能力を考慮し、拡散 U-Net の選択された自己注意マップを単位行列に置き換えることで構造が劣化した中間サンプルを生成し、デノイジングプロセスをこれらの劣化したサンプルから遠ざけるように誘導します。ADM と Stable Diffusion の両方において、PAG は条件付きシナリオだけでなく、無条件シナリオでもサンプルの品質を驚くほど向上させます。さらに、ControlNet の空プロンプトやインペインティング、デブラーリングなどの画像復元を含む、CG や CFG などの既存のガイダンスを十分に活用できないさまざまな下流タスクにおいて、PAG はベースラインの性能を大幅に向上させます。

PAGは、PAGパイプラインをインスタンス化する際にpag_applied_layersをパラメータとして指定することで使用できます。単一の文字列または文字列のリストを指定できます。各文字列は、一意のレイヤー識別子、または1つ以上のレイヤーを特定するための正規表現を指定できます。

  • 通常の文字列としての完全な識別子: down_blocks.2.attentions.0.transformer_blocks.0.attn1.processor
  • RegEx としての完全な識別子: down_blocks.2.(attentions|motion_modules).0.transformer_blocks.0.attn1.processor
  • RegEx としての部分識別子: down_blocks.2 または attn1
  • 識別子のリスト(文字列とReGExの組み合わせ可): ["blocks.1", "blocks.(14|20)", r"down_blocks\.(2,3)"]

RegEx はレイヤー識別子のマッチング手段としてサポートされているため、正しく使用することが極めて重要です。正しく使用しないと、予期しない動作が発生する可能性があります。PAG を使用する推奨方法は、レイヤーを blocks.{layer_index} および blocks.({layer_index_1|layer_index_2|...}) の形式で指定することです。これ以外の方法で使用する場合は、実行は可能ですが、基本的な検証チェックを回避してしまい、予期しない結果につながる可能性があります。

一般的なタスク

PAGは、テキストから画像への変換、画像から画像への変換、インペインティングなどのタスクにおいて、StableDiffusionXLPipelineに適用できます。特定のタスクでPAGを有効にするには、enable_pag=Trueフラグとpag_applied_layers引数を指定して、AutoPipeline APIを使用してパイプラインを読み込みます。

🤗 Diffusers は現在、PAG を一部の SDXL パイプラインおよび PixArtSigmaPAGPipeline で使用することのみサポートしています。新しいパイプラインに PAG のサポートを追加したい場合は、機能リクエスト をお気軽に作成してください。

テキストから画像へ
画像から画像へ
インペインティング
from diffusers import AutoPipelineForText2Image
from diffusers.utils import load_image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    enable_pag=True,
    pag_applied_layers=["mid"],
    dtype=torch.float16
)
pipeline.enable_model_cpu_offload()

pag_applied_layers 引数により、PAG を適用するレイヤーを指定できます。また、パイプラインの作成後に set_pag_applied_layers メソッドを使用して、これらのレイヤーを更新することも可能です。他のレイヤーへの PAG の適用方法については、pag_applied_layers セクションを参照してください。

すでに作成・読み込み済みのパイプラインがある場合、enable_pag フラグを指定して from_pipe API を使用することで、そのパイプラインに PAG を有効化できます。内部では、指定したパイプラインとタスクに基づいて PAG パイプラインが作成されます。以下の例では、AutoPipelineForText2Image を使用し StableDiffusionXLPipeline を渡したため、StableDiffusionXLPAGPipeline がそれに応じて作成されます。なお、これには追加のメモリは必要なく、StableDiffusionXLPipeline と StableDiffusionXLPAGPipeline の両方が読み込まれて使用可能な状態になります。from_pipe API とパイプラインの再利用方法については、diffuser の こちら をご覧ください。

pipeline_sdxl = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16)
pipeline = AutoPipelineForText2Image.from_pipe(pipeline_sdxl, enable_pag=True)

画像を生成するには、pag_scale も渡す必要があります。pag_scale を大きくすると、画像はより意味的に一貫性のある構造を持ち、アーティファクトが少なくなります。ただし、ガイドスケールが大きすぎると、CFG と同様に、テクスチャが滑らかになり、画像がわずかに飽和する可能性があります。公式デモでは pag_scale=3.0 が使用されており、ほとんどのユースケースで良好に動作しますが、必要に応じて実験し、適切な値を選択してください。pag_scale=0 の場合、PAG は無効になります。

prompt = "an insect robot preparing a delicious meal, anime style"

for pag_scale in [0.0, 3.0]:
    generator = torch.Generator(device="cpu").manual_seed(0)
    images = pipeline(
        prompt=prompt,
        num_inference_steps=25,
        guidance_scale=7.0,
        generator=generator,
        pag_scale=pag_scale,
    ).images
PAGなしで生成された画像
PAGで生成された画像

ControlNet を使用した PAG

PAGをControlNetと併用するには、まずcontrolnetを作成します。次に、指定したタスクのAutoPipelineのfrom_pretrainedメソッドに、controlnetとその他のPAG引数を渡します。

from diffusers import AutoPipelineForText2Image, ControlNetModel
import torch

controlnet = ControlNetModel.from_pretrained(
    "diffusers/controlnet-canny-sdxl-1.0", dtype=torch.float16
)

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    controlnet=controlnet,
    enable_pag=True,
    pag_applied_layers="mid",
    dtype=torch.float16
)
pipeline.enable_model_cpu_offload()

すでに ControlNet パイプラインがあり、PAG を有効にしたい場合は、from_pipe API を使用できます: AutoPipelineForText2Image.from_pipe(pipeline_controlnet, enable_pag=True)

は通常のControlNetパイプラインと同様に使用でき、pag_scaleパラメータを指定するオプションが追加されています。なお、PAGは条件なし生成で良好に動作します。この例では、プロンプトなしで画像を生成します。

from diffusers.utils import load_image
canny_image = load_image(
    "https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/pag_control_input.png"
)

for pag_scale in [0.0, 3.0]:
    generator = torch.Generator(device="cpu").manual_seed(1)
    images = pipeline(
        prompt="",
        controlnet_conditioning_scale=controlnet_conditioning_scale,
        image=canny_image,
        num_inference_steps=50,
        guidance_scale=0,
        generator=generator,
        pag_scale=pag_scale,
    ).images
    images[0]
PAGなしで生成された画像
PAGで生成された画像

IP-Adapter を使用した PAG

IP-Adapterは、基盤モデルを変更することなく画像プロンプトを可能にするため、拡散モデルに組み込むことができる人気のあるモデルです。IP-Adapterが読み込まれたパイプラインでPAGを有効にできます。

from diffusers import AutoPipelineForText2Image
from diffusers.utils import load_image
from transformers import CLIPVisionModelWithProjection
import torch

image_encoder = CLIPVisionModelWithProjection.from_pretrained(
    "h94/IP-Adapter",
    subfolder="models/image_encoder",
    dtype=torch.float16
)

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    image_encoder=image_encoder,
    enable_pag=True,
    dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"

pipeline.load_ip_adapter("h94/IP-Adapter", subfolder="sdxl_models", weight_name="ip-adapter-plus_sdxl_vit-h.bin")

pag_scales = 5.0
ip_adapter_scales = 0.8

image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_diner.png")

pipeline.set_ip_adapter_scale(ip_adapter_scale)
generator = torch.Generator(device="cpu").manual_seed(0)
images = pipeline(
    prompt="a polar bear sitting in a chair drinking a milkshake",
    ip_adapter_image=image,
    negative_prompt="deformed, ugly, wrong proportion, low res, bad anatomy, worst quality, low quality",
    num_inference_steps=25,
    guidance_scale=3.0,
    generator=generator,
    pag_scale=pag_scale,
).images
images[0]

PAG はアーティファクトを軽減し、全体の構成を改善します。

PAGなしで生成された画像
PAGで生成された画像

パラメータを設定

pag_applied_layers

pag_applied_layers 引数により、PAG を適用するレイヤーを指定できます。デフォルトでは、mid blocks にのみ適用されます。この設定を変更すると、出力に大きな影響を与えます。パイプラインの作成後、set_pag_applied_layers メソッドを使用して PAG の適用レイヤーを調整することで、モデルに最適なレイヤーを見つけることができます。

例として、pag_layers = ["down.block_2"]とpag_layers = ["down.block_2", "up.block_1.attentions_0"]で生成された画像を示します。

prompt = "an insect robot preparing a delicious meal, anime style"
pipeline.set_pag_applied_layers(pag_layers)
generator = torch.Generator(device="cpu").manual_seed(0)
images = pipeline(
    prompt=prompt,
    num_inference_steps=25,
    guidance_scale=guidance_scale,
    generator=generator,
    pag_scale=pag_scale,
).images
images[0]
down.block_2 + up.block1.attentions_0
down.block_2

AnimateDiffPAGPipeline

クラス diffusers.AnimateDiffPAGPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: diffusers.models.unets.unet_2d_condition.UNet2DConditionModel | diffusers.models.unets.unet_motion_model.UNetMotionModelmotion_adapter: MotionAdapterscheduler: KarrasDiffusionSchedulersfeature_extractor: CLIPImageProcessorPil = Noneimage_encoder: CLIPVisionModelWithProjection = Nonepag_applied_layers: str | list[str] = 'mid_block.*attn1' )

パラメータ

  • vae (AutoencoderKL) — 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ (VAE) モデル。
  • text_encoder (CLIPTextModel) — 凍結されたテキストエンコーダー (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — テキストをトークン化するためのCLIPTokenizerです。
  • unet (UNet2DConditionModel) — エンコードされた動画の潜在変数をノイズ除去するために、UNetMotionModel を作成するために使用される UNet2DConditionModel。
  • motion_adapter (MotionAdapter) — unet と組み合わせて、エンコードされた動画の潜在変数(latents)のノイズ除去に使用する MotionAdapter です。
  • scheduler (SchedulerMixin) — unet と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。DDIMScheduler、LMSDiscreteScheduler、または PNDMScheduler のいずれかです。

AnimateDiffとPerturbed Attention Guidanceを用いたテキストから動画への変換パイプライン。

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

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

__call__

< >

( prompt: str | list[str] | None = Nonenum_frames: int | None = 16height: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50guidance_scale: float = 7.5negative_prompt: str | list[str] | None = Nonenum_videos_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 = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']decode_chunk_size: int = 16pag_scale: float = 3.0pag_adaptive_scale: float = 0.0 ) → AnimateDiffPipelineOutput or tuple

パラメータ

  • prompt (str または list[str]、任意) — 画像生成をガイドするためのプロンプトです。未定義の場合、prompt_embeds を渡す必要があります。
  • height (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) — 生成される動画のピクセル単位の縦幅です。
  • width (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) — 生成される動画のピクセル単位の幅です。
  • num_frames (int, 任意、デフォルト値は 16) — 生成される動画のフレーム数です。デフォルトでは 16 フレームが設定されており、1 秒あたり 8 フレームの場合、2 秒間の動画に相当します。
  • num_inference_steps (int, 任意、デフォルト値は 50) — デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常、より高品質な動画が生成されます。
  • guidance_scale (float、任意、デフォルト値は 7.5) — guidance scale の値を高くすると、画像の品質が低下する代わりに、prompt と密接に関連した画像を生成するようモデルが促されます。guidance_scale > 1 の場合、guidance scale が有効になります。
  • negative_prompt (str または list[str]、任意) — 画像生成において含めるべきでない内容を指定するためのプロンプトです。未定義の場合、代わりに negative_prompt_embeds を渡す必要があります。ガイダンスを使用していない場合(guidance_scale < 1)は無視されます。
  • num_videos_per_prompt (int、任意、デフォルト値は 1) — 1 つのプロンプトごとに生成する動画の数です。
  • eta (float、省略可、デフォルト値は 0.0) — DDIM論文のパラメータ eta (η) に対応します。DDIMSchedulerでのみ適用され、他のスケジューラーでは無視されます。
  • generator (torch.Generator または list[torch.Generator]、省略可) — 生成を決定論的にするための torch.Generator。
  • latents (torch.Tensor, 任意) — ガウス分布からサンプリングされた事前生成されたノイズ付き潜在変数で、動画生成の入力として使用されます。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムgeneratorを使用してサンプリングを行い、潜在変数テンソルが生成されます。潜在変数の形状は(batch_size, num_channel, num_frames, height, width)である必要があります。
  • 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") — 生成された動画の出力形式です。torch.Tensor、PIL.Image、または np.array から選択してください。
  • return_dict (bool、省略可能、デフォルトは True) — ~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput を返すか、プレーンなタプルを返すかを指定します。
  • cross_attention_kwargs (dict, 任意) — 指定された場合、self.processor で定義されている AttentionProcessor に渡される kwargs の辞書です。
  • 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 属性にリストされている変数のみを、このリストに含めることができます。
  • decode_chunk_size (int, 任意、デフォルトは 16) — decode_latents メソッドを呼び出す際に、一度にデコードするフレーム数です。
  • pag_scale (float、任意、デフォルト値は 3.0) — Perturbed attention guidance のスケール係数です。0.0 に設定すると、perturbed attention guidance は使用されません。
  • pag_adaptive_scale (float, 任意、デフォルト値は 0.0) — パーターブド・アテンション・ガイダンス用の適応スケール係数です。0.0 に設定されている場合、pag_scale が使用されます。

戻り値

AnimateDiffPipelineOutput または tuple

return_dict が True の場合、AnimateDiffPipelineOutput が返され、それ以外の場合は、最初の要素が生成されたフレームのリストである tuple が返されます。

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

例:

>>> import torch
>>> from diffusers import AnimateDiffPAGPipeline, MotionAdapter, DDIMScheduler
>>> from diffusers.utils import export_to_gif

>>> model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
>>> motion_adapter_id = "guoyww/animatediff-motion-adapter-v1-5-2"
>>> motion_adapter = MotionAdapter.from_pretrained(motion_adapter_id)
>>> scheduler = DDIMScheduler.from_pretrained(
...     model_id, subfolder="scheduler", beta_schedule="linear", steps_offset=1, clip_sample=False
... )
>>> pipe = AnimateDiffPAGPipeline.from_pretrained(
...     model_id,
...     motion_adapter=motion_adapter,
...     scheduler=scheduler,
...     pag_applied_layers=["mid"],
...     torch_dtype=torch.float16,
... ).to("cuda")

>>> video = pipe(
...     prompt="car, futuristic cityscape with neon lights, street, no human",
...     negative_prompt="low quality, bad quality",
...     num_inference_steps=25,
...     guidance_scale=6.0,
...     pag_scale=3.0,
...     generator=torch.Generator().manual_seed(42),
... ).frames[0]

>>> export_to_gif(video, "animatediff_pag.gif")

encode_prompt

< >

( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

パラメータ

  • prompt (str または list[str]、省略可能) — エンコードするプロンプト
  • 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 未満の場合は無視されます)。
  • 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 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。

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

HunyuanDiTPAGPipeline

クラス diffusers.HunyuanDiTPAGPipeline

< >

( vae: AutoencoderKLtext_encoder: BertModeltokenizer: BertTokenizertransformer: HunyuanDiT2DModelscheduler: DDPMSchedulersafety_checker: diffusers.pipelines.stable_diffusion.safety_checker.StableDiffusionSafetyChecker | None = Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None = Nonerequires_safety_checker: bool = Truetext_encoder_2: transformers.models.t5.modeling_t5.T5EncoderModel | None = Nonetokenizer_2: transformers.models.t5.tokenization_t5.T5Tokenizer | None = Nonepag_applied_layers: str | list[str] = 'blocks.1' )

パラメータ

  • vae (AutoencoderKL) — 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ (VAE) モデルです。 sdxl-vae-fp16-fix を使用します。
  • text_encoder (~transformers.BertModel、~transformers.CLIPTextModel | None) — 凍結されたテキストエンコーダー(clip-vit-large-patch14)。 HunyuanDiT は、ファインチューニングされた [bilingual CLIP] を使用しています。
  • tokenizer (~transformers.BertTokenizer、~transformers.CLIPTokenizer | None) — テキストをトークン化するためのBertTokenizerまたはCLIPTokenizer。
  • transformer (HunyuanDiT2DModel) — Tencent Hunyuan によって設計された HunyuanDiT モデルです。
  • text_encoder_2 (T5EncoderModel) — mT5エンベッダーです。具体的には ‘t5-v1_1-xxl’ です。
  • tokenizer_2 (T5Tokenizer) — mT5 embedder 用のトークナイザー。
  • scheduler (DDPMScheduler) — HunyuanDiT と組み合わせて使用し、エンコードされた画像の潜在変数からノイズを除去するためのスケジューラ。

HunyuanDiT と Perturbed Attention Guidance を使用した英語/中国語から画像を生成するための Pipeline。

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

HunyuanDiTは2つのテキストエンコーダーを使用しています:mT5と[bilingual CLIP](fine-tuned by ourselves)

__call__

< >

( prompt: str | list[str] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50guidance_scale: float = 5.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_embeds_2: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds_2: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Noneprompt_attention_mask_2: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask_2: typing.Optional[torch.Tensor] = Noneoutput_type: str = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Union[typing.Callable[[int, int, dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']guidance_rescale: float = 0.0original_size: tuple = (1024, 1024)target_size: tuple = Nonecrops_coords_top_left: tuple = (0, 0)use_resolution_binning: bool = Truepag_scale: float = 3.0pag_adaptive_scale: float = 0.0 ) → StableDiffusionPipelineOutput or tuple

パラメータ

  • prompt (str または list[str]、任意) — 画像生成をガイドするためのプロンプトです。未定義の場合、prompt_embeds を渡す必要があります。
  • height (int) — 生成される画像の高さ(ピクセル単位)。
  • width (int) — 生成される画像の幅(ピクセル単位)。
  • num_inference_steps (int、任意、デフォルト値は 50)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。このパラメータは strength によって調整されます。
  • guidance_scale (float、任意、デフォルト値は 7.5) — guidance scale の値を高くすると、画像の品質が低下する代わりに、prompt と密接に関連した画像を生成するようモデルが促されます。guidance_scale > 1 の場合、guidance scale が有効になります。
  • 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 または list[torch.Generator]、省略可) — 生成を決定論的にするための torch.Generator。
  • latents (torch.Tensor, 任意) — ガウス分布からサンプリングされた事前生成されたノイズ付き latents。画像生成のインプットとして使用します。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム generator を用いてサンプリングを行い、latents テンソルが生成されます。
  • prompt_embeds (torch.Tensor, 任意) — 事前に生成されたテキスト埋め込みです。テキスト入力(プロンプトの重み付けなど)を簡単に調整するために使用できます。指定されない場合、prompt 入力引数からテキスト埋め込みが生成されます。
  • prompt_embeds_2 (torch.Tensor, 任意) — 事前に生成されたテキスト埋め込み。テキスト入力(プロンプトの重み付け)を簡単に調整するために使用できます。指定されない場合、prompt 入力引数からテキスト埋め込みが生成されます。
  • negative_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなテキスト埋め込み。テキスト入力(プロンプトの重み付け)を簡単に調整するために使用できます。指定されない場合、negative_prompt_embeds は negative_prompt 入力引数から生成されます。
  • negative_prompt_embeds_2 (torch.Tensor、任意) — 事前に生成されたネガティブなテキスト埋め込み。テキスト入力(プロンプトの重み付け)を簡単に調整するために使用できます。指定されない場合、negative_prompt 入力引数から negative_prompt_embeds が生成されます。
  • prompt_attention_mask (torch.Tensor, 任意) — プロンプト用のアテンションマスクです。prompt_embeds を直接渡す場合に必要です。
  • prompt_attention_mask_2 (torch.Tensor、省略可) — プロンプト用のアテンションマスクです。prompt_embeds_2 を直接渡す場合に必要です。
  • negative_prompt_attention_mask (torch.Tensor, 任意) — ネガティブプロンプト用のアテンションマスクです。negative_prompt_embeds を直接渡す場合に必要です。
  • negative_prompt_attention_mask_2 (torch.Tensor、任意) — ネガティブプロンプト用のアテンションマスクです。negative_prompt_embeds_2 を直接渡す場合に必要です。
  • output_type (str、任意、デフォルトは "pil") — 生成された画像の出力形式です。PIL.Image または np.array から選択します。
  • return_dict (bool、任意、デフォルトは True) — プレーンなタプルではなく StableDiffusionPipelineOutput を返すかどうかを指定します。
  • callback_on_step_end (Callable[[int, int], None]、PipelineCallback、MultiPipelineCallbacks、任意) — 各デノイジングステップの終了時に呼び出されるコールバック関数、またはコールバック関数のリストです。
  • callback_on_step_end_tensor_inputs (list[str]、省略可) — コールバック関数に渡すべきテンソル入力のリストです。定義されていない場合、すべてのテンソル入力が渡されます。
  • guidance_rescale (float, optional, defaults to 0.0) — Rescale the noise_cfg according to guidance_rescale. Based on findings of Common Diffusion Noise Schedules and Sample Steps are Flawed. See Section 3.4
  • original_size (tuple[int, int]、任意、デフォルトは (1024, 1024)) — 画像の元のサイズです。time ids の計算に使用されます。
  • target_size (tuple[int, int]、省略可) — 画像のターゲットサイズ。time ids の計算に使用されます。
  • crops_coords_top_left (tuple[int, int]、任意、デフォルトは (0, 0)) — クロップの左上座標です。time ids の計算に使用されます。
  • use_resolution_binning (bool、任意、デフォルトは True) — 解像度バインニングを使用するかどうかを指定します。True の場合、入力解像度は最も近い標準解像度に変換されます。サポートされている解像度は 1024x1024、1280x1280、1024x768、1152x864、1280x960、768x1024、864x1152、960x1280、1280x768、および 768x1280 です。この値を True に設定することを推奨します。
  • pag_scale (float、任意、デフォルト値は 3.0) — Perturbed attention guidance のスケール係数です。0.0 に設定すると、perturbed attention guidance は使用されません。
  • pag_adaptive_scale (float, 任意、デフォルト値は 0.0) — パーターブド・アテンション・ガイダンス用の適応スケール係数です。0.0 に設定されている場合、pag_scale が使用されます。

戻り値

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.

HunyuanDiT による生成用の pipeline への呼び出し関数。

例:

>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "Tencent-Hunyuan/HunyuanDiT-v1.2-Diffusers",
...     torch_dtype=torch.float16,
...     enable_pag=True,
...     pag_applied_layers=[14],
... ).to("cuda")

>>> # prompt = "an astronaut riding a horse"
>>> prompt = "一个宇航员在骑马"
>>> image = pipe(prompt, guidance_scale=4, pag_scale=3).images[0]

encode_prompt

< >

( prompt: strdevice: device = Nonedtype: dtype = Nonenum_images_per_prompt: int = 1do_classifier_free_guidance: bool = Truenegative_prompt: str | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int | None = Nonetext_encoder_index: int = 0 )

パラメータ

  • prompt (str または list[str]、省略可能) — エンコードするプロンプト
  • device — (torch.device): torch デバイス
  • dtype (torch.dtype) — torch の dtype
  • 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 未満の場合は無視されます)。
  • prompt_embeds (torch.Tensor, 任意) — 事前に生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt 入力引数からテキスト埋め込みが生成されます。
  • negative_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなテキスト埋め込みです。テキスト入力の調整、例えばプロンプトの重み付けなどを簡単に実行できます。指定されない場合、negative_prompt 入力引数から negative_prompt_embeds が生成されます。
  • prompt_attention_mask (torch.Tensor, 任意) — プロンプト用のアテンションマスクです。prompt_embeds を直接渡す場合に必要です。
  • negative_prompt_attention_mask (torch.Tensor, 任意) — ネガティブプロンプト用のアテンションマスクです。negative_prompt_embeds を直接渡す場合に必要です。
  • max_sequence_length (int、任意) — プロンプトに使用する最大シーケンス長。
  • text_encoder_index (int, 省略可) — 使用するテキストエンコーダーのインデックス。clip は 0、T5 は 1 です。

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

KolorsPAGPipeline

class diffusers.KolorsPAGPipeline

< >

( vae: AutoencoderKLtext_encoder: ChatGLMModeltokenizer: ChatGLMTokenizerunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulersimage_encoder: CLIPVisionModelWithProjection = Nonefeature_extractor: CLIPImageProcessorPil = Noneforce_zeros_for_empty_prompt: bool = Falsepag_applied_layers: str | list[str] = 'mid' )

パラメータ

  • vae (AutoencoderKL) — 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ (VAE) モデル。
  • text_encoder (ChatGLMModel) — 凍結されたテキストエンコーダー。Kolors は ChatGLM3-6B を使用しています。
  • tokenizer (ChatGLMTokenizer) — クラス ChatGLMTokenizer のトークナイザー。
  • unet (UNet2DConditionModel) — エンコードされた画像の潜在変数をノイズ除去するための条件付き U-Net アーキテクチャ。
  • scheduler (SchedulerMixin) — unet と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。DDIMScheduler、LMSDiscreteScheduler、または PNDMScheduler のいずれかです。
  • force_zeros_for_empty_prompt (bool、省略可、デフォルトは "False") — ネガティブプロンプトの埋め込みを常に 0 に設定するかどうか。Kwai-Kolors/Kolors-diffusers の設定も参照してください。
  • pag_applied_layers (str or list[str]``, *optional*, defaults to “mid”`) — パーターブド・アテンション・ガイダンスを適用する Transformer のアテンション層を設定します。文字列または文字列のリストで指定でき、“down”、“mid”、“up”、Transformer ブロック全体、または特定の Transformer ブロックのアテンション層を指定できます。例: [“mid”] [“down”, “mid”] [“down”, “mid”, “up.block_1”] [“down”, “mid”, “up.block_1.attentions_0”, “up.block_1.attentions_1”]

Kolors を使用したテキストから画像への生成を行う Pipeline です。

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

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

__call__

< >

( prompt: str | list[str] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50timesteps: list = Nonesigmas: list = Nonedenoising_end: float | None = Noneguidance_scale: float = 5.0negative_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] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = 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] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneoriginal_size: tuple[int, int] | None = Nonecrops_coords_top_left: tuple = (0, 0)target_size: tuple[int, int] | None = Nonenegative_original_size: tuple[int, int] | None = Nonenegative_crops_coords_top_left: tuple = (0, 0)negative_target_size: tuple[int, int] | None = Nonecallback_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']pag_scale: float = 3.0pag_adaptive_scale: float = 0.0max_sequence_length: int = 256 ) → ~pipelines.kolors.KolorsPipelineOutput or tuple

パラメータ

  • prompt (str または list[str]、省略可) — 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに prompt_embeds を渡す必要があります。
  • height (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor)— 生成される画像のピクセル単位の縦幅です。最適な結果を得るため、デフォルトでは 1024 に設定されています。 512 ピクセル未満の値は、Kwai-Kolors/Kolors-diffusers や、低解像度に特化してファインチューニングされていないチェックポイントでは適切に動作しません。
  • width (int, 任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) — 生成される画像の幅(ピクセル単位)です。最適な結果を得るため、デフォルトでは 1024 に設定されています。 512 ピクセル未満の値は、Kwai-Kolors/Kolors-diffusers や、低解像度に特化してファインチューニングされていないチェックポイントでは、適切に動作しません。
  • num_inference_steps (int、任意、デフォルト値は 50)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • timesteps (list[int], 任意) — timesteps 引数をサポートするスケジューラーの set_timesteps メソッドで、デノイジングプロセスに使用するカスタムタイムステップ。未定義の場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。降順で指定する必要があります。
  • sigmas (list[float]、任意) — set_timesteps メソッドで sigmas 引数を受け付けるスケジューラーにおいて、デノイジングプロセスに使用するカスタムのシグマです。定義されていない場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。
  • 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 のテキストと密接に関連する画像の生成が促されますが、通常は画像の品質が低下する傾向があります。
  • negative_prompt (str または list[str]、省略可) — 画像生成をガイドしないプロンプトです。未定義の場合、代わりに negative_prompt_embeds を渡す必要があります。ガイダンスを使用していない場合は無視されます(guidance_scale が 1 未満の場合は無視されます)。
  • 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 入力引数からテキスト埋め込みが生成されます。
  • pooled_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたプールのテキスト埋め込みです。テキスト入力の調整、例えばプロンプトの重み付けなどに簡単に利用できます。 指定されない場合、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 と組み合わせて使用する任意の画像入力です。
  • 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: PIL.Image.Image または np.array から選択します。
  • return_dict (bool、省略可能、デフォルトは True) — ~pipelines.kolors.KolorsPipelineOutput を返すか、プレーンなタプルを返すかを指定します。
  • cross_attention_kwargs (dict、省略可) — 指定された場合、diffusers.models.attention_processor で定義されている self.processor 配下の AttentionProcessor に渡される kwargs の辞書です。
  • 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 の一部です。
  • negative_original_size (tuple[int]、任意、デフォルト値は (1024, 1024)) — 特定の画像解像度に基づいて、生成プロセスをネガティブに条件付けするために使用します。これは、https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL の micro-conditioning の一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • negative_crops_coords_top_left (tuple[int]、任意、デフォルト値は (0, 0)) — 特定のクロップ座標に基づいて、生成プロセスをネガティブに条件付けするために使用します。これは、https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • negative_target_size (tuple[int]、任意、デフォルト値は (1024, 1024)) — ターゲット画像の解像度に基づいて、生成プロセスをネガティブに条件付けするために使用します。ほとんどの場合、target_size と同じ値である必要があります。https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • 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 属性にリストされている変数のみを、このリストに含めることができます。
  • pag_scale (float、任意、デフォルト値は 3.0) — Perturbed attention guidance のスケール係数です。0.0 に設定すると、perturbed attention guidance は使用されません。
  • pag_adaptive_scale (float, 任意、デフォルト値は 0.0) — パーターブド・アテンション・ガイダンス用の適応スケール係数です。0.0 に設定されている場合、pag_scale が使用されます。
  • max_sequence_length (int、デフォルトは 256) — prompt に使用する最大シーケンス長。

戻り値

~pipelines.kolors.KolorsPipelineOutput または tuple

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

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

例:

>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "Kwai-Kolors/Kolors-diffusers",
...     variant="fp16",
...     torch_dtype=torch.float16,
...     enable_pag=True,
...     pag_applied_layers=["down.block_2.attentions_1", "up.block_0.attentions_1"],
... )
>>> pipe = pipe.to("cuda")

>>> prompt = (
...     "A photo of a ladybug, macro, zoom, high quality, film, holding a wooden sign with the text 'KOLORS'"
... )
>>> image = pipe(prompt, guidance_scale=5.5, pag_scale=1.5).images[0]

encode_prompt

< >

( promptdevice: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1do_classifier_free_guidance: bool = Truenegative_prompt = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 256 )

パラメータ

  • prompt (str または list[str]、省略可能) — エンコードするプロンプト
  • 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 未満の場合は無視されます)。
  • prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt 入力引数からテキスト埋め込みが生成されます。
  • pooled_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたプールのテキスト埋め込みです。テキスト入力の調整、例えばプロンプトの重み付けなどに簡単に利用できます。 指定されない場合、prompt 入力引数からプールのテキスト埋め込みが生成されます。
  • negative_prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたネガティブなテキスト埋め込みです。テキスト入力の調整、例えばプロンプトの重み付けなどを簡単に実行できます。指定されない場合、negative_prompt 入力引数から negative_prompt_embeds が生成されます。
  • negative_pooled_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなプーリング済みテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、negative_prompt 入力引数からプーリング済み negative_prompt_embeds が生成されます。
  • max_sequence_length (int、デフォルトは 256) — prompt に使用する最大シーケンス長。

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

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 を参照してください。

StableDiffusionPAGInpaintPipeline

class diffusers.StableDiffusionPAGInpaintPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulerssafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilimage_encoder: CLIPVisionModelWithProjection = Nonerequires_safety_checker: bool = Truepag_applied_layers: str | list[str] = 'mid' )

パラメータ

  • 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の入力として使用されます。

Stable Diffusion を使用したテキストから画像への生成を行う Pipeline。

このモデルは 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]] = Nonemask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonemasked_image_latents: Tensor = Noneheight: int | None = Nonewidth: int | None = Nonepadding_mask_crop: int | None = Nonestrength: float = 0.9999num_inference_steps: int = 50timesteps: list = Nonesigmas: list = Noneguidance_scale: float = 7.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 = 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']pag_scale: float = 3.0pag_adaptive_scale: float = 0.0 ) → StableDiffusionPipelineOutput or tuple

パラメータ

  • prompt (str または list[str]、任意) — 画像生成をガイドするためのプロンプトです。未定義の場合、prompt_embeds を渡す必要があります。
  • image (torch.Tensor、PIL.Image.Image、np.ndarray、list[torch.Tensor]、list[PIL.Image.Image]、または list[np.ndarray]) — インペイントする(mask_image でマスクアウトする部分と、prompt に従って再描画する部分)画像バッチを表す Image、NumPy 配列、またはテンソル。
  • mask_image (torch.Tensor、PIL.Image.Image、np.ndarray、list[torch.Tensor]、list[PIL.Image.Image]、または list[np.ndarray]) — image をマスクするための Image、NumPy 配列、またはテンソル。マスク内の白いピクセルは再描画され、黒いピクセルは保持されます。mask_image が PIL イメージの場合、使用の前に単一チャネル(輝度)に変換されます。NumPy 配列または PyTorch テンソルの場合は、3 チャネルではなく 1 つの色チャネル(L)を含む必要があります。したがって、PyTorch テンソルの想定される形状は (B, 1, H, W)、(B, H, W)、(1, H, W)、(H, W) となります。NumPy 配列の場合は (B, H, W, 1)、(B, H, W)、(H, W, 1)、または (H, W) となります。
  • masked_image_latents (torch.Tensor, 任意) — マスクされた画像の事前エンコード済み潜在変数(インペインティング用)。
  • height (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) — 生成される画像のピクセル単位の縦幅です。
  • width (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) — 生成される画像の幅(ピクセル単位)。
  • padding_mask_crop (int、任意、デフォルトは None) — 画像とマスクに適用されるクロップの余白サイズです。None の場合、画像および mask_image にはクロップが適用されません。padding_mask_crop が None でない場合、まず画像と同じアスペクト比を持ち、すべてのマスク領域を含む長方形領域を特定し、その後 padding_mask_crop に基づいてその領域を拡大します。その後、インペインティングのために元の画像サイズにリサイズする前に、拡大された領域に基づいて画像と mask_image がクロップされます。これは、マスク領域が小さく、画像が大きく、インペインティングに関連しない情報(背景など)を含む場合に有用です。
  • strength (float、任意、デフォルト値は 0.9999) — 参照となるimageの変換の度合いを示します。0 から 1 の間の値である必要があります。imageが起点として使用され、strengthが大きいほど多くのノイズが追加されます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。strengthが 1 の場合、追加されるノイズは最大となり、デノイジングプロセスはnum_inference_stepsで指定された全イテレーション数分実行されます。値が 1 の場合、imageは実質的に無視されます。
  • num_inference_steps (int、任意、デフォルト値は 50)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • timesteps (list[int], 任意) — timesteps 引数をサポートするスケジューラーの set_timesteps メソッドで、デノイジングプロセスに使用するカスタムタイムステップ。未定義の場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。降順で指定する必要があります。
  • sigmas (list[float]、任意) — set_timesteps メソッドで sigmas 引数を受け付けるスケジューラーにおいて、デノイジングプロセスに使用するカスタムのシグマです。定義されていない場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。
  • guidance_scale (float、任意、デフォルト値は 7.5) — guidance scale の値を高くすると、画像の品質が低下する代わりに、prompt と密接に関連した画像を生成するようモデルが促されます。guidance_scale > 1 の場合、guidance scale が有効になります。
  • 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 または list[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 を返すかどうかを指定します。
  • 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、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 属性にリストされている変数のみを、このリストに含めることができます。
  • pag_scale (float、任意、デフォルト値は 3.0) — Perturbed attention guidance のスケール係数です。0.0 に設定すると、perturbed attention guidance は使用されません。
  • pag_adaptive_scale (float, 任意、デフォルト値は 0.0) — パーターブド・アテンション・ガイダンス用の適応スケール係数です。0.0 に設定されている場合、pag_scale が使用されます。

戻り値

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 torch
>>> from diffusers import AutoPipelineForInpainting

>>> pipe = AutoPipelineForInpainting.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, enable_pag=True
... )
>>> pipe = pipe.to("cuda")
>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
>>> init_image = load_image(img_url).convert("RGB")
>>> mask_image = load_image(mask_url).convert("RGB")
>>> prompt = "A majestic tiger sitting on a bench"
>>> image = pipe(
...     prompt=prompt,
...     image=init_image,
...     mask_image=mask_image,
...     strength=0.8,
...     num_inference_steps=50,
...     guidance_scale=guidance_scale,
...     generator=generator,
...     pag_scale=pag_scale,
... ).images[0]

encode_prompt

< >

( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

パラメータ

  • prompt (str または list[str]、省略可能) — エンコードするプロンプト
  • 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 未満の場合は無視されます)。
  • 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 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。

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

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 を参照してください。

StableDiffusionPAGPipeline

class diffusers.StableDiffusionPAGPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulerssafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilimage_encoder: CLIPVisionModelWithProjection = Nonerequires_safety_checker: bool = Truepag_applied_layers: str | list[str] = 'mid' )

パラメータ

  • 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の入力として使用されます。

Stable Diffusion を使用したテキストから画像への生成を行う Pipeline。

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

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

__call__

< >

( prompt: str | list[str] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50timesteps: list = Nonesigmas: list = Noneguidance_scale: float = 7.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 = 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']pag_scale: float = 3.0pag_adaptive_scale: float = 0.0 ) → StableDiffusionPipelineOutput or tuple

パラメータ

  • prompt (str または list[str]、任意) — 画像生成をガイドするためのプロンプトです。未定義の場合、prompt_embeds を渡す必要があります。
  • 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)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • timesteps (list[int], 任意) — timesteps 引数をサポートするスケジューラーの set_timesteps メソッドで、デノイジングプロセスに使用するカスタムタイムステップ。未定義の場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。降順で指定する必要があります。
  • sigmas (list[float]、任意) — set_timesteps メソッドで sigmas 引数を受け付けるスケジューラーにおいて、デノイジングプロセスに使用するカスタムのシグマです。定義されていない場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。
  • guidance_scale (float、任意、デフォルト値は 7.5) — guidance scale の値を高くすると、画像の品質が低下する代わりに、prompt と密接に関連した画像を生成するようモデルが促されます。guidance_scale > 1 の場合、guidance scale が有効になります。
  • 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 または list[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 を返すかどうかを指定します。
  • 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、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 属性にリストされている変数のみを、このリストに含めることができます。
  • pag_scale (float、任意、デフォルト値は 3.0) — Perturbed attention guidance のスケール係数です。0.0 に設定すると、perturbed attention guidance は使用されません。
  • pag_adaptive_scale (float, 任意、デフォルト値は 0.0) — パーターブド・アテンション・ガイダンス用の適応スケール係数です。0.0 に設定されている場合、pag_scale が使用されます。

戻り値

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 torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, enable_pag=True
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, pag_scale=0.3).images[0]

encode_prompt

< >

( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

パラメータ

  • prompt (str または list[str]、省略可能) — エンコードするプロンプト
  • 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 未満の場合は無視されます)。
  • 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 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。

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

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 を参照してください。

StableDiffusionPAGImg2ImgPipeline

class diffusers.StableDiffusionPAGImg2ImgPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulerssafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilimage_encoder: CLIPVisionModelWithProjection = Nonerequires_safety_checker: bool = Truepag_applied_layers: str | list[str] = 'mid' )

パラメータ

  • 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の入力として使用されます。

Stable Diffusion を使用したテキストガイド付きの画像から画像への生成を行う Pipeline。

このモデルは 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]] = Nonestrength: float = 0.8num_inference_steps: int | None = 50timesteps: list = Nonesigmas: list = Noneguidance_scale: float | None = 7.5negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float | None = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = 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 = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int = Nonecallback_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']pag_scale: float = 3.0pag_adaptive_scale: float = 0.0 ) → StableDiffusionPipelineOutput or tuple

パラメータ

  • prompt (str または list[str]、任意) — 画像生成をガイドするためのプロンプトです。未定義の場合、prompt_embeds を渡す必要があります。
  • 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) です。画像の潜在変数も image として受け取れますが、潜在変数を直接渡す場合は、再度エンコードされません。
  • strength (float、任意、デフォルト値は 0.8) — 参照となるimageの変換の度合いを示します。0 から 1 の間の値である必要があります。imageが起点として使用され、strengthが大きいほど多くのノイズが追加されます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。strengthが 1 の場合、追加されるノイズは最大となり、デノイジングプロセスはnum_inference_stepsで指定された全イテレーション数分実行されます。値が 1 の場合、imageは実質的に無視されます。
  • num_inference_steps (int、任意、デフォルト値は 50)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。このパラメータは strength によって調整されます。
  • timesteps (list[int], 任意) — timesteps 引数をサポートするスケジューラーの set_timesteps メソッドで、デノイジングプロセスに使用するカスタムタイムステップ。未定義の場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。降順で指定する必要があります。
  • sigmas (list[float]、任意) — set_timesteps メソッドで sigmas 引数を受け付けるスケジューラーにおいて、デノイジングプロセスに使用するカスタムのシグマです。定義されていない場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。
  • guidance_scale (float、任意、デフォルト値は 7.5) — guidance scale の値を高くすると、画像の品質が低下する代わりに、prompt と密接に関連した画像を生成するようモデルが促されます。guidance_scale > 1 の場合、guidance scale が有効になります。
  • 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 または list[torch.Generator]、省略可) — 生成を決定論的にするための torch.Generator。
  • 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 を返すかどうかを指定します。
  • cross_attention_kwargs (dict, 任意) — 指定された場合、self.processor で定義されている AttentionProcessor に渡される kwargs の辞書です。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。
  • 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 属性にリストされている変数のみを、このリストに含めることができます。
  • pag_scale (float、任意、デフォルト値は 3.0) — Perturbed attention guidance のスケール係数です。0.0 に設定すると、perturbed attention guidance は使用されません。
  • pag_adaptive_scale (float, 任意、デフォルト値は 0.0) — パーターブド・アテンション・ガイダンス用の適応スケール係数です。0.0 に設定されている場合、pag_scale が使用されます。

戻り値

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 torch
>>> from diffusers import AutoPipelineForImage2Image
>>> from diffusers.utils import load_image

>>> pipe = AutoPipelineForImage2Image.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"

>>> init_image = load_image(url).convert("RGB")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, image=init_image, pag_scale=0.3).images[0]

encode_prompt

< >

( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

パラメータ

  • prompt (str または list[str]、省略可能) — エンコードするプロンプト
  • 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 未満の場合は無視されます)。
  • 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 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。

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

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 を参照してください。

StableDiffusionControlNetPAGPipeline

クラス diffusers.StableDiffusionControlNetPAGPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModelcontrolnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModelscheduler: KarrasDiffusionSchedulerssafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilimage_encoder: CLIPVisionModelWithProjection = Nonerequires_safety_checker: bool = Truepag_applied_layers: str | list[str] = 'mid' )

パラメータ

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

ControlNetによるガイダンスを用いたStable Diffusionのテキストから画像への生成を行うPipeline。

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

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

encode_prompt

< >

( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

パラメータ

  • prompt (str または list[str]、省略可能) — エンコードするプロンプト
  • 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 未満の場合は無視されます)。
  • 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 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。

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

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 を参照してください。

StableDiffusionControlNetPAGInpaintPipeline

クラス diffusers.StableDiffusionControlNetPAGInpaintPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModelcontrolnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModelscheduler: KarrasDiffusionSchedulerssafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilimage_encoder: CLIPVisionModelWithProjection = Nonerequires_safety_checker: bool = Truepag_applied_layers: str | list[str] = 'mid' )

パラメータ

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

ControlNetのガイダンスを用いたStable Diffusionによる画像インペインティングのパイプライン。

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

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

> このパイプラインは、インペインティング用に特別にファインチューニングされたチェックポイント > (stable-diffusion-v1-5/stable-diffusion-inpainting) および > デフォルトのテキストから画像への変換 Stable Diffusion チェックポイント > (stable-diffusion-v1-5/stable-diffusion-v1-5) と使用できます。 デフォルトのテキストから画像への変換 > Stable Diffusion チェックポイントは、それらでファインチューニングされた ControlNet、例えば > lllyasviel/control_v11p_sd15_inpaint のようなものに対して、より好ましい場合があります。

__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]] = Nonemask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonecontrol_image: 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 = Nonepadding_mask_crop: int | None = Nonestrength: float = 1.0num_inference_steps: int = 50guidance_scale: float = 7.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 = Truecross_attention_kwargs: dict[str, typing.Any] | None = Nonecontrolnet_conditioning_scale: float | list[float] = 0.5control_guidance_start: float | list[float] = 0.0control_guidance_end: float | list[float] = 1.0clip_skip: int | None = Nonecallback_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']pag_scale: float = 3.0pag_adaptive_scale: float = 0.0 ) → StableDiffusionPipelineOutput or tuple

パラメータ

  • prompt (str または list[str]、任意) — 画像生成をガイドするためのプロンプトです。未定義の場合、prompt_embeds を渡す必要があります。
  • 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) です。また、image として画像の潜在変数(latents)を受け取ることができますが、潜在変数を直接渡す場合は、再度エンコードされません。
  • mask_image (torch.Tensor、PIL.Image.Image、np.ndarray、list[torch.Tensor]、list[PIL.Image.Image]、または list[np.ndarray]): Image、NumPy 配列、または image をマスクする画像バッチを表すテンソル。マスク内の白いピクセルは再描画され、黒いピクセルは保持されます。mask_image が PIL 画像の場合、使用前に単一チャネル(輝度)に変換されます。NumPy 配列または PyTorch テンソルの場合は、3 チャネルではなく 1 つの色チャネル(L)を含む必要があります。したがって、PyTorch テンソルの想定される形状は (B, 1, H, W)、(B, H, W)、(1, H, W)、(H, W) となります。NumPy 配列の場合は、(B, H, W, 1)、(B, H, W)、(H, W, 1)、または (H, W) となります。
  • control_image (torch.Tensor, PIL.Image.Image, list[torch.Tensor], list[PIL.Image.Image], — list[list[torch.Tensor]] または list[list[PIL.Image.Image]]): 生成時に unet へガイダンスを与えるための ControlNet の入力条件です。型が torch.Tensor として指定されている場合、ControlNet にそのまま渡されます。画像として PIL.Image.Image も受け付けられます。出力画像の寸法はデフォルトで image の寸法になります。 height と/または width が渡された場合、image はそれに合わせてリサイズされます。 init で複数の ControlNet が指定されている場合、リストとして画像を渡す必要があり、 リストの各要素が単一の ControlNet への入力として正しくバッチ処理できるようにしてください。
  • height (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) — 生成される画像のピクセル単位の縦幅です。
  • width (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) — 生成される画像の幅(ピクセル単位)。
  • padding_mask_crop (int、任意、デフォルトは None) — 画像とマスクに適用されるクロップの余白サイズです。None の場合、画像および mask_image にはクロップが適用されません。padding_mask_crop が None でない場合、まず画像と同じアスペクト比を持ち、すべてのマスク領域を含む長方形領域を特定し、その後 padding_mask_crop に基づいてその領域を拡大します。その後、インペインティングのために元の画像サイズにリサイズする前に、拡大された領域に基づいて画像と mask_image がクロップされます。これは、マスク領域が小さく、画像が大きく、インペインティングに関連しない情報(背景など)を含む場合に有用です。
  • strength (float、任意、デフォルト値は 1.0) — 参照となるimageの変換の度合いを示します。0 から 1 の間の値である必要があります。imageが起点として使用され、strengthが大きいほど多くのノイズが追加されます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。strengthが 1 の場合、追加されるノイズは最大となり、デノイジングプロセスはnum_inference_stepsで指定された全イテレーション数分実行されます。値が 1 の場合、imageは実質的に無視されます。
  • num_inference_steps (int、任意、デフォルト値は 50)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • guidance_scale (float、任意、デフォルト値は 7.5) — guidance scale の値を高くすると、画像の品質が低下する代わりに、prompt と密接に関連した画像を生成するようモデルが促されます。guidance_scale > 1 の場合、guidance scale が有効になります。
  • 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 または list[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 を返すかどうかを指定します。
  • cross_attention_kwargs (dict, 任意) — 指定された場合、self.processor で定義されている AttentionProcessor に渡される kwargs の辞書です。
  • controlnet_conditioning_scale (float または list[float]、任意、デフォルト値は 0.5) — ControlNet の出力は、元の unet の残差に加算される前に、controlnet_conditioning_scale 倍されます。init で複数の ControlNet が指定されている場合、対応するスケールをリストとして設定できます。
  • control_guidance_start (float または list[float]、任意、デフォルト値は 0.0) — ControlNet が適用を開始するステップの割合(全体のステップ数に対するパーセンテージ)です。
  • control_guidance_end (float または list[float]、任意、デフォルト値は 1.0) — ControlNet が適用を停止するステップの割合です。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。
  • 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 属性にリストされている変数のみを、このリストに含めることができます。
  • pag_scale (float、任意、デフォルト値は 3.0) — Perturbed attention guidance のスケール係数です。0.0 に設定すると、perturbed attention guidance は使用されません。
  • pag_adaptive_scale (float, 任意、デフォルト値は 0.0) — パーターブド・アテンション・ガイダンス用の適応スケール係数です。0.0 に設定されている場合、pag_scale が使用されます。

戻り値

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 への呼び出し関数。

例:

>>> # !pip install transformers accelerate
>>> import cv2
>>> from diffusers import AutoPipelineForInpainting, ControlNetModel, DDIMScheduler
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> from PIL import Image
>>> import torch

>>> init_image = load_image(
...     "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy.png"
... )
>>> init_image = init_image.resize((512, 512))

>>> generator = torch.Generator(device="cpu").manual_seed(1)

>>> mask_image = load_image(
...     "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy_mask.png"
... )
>>> mask_image = mask_image.resize((512, 512))


>>> def make_canny_condition(image):
...     image = np.array(image)
...     image = cv2.Canny(image, 100, 200)
...     image = image[:, :, None]
...     image = np.concatenate([image, image, image], axis=2)
...     image = Image.fromarray(image)
...     return image


>>> control_image = make_canny_condition(init_image)

>>> controlnet = ControlNetModel.from_pretrained(
...     "lllyasviel/control_v11p_sd15_inpaint", torch_dtype=torch.float16
... )
>>> pipe = AutoPipelineForInpainting.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     controlnet=controlnet,
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )

>>> pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
>>> pipe.enable_model_cpu_offload()

>>> # generate image
>>> image = pipe(
...     "a handsome man with ray-ban sunglasses",
...     num_inference_steps=20,
...     generator=generator,
...     eta=1.0,
...     image=init_image,
...     mask_image=mask_image,
...     control_image=control_image,
...     pag_scale=0.3,
... ).images[0]

encode_prompt

< >

( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

パラメータ

  • prompt (str または list[str]、省略可能) — エンコードするプロンプト
  • 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 未満の場合は無視されます)。
  • 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 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。

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

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 を参照してください。

StableDiffusionXLPAGPipeline

class diffusers.StableDiffusionXLPAGPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulersimage_encoder: CLIPVisionModelWithProjection = Nonefeature_extractor: CLIPImageProcessorPil = Noneforce_zeros_for_empty_prompt: bool = Trueadd_watermarker: bool | None = Nonepag_applied_layers: str | list[str] = 'mid' )

パラメータ

  • 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 のいずれかです。
  • force_zeros_for_empty_prompt (bool、省略可、デフォルトは "True") — ネガティブプロンプトの埋め込みを常に 0 に設定するかどうか。stabilityai/stable-diffusion-xl-base-1-0 の設定も参照してください。
  • add_watermarker (bool、省略可) — invisible_watermark ライブラリを使用して出力画像にウォーターマークを付与するかどうかを指定します。未定義の場合、パッケージがインストールされていれば True がデフォルトとなり、インストールされていなければウォーターマークは付与されません。

Stable Diffusion XL を使用したテキストから画像への生成を行う Pipeline。

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

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

__call__

< >

( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50timesteps: list = Nonesigmas: list = Nonedenoising_end: float | None = Noneguidance_scale: float = 5.0negative_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] = 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 = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneguidance_rescale: float = 0.0original_size: tuple[int, int] | None = Nonecrops_coords_top_left: tuple = (0, 0)target_size: tuple[int, int] | None = Nonenegative_original_size: tuple[int, int] | None = Nonenegative_crops_coords_top_left: tuple = (0, 0)negative_target_size: tuple[int, int] | None = Noneclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']pag_scale: float = 3.0pag_adaptive_scale: float = 0.0 ) → ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput or tuple

パラメータ

  • prompt (str または list[str]、省略可) — 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに prompt_embeds を渡す必要があります。
  • prompt_2 (str または list[str]、省略可) — tokenizer_2 および text_encoder_2 に送信するプロンプトです。定義されていない場合、両方のテキストエンコーダーに prompt が使用されます。
  • height (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor)— 生成される画像のピクセル単位の縦幅です。最適な結果を得るため、デフォルトでは 1024 に設定されています。 512 ピクセル未満の値は、stabilityai/stable-diffusion-xl-base-1.0 や、低解像度に特化してファインチューニングされていないチェックポイントではうまく機能しません。
  • width (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) — 生成される画像の幅(ピクセル単位)です。最適な結果を得るため、デフォルトでは 1024 に設定されています。 512 ピクセル未満の値は、stabilityai/stable-diffusion-xl-base-1.0 や、低解像度に特化してファインチューニングされていないチェックポイントでは、適切に動作しません。
  • num_inference_steps (int、任意、デフォルト値は 50)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • timesteps (list[int], 任意) — timesteps 引数をサポートするスケジューラーの set_timesteps メソッドで、デノイジングプロセスに使用するカスタムタイムステップ。未定義の場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。降順で指定する必要があります。
  • sigmas (list[float]、任意) — set_timesteps メソッドで sigmas 引数を受け付けるスケジューラーにおいて、デノイジングプロセスに使用するカスタムのシグマです。定義されていない場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。
  • 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 のテキストと密接に関連する画像の生成が促されますが、通常は画像の品質が低下する傾向があります。
  • 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 が生成されます。
  • 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: 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.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 の一部です。
  • negative_original_size (tuple[int]、任意、デフォルト値は (1024, 1024)) — 特定の画像解像度に基づいて、生成プロセスをネガティブに条件付けするために使用します。これは、https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL の micro-conditioning の一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • negative_crops_coords_top_left (tuple[int]、任意、デフォルト値は (0, 0)) — 特定のクロップ座標に基づいて、生成プロセスをネガティブに条件付けするために使用します。これは、https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • negative_target_size (tuple[int]、任意、デフォルト値は (1024, 1024)) — ターゲット画像の解像度に基づいて、生成プロセスをネガティブに条件付けするために使用します。ほとんどの場合、target_size と同じ値である必要があります。https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • 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 属性にリストされている変数のみを、このリストに含めることができます。
  • pag_scale (float、任意、デフォルト値は 3.0) — Perturbed attention guidance のスケール係数です。0.0 に設定すると、perturbed attention guidance は使用されません。
  • pag_adaptive_scale (float, 任意、デフォルト値は 0.0) — パーターブド・アテンション・ガイダンス用の適応スケール係数です。0.0 に設定されている場合、pag_scale が使用されます。

戻り値

~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput または tuple

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

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

例:

>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, pag_scale=0.3).images[0]

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 = Noneclip_skip: int | 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 スケールです。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。

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

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 を参照してください。

StableDiffusionXLPAGImg2ImgPipeline

class diffusers.StableDiffusionXLPAGImg2ImgPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulersimage_encoder: CLIPVisionModelWithProjection = Nonefeature_extractor: CLIPImageProcessorPil = Nonerequires_aesthetics_score: bool = Falseforce_zeros_for_empty_prompt: bool = Trueadd_watermarker: bool | None = Nonepag_applied_layers: str | list[str] = 'mid' )

パラメータ

  • 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 がデフォルトとなり、インストールされていなければウォーターマークは付与されません。

Stable Diffusion XL を使用したテキストから画像への生成を行う Pipeline。

このモデルは 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]] = Nonestrength: float = 0.3num_inference_steps: int = 50timesteps: list = Nonesigmas: list = Nonedenoising_start: float | None = Nonedenoising_end: float | None = Noneguidance_scale: float = 5.0negative_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] = 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 = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneguidance_rescale: float = 0.0original_size: tuple = Nonecrops_coords_top_left: tuple = (0, 0)target_size: tuple = Nonenegative_original_size: tuple[int, int] | None = Nonenegative_crops_coords_top_left: tuple = (0, 0)negative_target_size: tuple[int, int] | None = Noneaesthetic_score: float = 6.0negative_aesthetic_score: float = 2.5clip_skip: int | None = Nonecallback_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']pag_scale: float = 3.0pag_adaptive_scale: float = 0.0 ) → ~pipelines.stable_diffusion.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]) — パイプラインで修正する画像です。
  • strength (float、任意、デフォルト値は 0.3) — 概念的には、参照となるimageをどの程度変換するかを示します。0 から 1 の間の値である必要があります。image は開始点として使用され、strengthが大きいほど、それに加えられるノイズ量が増えます。 デノイジングのステップ数は、最初に追加されるノイズ量に依存します。strengthが 1 の場合、 追加されるノイズは最大となり、デノイジングプロセスはnum_inference_stepsで指定された 全イテレーション数分実行されます。したがって、値が 1 の場合、imageは実質的に無視されます。 denoising_startが整数として宣言されている場合、strengthの値は無視されることに注意してください。
  • num_inference_steps (int、任意、デフォルト値は 50)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • timesteps (list[int], 任意) — timesteps 引数をサポートするスケジューラーの set_timesteps メソッドで、デノイジングプロセスに使用するカスタムタイムステップ。未定義の場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。降順で指定する必要があります。
  • sigmas (list[float]、任意) — set_timesteps メソッドで sigmas 引数を受け付けるスケジューラーにおいて、デノイジングプロセスに使用するカスタムのシグマです。定義されていない場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。
  • denoising_start (float, 任意) — 指定された場合、デノイジングプロセス全体のうち、開始前にバイパスされる割合(0.0 から 1.0 の間)を示します。これにより、デノイジングプロセスの初期部分がスキップされ、渡された image が部分的にデノイジングされた画像であるとみなされます。なお、このパラメータが指定されると、strength は無視されます。denoising_start パラメータは、画像品質の向上 に詳述されている「Mixture of Denoisers」マルチパイプライン構成にこのパイプラインを統合する場合に特に有用です。
  • denoising_end (float, 任意) — 指定された場合、デノイジング全体のどの割合(0.0 から 1.0 の間)まで完了した時点で、意図的に早期に終了させるかを決定します。その結果、返されるサンプルには依然としてかなりの量のノイズ(おおよそ最後の 20% のタイムステップ分)が残っており、denoising_start が 0.8 に設定された後続のパイプラインによってデノイジングされるべきです。これにより、スケジューラの最後の 20% のみデノイジングされます。denoising_end パラメータは、画像品質の向上 に詳述されている「Mixture of Denoisers」マルチパイプライン構成の一部としてこのパイプラインが機能する場合に、理想的には利用されるべきです。
  • guidance_scale (float、任意、デフォルト値は 7.5) — Classifier-Free Diffusion Guidance で定義されているガイダンススケールです。guidance_scale は、Imagen Paper の数式 2 の w として定義されています。guidance_scale > 1 を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、prompt のテキストと密接に関連した画像の生成が促されますが、通常は画像の品質が低下する傾向があります。
  • 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 が生成されます。
  • 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: PIL.Image.Image または np.array から選択します。
  • return_dict (bool、任意、デフォルトは True) — ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput を返すか、それとも通常のタプルを返すかを指定します。
  • 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 の一部です。
  • negative_original_size (tuple[int]、任意、デフォルト値は (1024, 1024)) — 特定の画像解像度に基づいて、生成プロセスをネガティブに条件付けするために使用します。これは、https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL の micro-conditioning の一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • negative_crops_coords_top_left (tuple[int]、任意、デフォルト値は (0, 0)) — 特定のクロップ座標に基づいて、生成プロセスをネガティブに条件付けするために使用します。これは、https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • negative_target_size (tuple[int]、任意、デフォルト値は (1024, 1024)) — ターゲット画像の解像度に基づいて、生成プロセスをネガティブに条件付けするために使用します。ほとんどの場合、target_size と同じ値である必要があります。https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • aesthetic_score (float、任意、デフォルト値は 6.0) — 正のテキスト条件に影響を与えることで、生成された画像の美観スコアをシミュレートするために使用されます。 https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。
  • negative_aesthetic_score (float、任意、デフォルト値: 2.5) — https://huggingface.co/papers/2307.01952のセクション 2.2 で説明されている SDXL のマイクロコンディショニングの一部です。ネガティブなテキスト条件に影響を与えることで、生成された画像の美観スコアをシミュレートするために使用できます。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。
  • 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 属性にリストされている変数のみを、このリストに含めることができます。
  • pag_scale (float、任意、デフォルト値は 3.0) — Perturbed attention guidance のスケール係数です。0.0 に設定すると、perturbed attention guidance は使用されません。
  • pag_adaptive_scale (float, 任意、デフォルト値は 0.0) — パーターブド・アテンション・ガイダンス用の適応スケール係数です。0.0 に設定されている場合、pag_scale が使用されます。

戻り値

~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput または tuple

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

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

例:

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

>>> pipe = AutoPipelineForImage2Image.from_pretrained(
...     "stabilityai/stable-diffusion-xl-refiner-1.0",
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"

>>> init_image = load_image(url).convert("RGB")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, image=init_image, pag_scale=0.3).images[0]

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 = Noneclip_skip: int | 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 スケールです。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。

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

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 を参照してください。

StableDiffusionXLPAGInpaintPipeline

class diffusers.StableDiffusionXLPAGInpaintPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulersimage_encoder: CLIPVisionModelWithProjection = Nonefeature_extractor: CLIPImageProcessorPil = Nonerequires_aesthetics_score: bool = Falseforce_zeros_for_empty_prompt: bool = Trueadd_watermarker: bool | None = Nonepag_applied_layers: str | list[str] = 'mid' )

パラメータ

  • 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 がデフォルトとなり、インストールされていなければウォーターマークは付与されません。

Stable Diffusion XL を使用したテキストから画像への生成を行う Pipeline。

このモデルは 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]] = Nonemask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonemasked_image_latents: Tensor = Noneheight: int | None = Nonewidth: int | None = Nonepadding_mask_crop: int | None = Nonestrength: float = 0.9999num_inference_steps: int = 50timesteps: list = Nonesigmas: list = Nonedenoising_start: float | None = Nonedenoising_end: float | None = Noneguidance_scale: float = 7.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] = 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 = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneguidance_rescale: float = 0.0original_size: tuple = Nonecrops_coords_top_left: tuple = (0, 0)target_size: tuple = Nonenegative_original_size: tuple[int, int] | None = Nonenegative_crops_coords_top_left: tuple = (0, 0)negative_target_size: tuple[int, int] | None = Noneaesthetic_score: float = 6.0negative_aesthetic_score: float = 2.5clip_skip: int | None = Nonecallback_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']pag_scale: float = 3.0pag_adaptive_scale: float = 0.0 ) → ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput or tuple

パラメータ

  • prompt (str または list[str]、省略可) — 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに prompt_embeds を渡す必要があります。
  • prompt_2 (str または list[str]、省略可) — tokenizer_2 および text_encoder_2 に送信するプロンプトです。定義されていない場合、両方のテキストエンコーダーに prompt が使用されます。
  • image (PIL.Image.Image) — インペイント対象のImage、または画像バッチを表すテンソル。つまり、画像の一部がmask_imageでマスクされ、promptに従って再描画されます。
  • mask_image (PIL.Image.Image) — Image、または画像バッチを表すテンソルで、image をマスクするために使用します。マスク内の白いピクセルは再描画され、黒いピクセルは保持されます。mask_image が PIL 画像の場合、使用前に単一チャネル(輝度)に変換されます。テンソルの場合は、3 チャネルではなく 1 つの色チャネル(L)を含む必要があるため、期待される形状は (B, H, W, 1) になります。
  • masked_image_latents (torch.Tensor, 任意) — マスクされた画像の事前エンコード済み潜在変数(インペインティング用)。
  • height (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor)— 生成される画像のピクセル単位の縦幅です。最適な結果を得るため、デフォルトでは 1024 に設定されています。 512 ピクセル未満の値は、stabilityai/stable-diffusion-xl-base-1.0 や、低解像度に特化してファインチューニングされていないチェックポイントではうまく機能しません。
  • width (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) — 生成される画像の幅(ピクセル単位)です。最適な結果を得るため、デフォルトでは 1024 に設定されています。 512 ピクセル未満の値は、stabilityai/stable-diffusion-xl-base-1.0 や、低解像度に特化してファインチューニングされていないチェックポイントでは、適切に動作しません。
  • padding_mask_crop (int、任意、デフォルトは None) — 画像とマスクに適用されるクロップの余白サイズです。None の場合、画像および mask_image にはクロップが適用されません。padding_mask_crop が None でない場合、まず画像と同じアスペクト比を持ち、すべてのマスク領域を含む長方形領域を特定し、その後 padding_mask_crop に基づいてその領域を拡大します。その後、インペインティングのために元の画像サイズにリサイズする前に、拡大された領域に基づいて画像と mask_image がクロップされます。これは、マスク領域が小さく、画像が大きく、インペインティングに関連しない情報(背景など)を含む場合に有用です。
  • strength (float、任意、デフォルト値は 0.9999) — 概念的には、参照imageのマスクされた部分をどの程度変換するかを示します。0 から 1 の間の値である必要があります。imageが起点として使用され、strengthが大きいほど、それにより多くのノイズが加えられます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。strengthが 1 の場合、加えられるノイズは最大となり、デノイジングプロセスはnum_inference_stepsで指定された全イテレーション数分実行されます。したがって、値が 1 である場合、参照imageのマスクされた部分は実質的に無視されます。denoising_startが整数として宣言されている場合、strengthの値は無視されることに注意してください。
  • num_inference_steps (int、任意、デフォルト値は 50)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • timesteps (list[int], 任意) — timesteps 引数をサポートするスケジューラーの set_timesteps メソッドで、デノイジングプロセスに使用するカスタムタイムステップ。未定義の場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。降順で指定する必要があります。
  • sigmas (list[float]、任意) — set_timesteps メソッドで sigmas 引数を受け付けるスケジューラーにおいて、デノイジングプロセスに使用するカスタムのシグマです。定義されていない場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。
  • denoising_start (float, 任意) — 指定した場合、デノイジング全体のどの割合(0.0 から 1.0 の間)をスキップしてから開始するかを示します。これにより、デノイジングプロセスの初期部分がスキップされ、渡された image が部分的にデノイズされた画像であるとみなされます。なお、このパラメータが指定されると、strength は無視されます。denoising_start パラメータは、画像出力の洗練 に詳述されている「Mixture of Denoisers」マルチパイプライン構成にこのパイプラインを統合する場合に特に有用です。
  • denoising_end (float, 任意) — 指定された場合、デノイジング全体のどの割合(0.0 から 1.0 の間)まで完了した時点で、意図的に処理を早期終了させるかを決定します。その結果、返されるサンプルには依然としてかなりの量のノイズ(最終的なタイムステップの約 20% 分)が残っており、denoising_start が 0.8 に設定された後続のパイプラインによってデノイズされるべきです。これにより、スケジューラの最終 20% の部分のみがデノイズされます。denoising_end パラメータは、画像出力の洗練 に詳述されている「Mixture of Denoisers」マルチパイプライン構成の一部としてこのパイプラインが機能する場合に、理想的には利用されるべきです。
  • guidance_scale (float、任意、デフォルト値は 7.5) — Classifier-Free Diffusion Guidance で定義されているガイダンススケールです。guidance_scale は、Imagen Paper の数式 2 の w として定義されています。guidance_scale > 1 を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、prompt のテキストと密接に関連した画像の生成が促されますが、通常は画像の品質が低下する傾向があります。
  • 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 が生成されます。
  • 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 入力引数から埋め込みが計算されます。
  • num_images_per_prompt (int、任意、デフォルトは 1) — プロンプトごとに生成する画像の数。
  • eta (float、省略可、デフォルト値は 0.0) — DDIM 論文におけるパラメータ eta (η) に相当します: https://huggingface.co/papers/2010.02502。 schedulers.DDIMScheduler にのみ適用され、それ以外の場合は無視されます。
  • generator (torch.Generator、省略可) — 生成を決定論的にするためのtorch ジェネレーター1つまたはリスト。
  • latents (torch.Tensor, 任意) — 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイズ付き潜在変数。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムgeneratorを使用してサンプリングを行い、潜在変数テンソルが生成されます。
  • output_type (str、任意、デフォルトは "pil") — 画像生成の出力形式です。PIL: PIL.Image.Image または np.array から選択します。
  • return_dict (bool、任意、デフォルトは True) — プレーンなタプルではなく StableDiffusionPipelineOutput を返すかどうかを指定します。
  • cross_attention_kwargs (dict、省略可) — 指定された場合、diffusers.models.attention_processor で定義されている self.processor 配下の AttentionProcessor に渡される kwargs の辞書です。
  • 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 の一部です。
  • negative_original_size (tuple[int]、任意、デフォルト値は (1024, 1024)) — 特定の画像解像度に基づいて、生成プロセスをネガティブに条件付けするために使用します。これは、https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL の micro-conditioning の一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • negative_crops_coords_top_left (tuple[int]、任意、デフォルト値は (0, 0)) — 特定のクロップ座標に基づいて、生成プロセスをネガティブに条件付けするために使用します。これは、https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • negative_target_size (tuple[int]、任意、デフォルト値は (1024, 1024)) — ターゲット画像の解像度に基づいて、生成プロセスをネガティブに条件付けするために使用します。ほとんどの場合、target_size と同じ値である必要があります。https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • aesthetic_score (float、任意、デフォルト値は 6.0) — 正のテキスト条件に影響を与えることで、生成された画像の美観スコアをシミュレートするために使用されます。 https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。
  • negative_aesthetic_score (float、任意、デフォルト値: 2.5) — https://huggingface.co/papers/2307.01952のセクション 2.2 で説明されている SDXL のマイクロコンディショニングの一部です。ネガティブなテキスト条件に影響を与えることで、生成された画像の美観スコアをシミュレートするために使用できます。
  • guidance_rescale (float, optional, defaults to 0.0) — Guidance rescale factor from Common Diffusion Noise Schedules and Sample Steps are Flawed.
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。
  • 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 属性にリストされている変数のみを、このリストに含めることができます。
  • pag_scale (float、任意、デフォルト値は 3.0) — Perturbed attention guidance のスケール係数です。0.0 に設定すると、perturbed attention guidance は使用されません。
  • pag_adaptive_scale (float, 任意、デフォルト値は 0.0) — パーターブド・アテンション・ガイダンス用の適応スケール係数です。0.0 に設定されている場合、pag_scale が使用されます。

戻り値

~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput または tuple

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

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

例:

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

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

>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"

>>> init_image = load_image(img_url).convert("RGB")
>>> mask_image = load_image(mask_url).convert("RGB")

>>> prompt = "A majestic tiger sitting on a bench"
>>> image = pipe(
...     prompt=prompt,
...     image=init_image,
...     mask_image=mask_image,
...     num_inference_steps=50,
...     strength=0.80,
...     pag_scale=0.3,
... ).images[0]

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 = Noneclip_skip: int | 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 スケールです。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。

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

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 を参照してください。

StableDiffusionXLControlNetPAGPipeline

class diffusers.StableDiffusionXLControlNetPAGPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: UNet2DConditionModelcontrolnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModelscheduler: KarrasDiffusionSchedulersforce_zeros_for_empty_prompt: bool = Trueadd_watermarker: bool | None = Nonefeature_extractor: CLIPImageProcessorPil = Noneimage_encoder: CLIPVisionModelWithProjection = Nonepag_applied_layers: str | list[str] = 'mid' )

パラメータ

  • vae (AutoencoderKL) — 画像を潜在表現にエンコードし、潜在表現からデコードするための Variational Auto-Encoder (VAE) モデル。
  • text_encoder (CLIPTextModel) — 凍結されたテキストエンコーダー (clip-vit-large-patch14)。
  • text_encoder_2 (CLIPTextModelWithProjection) — 2番目の凍結されたテキストエンコーダー (laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)。
  • tokenizer (CLIPTokenizer) — テキストをトークン化するためのCLIPTokenizer。
  • tokenizer_2 (CLIPTokenizer) — テキストをトークン化するためのCLIPTokenizerです。
  • unet (UNet2DConditionModel) — エンコードされた画像の潜在変数からノイズを除去するためのUNet2DConditionModel。
  • controlnet (ControlNetModel または list[ControlNetModel]) — デノイジングプロセス中に unet へ追加の条件付けを提供します。リストとして複数の ControlNet を設定した場合、各 ControlNet の出力が加算され、1 つの統合された追加条件付けが作成されます。
  • scheduler (SchedulerMixin) — unet と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。DDIMScheduler、LMSDiscreteScheduler、または PNDMScheduler のいずれかです。
  • force_zeros_for_empty_prompt (bool、省略可、デフォルトは"True") — ネガティブプロンプトの埋め込みを常に 0 に設定するかどうか。stabilityai/stable-diffusion-xl-base-1-0 の設定も参照してください。
  • add_watermarker (bool、省略可) — 出力画像にウォーターマークを付与するために invisible_watermark ライブラリを使用するかどうかを指定します。未定義の場合、パッケージがインストールされている場合は True がデフォルトとなり、それ以外の場合はウォーターマークは使用されません。

ControlNetによるガイダンスを用いたStable Diffusion XLのテキストから画像への生成を行うPipelineです。

このモデルは 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 = 50timesteps: list = Nonesigmas: list = Nonedenoising_end: float | None = Noneguidance_scale: float = 5.0negative_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] = 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 = Truecross_attention_kwargs: dict[str, typing.Any] | None = Nonecontrolnet_conditioning_scale: float | list[float] = 1.0control_guidance_start: float | list[float] = 0.0control_guidance_end: float | list[float] = 1.0original_size: tuple = Nonecrops_coords_top_left: tuple = (0, 0)target_size: tuple = Nonenegative_original_size: tuple[int, int] | None = Nonenegative_crops_coords_top_left: tuple = (0, 0)negative_target_size: tuple[int, int] | None = Noneclip_skip: int | None = Nonecallback_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']pag_scale: float = 3.0pag_adaptive_scale: float = 0.0 ) → StableDiffusionPipelineOutput 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]、 list[list[torch.Tensor]]、list[list[np.ndarray]] または list[list[PIL.Image.Image]]): 生成時に unet へのガイダンスを提供するための ControlNet の入力条件です。型が torch.Tensor として指定されている場合、ControlNet にそのまま渡されます。画像として PIL.Image.Image も受け付けられます。出力画像の寸法はデフォルトで image の寸法になります。高さおよび/または幅が渡された場合、image はそれに応じてリサイズされます。init で複数の ControlNet が指定されている場合、リストとして画像を渡す必要があり、リストの各要素が単一の ControlNet への入力として正しくバッチ処理できるようにしてください。
  • height (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) — 生成される画像のピクセル単位の縦幅です。stabilityai/stable-diffusion-xl-base-1.0 および低解像度に特化してファインチューニングされていないチェックポイントでは、512 ピクセル未満の値ではうまく動作しません。
  • width (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) — 生成される画像の幅(ピクセル単位)です。stabilityai/stable-diffusion-xl-base-1.0 および低解像度に特化してファインチューニングされていないチェックポイントでは、512 ピクセル未満の値ではうまく動作しません。
  • num_inference_steps (int、任意、デフォルト値は 50)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • timesteps (list[int], 任意) — timesteps 引数をサポートするスケジューラーの set_timesteps メソッドで、デノイジングプロセスに使用するカスタムタイムステップ。未定義の場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。降順で指定する必要があります。
  • sigmas (list[float]、任意) — set_timesteps メソッドで sigmas 引数を受け付けるスケジューラーにおいて、デノイジングプロセスに使用するカスタムのシグマです。定義されていない場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。
  • denoising_end (float, 省略可) — 指定した場合、デノイジング全体のどの割合(0.0 から 1.0 の間)で処理を意図的に早期終了させるかを決定します。その結果、スケジューラによって選択された離散タイムステップによって決定されるように、返されるサンプルには依然としてかなりの量のノイズが残ります。denoising_end パラメータは、画像出力の洗練 に詳述されている「Mixture of Denoisers」マルチパイプライン構成の一部としてこのパイプラインが使用される場合に、理想的には利用されるべきです。
  • guidance_scale (float、任意、デフォルト値は 5.0) — この値を大きくすると、画像の品質が低下する代わりに、prompt と強く関連した画像を生成するようモデルが促されます。guidance_scale > 1 の場合に guidance scale が有効になります。
  • 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 (η) に対応します。DDIMSchedulerでのみ適用され、他のスケジューラーでは無視されます。
  • generator (torch.Generator または list[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 入力引数から生成されます。
  • pooled_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたプールのテキスト埋め込み。テキスト入力(プロンプトの重み付け)を簡単に調整するために使用できます。指定されない場合、prompt 入力引数からプールのテキスト埋め込みが生成されます。
  • negative_pooled_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなプーリング済みテキスト埋め込みです。テキスト入力(プロンプトの重み付けなど)を簡単に調整するために使用できます。指定されない場合、negative_prompt 入力引数からプーリング済みの negative_prompt_embeds が生成されます。
  • 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 を返すかどうかを指定します。
  • cross_attention_kwargs (dict, 任意) — 指定された場合、self.processor で定義されている AttentionProcessor に渡される kwargs の辞書です。
  • controlnet_conditioning_scale (float または list[float]、任意、デフォルト値は 1.0) — ControlNet の出力は、元の unet の残差に加算される前に controlnet_conditioning_scale 倍されます。init で複数の ControlNet が指定されている場合、対応するスケールをリストとして設定できます。
  • control_guidance_start (float または list[float]、任意、デフォルト値は 0.0) — ControlNet が適用を開始するステップの割合(全体のステップ数に対するパーセンテージ)です。
  • control_guidance_end (float または list[float]、任意、デフォルト値は 1.0) — ControlNet が適用を停止するステップの割合です。
  • 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 の一部です。
  • negative_original_size (tuple[int]、任意、デフォルト値は (1024, 1024)) — 特定の画像解像度に基づいて、生成プロセスをネガティブに条件付けするために使用します。これは、https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL の micro-conditioning の一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • negative_crops_coords_top_left (tuple[int]、任意、デフォルト値は (0, 0)) — 特定のクロップ座標に基づいて、生成プロセスをネガティブに条件付けするために使用します。これは、https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • negative_target_size (tuple[int]、任意、デフォルト値は (1024, 1024)) — ターゲット画像の解像度に基づいて、生成プロセスをネガティブに条件付けするために使用します。ほとんどの場合、target_size と同じ値である必要があります。https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。
  • 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 属性にリストされている変数のみを、このリストに含めることができます。
  • pag_scale (float、任意、デフォルト値は 3.0) — Perturbed attention guidance のスケール係数です。0.0 に設定すると、perturbed attention guidance は使用されません。
  • pag_adaptive_scale (float, 任意、デフォルト値は 0.0) — パーターブド・アテンション・ガイダンス用の適応スケール係数です。0.0 に設定されている場合、pag_scale が使用されます。

戻り値

StableDiffusionPipelineOutput または tuple

return_dict が True の場合、StableDiffusionPipelineOutput が返され、それ以外の場合は出力画像を含む tuple が返されます。

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

例:

>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import AutoPipelineForText2Image, ControlNetModel, AutoencoderKL
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> import torch

>>> import cv2
>>> from PIL import Image

>>> prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
>>> negative_prompt = "low quality, bad quality, sketches"

>>> # download an image
>>> image = load_image(
...     "https://hf.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
... )

>>> # initialize the models and pipeline
>>> controlnet_conditioning_scale = 0.5  # recommended for good generalization
>>> controlnet = ControlNetModel.from_pretrained(
...     "diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16
... )
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     controlnet=controlnet,
...     vae=vae,
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe.enable_model_cpu_offload()

>>> # get canny image
>>> image = np.array(image)
>>> image = cv2.Canny(image, 100, 200)
>>> image = image[:, :, None]
>>> image = np.concatenate([image, image, image], axis=2)
>>> canny_image = Image.fromarray(image)

>>> # generate image
>>> image = pipe(
...     prompt, controlnet_conditioning_scale=controlnet_conditioning_scale, image=canny_image, pag_scale=0.3
... ).images[0]

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 = Noneclip_skip: int | 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 スケールです。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。

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

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 を参照してください。

StableDiffusionXLControlNetPAGImg2ImgPipeline

class diffusers.StableDiffusionXLControlNetPAGImg2ImgPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: UNet2DConditionModelcontrolnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModelscheduler: KarrasDiffusionSchedulersrequires_aesthetics_score: bool = Falseforce_zeros_for_empty_prompt: bool = Trueadd_watermarker: bool | None = Nonefeature_extractor: CLIPImageProcessorPil = Noneimage_encoder: CLIPVisionModelWithProjection = Nonepag_applied_layers: str | list[str] = 'mid' )

パラメータ

  • vae (AutoencoderKL) — 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ (VAE) モデル。
  • text_encoder (CLIPTextModel) — 凍結されたテキストエンコーダー。Stable Diffusion は 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 アーキテクチャ。
  • controlnet (ControlNetModel または list[ControlNetModel]) — デノイジング処理中に unet へ追加の条件付けを提供します。リストとして複数の ControlNet を設定した場合、各 ControlNet の出力が加算され、1 つの統合された追加条件付けが作成されます。
  • 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 がデフォルトとなり、インストールされていなければウォーターマークは付与されません。
  • feature_extractor (CLIPImageProcessor) — 生成された画像から特徴量を抽出するためのCLIPImageProcessor。safety_checkerの入力として使用されます。

ControlNetによるガイダンスを用いたStable Diffusion XLの画像から画像への生成を行うPipelineです。

このモデルは 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]] = Nonecontrol_image: 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 = Nonestrength: float = 0.8num_inference_steps: int = 50guidance_scale: float = 5.0negative_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] = 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 = Truecross_attention_kwargs: dict[str, typing.Any] | None = Nonecontrolnet_conditioning_scale: float | list[float] = 0.8guess_mode: bool = Falsecontrol_guidance_start: float | list[float] = 0.0control_guidance_end: float | list[float] = 1.0original_size: tuple = Nonecrops_coords_top_left: tuple = (0, 0)target_size: tuple = Nonenegative_original_size: tuple[int, int] | None = Nonenegative_crops_coords_top_left: tuple = (0, 0)negative_target_size: tuple[int, int] | None = Noneaesthetic_score: float = 6.0negative_aesthetic_score: float = 2.5clip_skip: int | None = Nonecallback_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']pag_scale: float = 3.0pag_adaptive_scale: float = 0.0 ) → ~pipelines.stable_diffusion.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]、 list[list[torch.Tensor]]、list[list[np.ndarray]] または list[list[PIL.Image.Image]]): 初期画像は、画像生成プロセスの開始点として使用されます。image として画像の潜在変数(latents)を直接渡すことも可能で、その場合は再度エンコードされません。
  • control_image (torch.Tensor, PIL.Image.Image, np.ndarray, list[torch.Tensor], list[PIL.Image.Image], list[np.ndarray], — list[list[torch.Tensor]], list[list[np.ndarray]] または list[list[PIL.Image.Image]]): ControlNet の入力条件です。ControlNet はこの入力条件を使用して、Unet へのガイダンスを生成します。型が torch.Tensor として指定されている場合、ControlNet にそのまま渡されます。PIL.Image.Image も画像として受け入れられます。出力画像の寸法は、デフォルトで image の寸法になります。高さおよび/または幅が渡された場合、image はそれらに従ってリサイズされます。init で複数の ControlNet が指定されている場合、各 ControlNet への入力が正しくバッチ処理できるよう、画像はリストとして渡す必要があります。
  • height (int、任意、デフォルトは control_image のサイズ)— 生成される画像のピクセル高さです。512 ピクセル未満の値は、stabilityai/stable-diffusion-xl-base-1.0 や、低解像度に特化してファインチューニングされていないチェックポイントでは適切に動作しません。
  • width (int、任意、デフォルトは control_image のサイズ)— 生成される画像の幅(ピクセル単位)。stabilityai/stable-diffusion-xl-base-1.0 および低解像度に特化してファインチューニングされていないチェックポイントでは、512 ピクセル未満の値ではうまく動作しません。
  • strength (float、任意、デフォルト値は 0.8) — 参照となるimageの変換の度合いを示します。0 から 1 の間の値である必要があります。imageが起点として使用され、strengthが大きいほど多くのノイズが追加されます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。strengthが 1 の場合、追加されるノイズは最大となり、デノイジングプロセスはnum_inference_stepsで指定された全イテレーション数分実行されます。値が 1 の場合、imageは実質的に無視されます。
  • num_inference_steps (int、任意、デフォルト値は 50)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • guidance_scale (float、任意、デフォルト値は 7.5) — Classifier-Free Diffusion Guidance で定義されているガイダンススケールです。guidance_scale は、Imagen Paper の数式 2 の w として定義されています。guidance_scale > 1 を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、prompt のテキストと密接に関連した画像の生成が促されますが、通常は画像の品質が低下する傾向があります。
  • 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 が生成されます。
  • 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: PIL.Image.Image または np.array から選択します。
  • return_dict (bool、任意、デフォルトは True) — プレーンなタプルではなく StableDiffusionPipelineOutput を返すかどうかを指定します。
  • cross_attention_kwargs (dict、省略可) — 指定された場合、diffusers.models.attention_processor で定義されている self.processor 配下の AttentionProcessor に渡される kwargs の辞書です。
  • controlnet_conditioning_scale (float または list[float]、任意、デフォルト値は 1.0) — ControlNet の出力は、元の unet の残差に加算される前に controlnet_conditioning_scale 倍されます。init で複数の ControlNet を指定する場合は、対応するスケールをリストとして設定できます。
  • guess_mode (bool、省略可、デフォルトは False) — このモードでは、プロンプトをすべて削除した場合でも、ControlNet エンコーダーは入力画像の内容を認識しようとします。guidance_scale は 3.0 から 5.0 の範囲が推奨されます。
  • control_guidance_start (float または list[float]、任意、デフォルト値は 0.0) — ControlNet が適用を開始するステップの割合(全体のステップ数に対するパーセンテージ)です。
  • control_guidance_end (float または list[float]、任意、デフォルト値は 1.0) — ControlNet が適用を停止するステップの割合です。
  • 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 の一部です。
  • negative_original_size (tuple[int]、任意、デフォルト値は (1024, 1024)) — 特定の画像解像度に基づいて、生成プロセスをネガティブに条件付けするために使用します。これは、https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL の micro-conditioning の一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • negative_crops_coords_top_left (tuple[int]、任意、デフォルト値は (0, 0)) — 特定のクロップ座標に基づいて、生成プロセスをネガティブに条件付けするために使用します。これは、https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • negative_target_size (tuple[int]、任意、デフォルト値は (1024, 1024)) — ターゲット画像の解像度に基づいて、生成プロセスをネガティブに条件付けするために使用します。ほとんどの場合、target_size と同じ値である必要があります。https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。詳細については、この issue スレッドを参照してください: https://github.com/huggingface/diffusers/issues/4208。
  • aesthetic_score (float、任意、デフォルト値は 6.0) — 正のテキスト条件に影響を与えることで、生成された画像の美観スコアをシミュレートするために使用されます。 https://huggingface.co/papers/2307.01952 のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。
  • negative_aesthetic_score (float、任意、デフォルト値: 2.5) — https://huggingface.co/papers/2307.01952のセクション 2.2 で説明されている SDXL のマイクロコンディショニングの一部です。ネガティブなテキスト条件に影響を与えることで、生成された画像の美観スコアをシミュレートするために使用できます。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。
  • 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 属性にリストされている変数のみを、このリストに含めることができます。
  • pag_scale (float、任意、デフォルト値は 3.0) — Perturbed attention guidance のスケール係数です。0.0 に設定すると、perturbed attention guidance は使用されません。
  • pag_adaptive_scale (float, 任意、デフォルト値は 0.0) — パーターブド・アテンション・ガイダンス用の適応スケール係数です。0.0 に設定されている場合、pag_scale が使用されます。

戻り値

~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput または tuple

return_dict が True の場合は ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput、それ以外の場合は出力画像を含む tuple を返します。

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

例:

>>> # pip install accelerate transformers safetensors diffusers

>>> import torch
>>> import numpy as np
>>> from PIL import Image

>>> from transformers import DPTFeatureExtractor, DPTForDepthEstimation
>>> from diffusers import ControlNetModel, StableDiffusionXLControlNetPAGImg2ImgPipeline, AutoencoderKL
>>> from diffusers.utils import load_image

>>> depth_estimator = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to("cuda")
>>> feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-hybrid-midas")
>>> controlnet = ControlNetModel.from_pretrained(
...     "diffusers/controlnet-depth-sdxl-1.0-small",
...     variant="fp16",
...     use_safetensors="True",
...     torch_dtype=torch.float16,
... )
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> pipe = StableDiffusionXLControlNetPAGImg2ImgPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     controlnet=controlnet,
...     vae=vae,
...     variant="fp16",
...     use_safetensors=True,
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe.enable_model_cpu_offload()


>>> def get_depth_map(image):
...     image = feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda")
...     with torch.no_grad(), torch.autocast("cuda"):
...         depth_map = depth_estimator(image).predicted_depth

...     depth_map = torch.nn.functional.interpolate(
...         depth_map.unsqueeze(1),
...         size=(1024, 1024),
...         mode="bicubic",
...         align_corners=False,
...     )
...     depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
...     depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
...     depth_map = (depth_map - depth_min) / (depth_max - depth_min)
...     image = torch.cat([depth_map] * 3, dim=1)
...     image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
...     image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
...     return image


>>> prompt = "A robot, 4k photo"
>>> image = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png"
... ).resize((1024, 1024))
>>> controlnet_conditioning_scale = 0.5  # recommended for good generalization
>>> depth_image = get_depth_map(image)

>>> images = pipe(
...     prompt,
...     image=image,
...     control_image=depth_image,
...     strength=0.99,
...     num_inference_steps=50,
...     controlnet_conditioning_scale=controlnet_conditioning_scale,
... ).images
>>> images[0].save(f"robot_cat.png")

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 = Noneclip_skip: int | 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 スケールです。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。

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

StableDiffusion3PAGPipeline

class diffusers.StableDiffusion3PAGPipeline

< >

( transformer: SD3Transformer2DModelscheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertext_encoder_2: CLIPTextModelWithProjectiontokenizer_2: CLIPTokenizertext_encoder_3: T5EncoderModeltokenizer_3: T5Tokenizerpag_applied_layers: str | list[str] = 'blocks.1' )

パラメータ

  • transformer (SD3Transformer2DModel) — エンコードされた画像潜在変数からノイズを除去するための、条件付き Transformer (MMDiT) アーキテクチャ。
  • scheduler (FlowMatchEulerDiscreteScheduler) — transformer と組み合わせて、エンコードされた画像の潜在変数からノイズを除去するために使用するスケジューラ。
  • vae (AutoencoderKL) — 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ (VAE) モデル。
  • text_encoder (CLIPTextModelWithProjection) — CLIP、 具体的には clip-vit-large-patch14 バリアントで、 hidden_size を次元とする対角行列で初期化された追加の投影層を備えています。
  • text_encoder_2 (CLIPTextModelWithProjection) — CLIP、 具体的には laion/CLIP-ViT-bigG-14-laion2B-39B-b160k バリアントです。
  • text_encoder_3 (T5EncoderModel) — 凍結されたテキストエンコーダーです。Stable Diffusion 3 は T5、具体的には t5-v1_1-xxl バリアントを使用しています。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer クラスのトークナイザー。
  • tokenizer_2 (CLIPTokenizer) — クラス CLIPTokenizer の2番目の Tokenizer。
  • tokenizer_3 (T5TokenizerFast) — クラス T5Tokenizer のトークナイザー。

Stable Diffusion 3 を用いたテキストから画像への生成のためのPAG パイプライン

__call__

< >

( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Noneprompt_3: str | list[str] | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 28sigmas: list[float] | None = Noneguidance_scale: float = 7.0negative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenegative_prompt_3: str | list[str] | None = Nonenum_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] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 256pag_scale: float = 3.0pag_adaptive_scale: float = 0.0 ) → ~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput or tuple

パラメータ

  • prompt (str または list[str]、省略可) — 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに prompt_embeds を渡す必要があります。
  • prompt_2 (str または list[str]、省略可) — tokenizer_2 および text_encoder_2 に送信するプロンプトです。未定義の場合、代わりに prompt が使用されます。
  • prompt_3 (str または list[str]、省略可) — tokenizer_3 および text_encoder_3 に送信するプロンプトです。未定義の場合、代わりに prompt が使用されます。
  • height (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) — 生成される画像のピクセル単位の縦幅です。最適な結果を得るため、デフォルトでは 1024 に設定されています。
  • width (int、任意、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) — 生成される画像の幅(ピクセル単位)です。最適な結果を得るため、デフォルトでは 1024 に設定されています。
  • num_inference_steps (int、任意、デフォルト値は 50)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • sigmas (list[float]、任意) — set_timesteps メソッドで sigmas 引数を受け付けるスケジューラーにおいて、デノイジングプロセスに使用するカスタムのシグマです。定義されていない場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。
  • guidance_scale (float、任意、デフォルト値は 7.0) — Classifier-Free Diffusion Guidance で定義されているガイダンススケールです。guidance_scale は、Imagen Paper の数式 2 の w として定義されています。guidance_scale > 1 を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、prompt のテキストと密接に関連した画像の生成が促されますが、通常は画像の品質が低下する傾向があります。
  • 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_3 (str または list[str]、省略可) — tokenizer_3 および text_encoder_3 に送信する、画像生成を導かないためのプロンプトです。未定義の場合、代わりに negative_prompt が使用されます。
  • num_images_per_prompt (int、任意、デフォルトは 1) — プロンプトごとに生成する画像の数。
  • generator (torch.Generator または list[torch.Generator]、省略可) — 生成を決定論的にするためのtorch ジェネレーター1つまたはリスト。
  • latents (torch.FloatTensor, 任意) — 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイジーな潜在変数です。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムgeneratorを使用してサンプリングを行い、潜在変数テンソルが生成されます。
  • prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt 入力引数からテキスト埋め込みが生成されます。
  • negative_prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたネガティブなテキスト埋め込みです。テキスト入力の調整、例えばプロンプトの重み付けなどを簡単に実行できます。指定されない場合、negative_prompt 入力引数から negative_prompt_embeds が生成されます。
  • pooled_prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたプールのテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどに簡単に使用できます。 指定されない場合、prompt 入力引数からプールのテキスト埋め込みが生成されます。
  • negative_pooled_prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたネガティブなプーリング済みテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、negative_prompt 入力引数からプーリング済み negative_prompt_embeds が生成されます。
  • output_type (str、任意、デフォルトは "pil") — 画像生成の出力形式です。PIL: PIL.Image.Image または np.array から選択します。
  • return_dict (bool、省略可能、デフォルトは True) — ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput を返すかどうか。プレーンなタプルを返すこともできます。
  • joint_attention_kwargs (dict、省略可) — 指定された場合、diffusers.models.attention_processor で定義されている self.processor 配下の AttentionProcessor に渡される kwargs の辞書です。
  • 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 属性にリストされている変数のみを、このリストに含めることができます。
  • max_sequence_length (int、デフォルトは 256) — prompt に使用する最大シーケンス長。
  • pag_scale (float、任意、デフォルト値は 3.0) — Perturbed attention guidance のスケール係数です。0.0 に設定すると、perturbed attention guidance は使用されません。
  • pag_adaptive_scale (float, 任意、デフォルト値は 0.0) — パーターブド・アテンション・ガイダンス用の適応スケール係数です。0.0 に設定されている場合、pag_scale が使用されます。

戻り値

~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput または tuple

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

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

例:

>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stabilityai/stable-diffusion-3-medium-diffusers",
...     torch_dtype=torch.float16,
...     enable_pag=True,
...     pag_applied_layers=["blocks.13"],
... )
>>> pipe.to("cuda")
>>> prompt = "A cat holding a sign that says hello world"
>>> image = pipe(prompt, guidance_scale=5.0, pag_scale=0.7).images[0]
>>> image.save("sd3_pag.png")

encode_prompt

< >

( prompt: str | list[str]prompt_2: str | list[str]prompt_3: str | list[str]device: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1do_classifier_free_guidance: bool = Truenegative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenegative_prompt_3: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneclip_skip: int | None = Nonemax_sequence_length: int = 256lora_scale: float | None = None )

パラメータ

  • prompt (str または list[str]、省略可能) — エンコードするプロンプト
  • prompt_2 (str または list[str]、省略可) — tokenizer_2 および text_encoder_2 に送信するプロンプトです。定義されていない場合、すべての text-encoder で prompt が使用されます。
  • prompt_3 (str または list[str]、省略可) — tokenizer_3 および text_encoder_3 に送信するプロンプトです。定義されていない場合、すべてのテキストエンコーダーで 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 が使用されます。
  • negative_prompt_3 (str または list[str]、省略可) — tokenizer_3 および text_encoder_3 に渡す、画像生成を誘導しないためのプロンプトです。定義されていない場合、すべての text-encoder で negative_prompt が使用されます。
  • prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt 入力引数からテキスト埋め込みが生成されます。
  • negative_prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたネガティブなテキスト埋め込みです。テキスト入力の調整、例えばプロンプトの重み付けなどを簡単に実行できます。指定されない場合、negative_prompt 入力引数から negative_prompt_embeds が生成されます。
  • pooled_prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたプールのテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどに簡単に使用できます。 指定されない場合、prompt 入力引数からプールのテキスト埋め込みが生成されます。
  • negative_pooled_prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたネガティブなプーリング済みテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、negative_prompt 入力引数からプーリング済み negative_prompt_embeds が生成されます。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。
  • lora_scale (float, 省略可) — LoRA レイヤーが読み込まれている場合、テキストエンコーダーのすべての LoRA レイヤーに適用される LoRA スケールです。

StableDiffusion3PAGImg2ImgPipeline

class diffusers.StableDiffusion3PAGImg2ImgPipeline

< >

( transformer: SD3Transformer2DModelscheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertext_encoder_2: CLIPTextModelWithProjectiontokenizer_2: CLIPTokenizertext_encoder_3: T5EncoderModeltokenizer_3: T5Tokenizerpag_applied_layers: str | list[str] = 'blocks.1' )

パラメータ

  • transformer (SD3Transformer2DModel) — エンコードされた画像潜在変数からノイズを除去するための、条件付き Transformer (MMDiT) アーキテクチャ。
  • scheduler (FlowMatchEulerDiscreteScheduler) — transformer と組み合わせて、エンコードされた画像の潜在変数からノイズを除去するために使用するスケジューラ。
  • vae (AutoencoderKL) — 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ (VAE) モデル。
  • text_encoder (CLIPTextModelWithProjection) — CLIP、 具体的には clip-vit-large-patch14 バリアントで、 hidden_size を次元とする対角行列で初期化された追加の投影層を備えています。
  • text_encoder_2 (CLIPTextModelWithProjection) — CLIP、 具体的には laion/CLIP-ViT-bigG-14-laion2B-39B-b160k バリアントです。
  • text_encoder_3 (T5EncoderModel) — 凍結されたテキストエンコーダーです。Stable Diffusion 3 は T5、具体的には t5-v1_1-xxl バリアントを使用しています。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer クラスのトークナイザー。
  • tokenizer_2 (CLIPTokenizer) — クラス CLIPTokenizer の2番目の Tokenizer。
  • tokenizer_3 (T5TokenizerFast) — クラス T5Tokenizer のトークナイザー。

Stable Diffusion 3 を用いた画像から画像への生成のためのPAG パイプライン

__call__

< >

( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Noneprompt_3: str | list[str] | None = Noneheight: int | None = Nonewidth: int | None = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonestrength: float = 0.6num_inference_steps: int = 50sigmas: list[float] | None = Noneguidance_scale: float = 7.0negative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenegative_prompt_3: str | list[str] | None = Nonenum_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] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 256pag_scale: float = 3.0pag_adaptive_scale: float = 0.0 ) → ~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput or tuple

パラメータ

  • prompt (str または list[str]、省略可) — 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに prompt_embeds を渡す必要があります。
  • prompt_2 (str または list[str]、省略可) — tokenizer_2 および text_encoder_2 に送信するプロンプトです。未定義の場合、代わりに prompt が使用されます。
  • prompt_3 (str または list[str]、省略可) — tokenizer_3 および text_encoder_3 に送信するプロンプトです。未定義の場合、代わりに prompt が使用されます。
  • height (int、任意、デフォルトは self.default_sample_size * self.vae_scale_factor) — 生成される画像の高さ(ピクセル単位)です。最適な結果を得るため、デフォルトでは 1024 に設定されています。
  • width (int、任意、デフォルトは self.default_sample_size * self.vae_scale_factor) — 生成される画像の幅(ピクセル単位)です。最適な結果を得るため、デフォルトでは 1024 に設定されています。
  • 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) です。画像の潜在変数も image として受け取れますが、潜在変数を直接渡す場合は、再度エンコードされません。
  • strength (float、任意、デフォルト値は 0.8) — 参照となるimageの変換の度合いを示します。0 から 1 の間の値である必要があります。imageが起点として使用され、strengthが大きいほど多くのノイズが追加されます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。strengthが 1 の場合、追加されるノイズは最大となり、デノイジングプロセスはnum_inference_stepsで指定された全イテレーション数分実行されます。値が 1 の場合、imageは実質的に無視されます。
  • num_inference_steps (int、任意、デフォルト値は 50)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • sigmas (list[float]、任意) — set_timesteps メソッドで sigmas 引数を受け付けるスケジューラーにおいて、デノイジングプロセスに使用するカスタムのシグマです。定義されていない場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。
  • guidance_scale (float、任意、デフォルト値は 7.0) — Classifier-Free Diffusion Guidance で定義されているガイダンススケールです。guidance_scale は、Imagen Paper の数式 2 の w として定義されています。guidance_scale > 1 を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、prompt のテキストと密接に関連した画像の生成が促されますが、通常は画像の品質が低下する傾向があります。
  • 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_3 (str または list[str]、省略可) — tokenizer_3 および text_encoder_3 に送信する、画像生成を導かないためのプロンプトです。未定義の場合、代わりに negative_prompt が使用されます。
  • num_images_per_prompt (int、任意、デフォルトは 1) — プロンプトごとに生成する画像の数。
  • generator (torch.Generator または list[torch.Generator]、省略可) — 生成を決定論的にするためのtorch ジェネレーター1つまたはリスト。
  • latents (torch.FloatTensor, 任意) — 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイジーな潜在変数です。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムgeneratorを使用してサンプリングを行い、潜在変数テンソルが生成されます。
  • prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt 入力引数からテキスト埋め込みが生成されます。
  • negative_prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたネガティブなテキスト埋め込みです。テキスト入力の調整、例えばプロンプトの重み付けなどを簡単に実行できます。指定されない場合、negative_prompt 入力引数から negative_prompt_embeds が生成されます。
  • pooled_prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたプールのテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどに簡単に使用できます。 指定されない場合、prompt 入力引数からプールのテキスト埋め込みが生成されます。
  • negative_pooled_prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたネガティブなプーリング済みテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、negative_prompt 入力引数からプーリング済み negative_prompt_embeds が生成されます。
  • output_type (str、任意、デフォルトは "pil") — 画像生成の出力形式です。PIL: PIL.Image.Image または np.array から選択します。
  • return_dict (bool、省略可能、デフォルトは True) — ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput を返すかどうか。プレーンなタプルを返すこともできます。
  • joint_attention_kwargs (dict、省略可) — 指定された場合、diffusers.models.attention_processor で定義されている self.processor 配下の AttentionProcessor に渡される kwargs の辞書です。
  • 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 属性にリストされている変数のみを、このリストに含めることができます。
  • max_sequence_length (int、デフォルトは 256) — prompt に使用する最大シーケンス長。
  • pag_scale (float、任意、デフォルト値は 3.0) — Perturbed attention guidance のスケール係数です。0.0 に設定すると、perturbed attention guidance は使用されません。
  • pag_adaptive_scale (float, 任意、デフォルト値は 0.0) — パーターブド・アテンション・ガイダンス用の適応スケール係数です。0.0 に設定されている場合、pag_scale が使用されます。

戻り値

~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput または tuple

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

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

例:

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

>>> pipe = StableDiffusion3PAGImg2ImgPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-3-medium-diffusers",
...     torch_dtype=torch.float16,
...     pag_applied_layers=["blocks.13"],
... )
>>> pipe.to("cuda")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"
>>> init_image = load_image(url).convert("RGB")
>>> image = pipe(prompt, image=init_image, guidance_scale=5.0, pag_scale=0.7).images[0]

encode_prompt

< >

( prompt: str | list[str]prompt_2: str | list[str]prompt_3: str | list[str]device: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1do_classifier_free_guidance: bool = Truenegative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenegative_prompt_3: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneclip_skip: int | None = Nonemax_sequence_length: int = 256lora_scale: float | None = None )

パラメータ

  • prompt (str または list[str]、省略可能) — エンコードするプロンプト
  • prompt_2 (str または list[str]、省略可) — tokenizer_2 および text_encoder_2 に送信するプロンプトです。定義されていない場合、すべての text-encoder で prompt が使用されます。
  • prompt_3 (str または list[str]、省略可) — tokenizer_3 および text_encoder_3 に送信するプロンプトです。定義されていない場合、すべてのテキストエンコーダーで 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 が使用されます。
  • negative_prompt_3 (str または list[str]、省略可) — tokenizer_3 および text_encoder_3 に渡す、画像生成を誘導しないためのプロンプトです。定義されていない場合、すべての text-encoder で negative_prompt が使用されます。
  • prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt 入力引数からテキスト埋め込みが生成されます。
  • negative_prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたネガティブなテキスト埋め込みです。テキスト入力の調整、例えばプロンプトの重み付けなどを簡単に実行できます。指定されない場合、negative_prompt 入力引数から negative_prompt_embeds が生成されます。
  • pooled_prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたプールのテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどに簡単に使用できます。 指定されない場合、prompt 入力引数からプールのテキスト埋め込みが生成されます。
  • negative_pooled_prompt_embeds (torch.FloatTensor, 任意) — 事前に生成されたネガティブなプーリング済みテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、negative_prompt 入力引数からプーリング済み negative_prompt_embeds が生成されます。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。
  • lora_scale (float, 省略可) — LoRA レイヤーが読み込まれている場合、テキストエンコーダーのすべての LoRA レイヤーに適用される LoRA スケールです。

PixArtSigmaPAGPipeline

class diffusers.PixArtSigmaPAGPipeline

< >

( tokenizer: T5Tokenizertext_encoder: T5EncoderModelvae: AutoencoderKLtransformer: PixArtTransformer2DModelscheduler: KarrasDiffusionSchedulerspag_applied_layers: str | list[str] = 'blocks.1' )

PixArt-Sigma を使用したテキストから画像への生成のためのPAG パイプライン

__call__

< >

( prompt: str | list[str] = Nonenegative_prompt: str = ''num_inference_steps: int = 20timesteps: list = Nonesigmas: list = Noneguidance_scale: float = 4.5num_images_per_prompt: int | None = 1height: int | None = Nonewidth: int | None = Noneeta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: 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 = 1clean_caption: bool = Trueuse_resolution_binning: bool = Truemax_sequence_length: int = 300pag_scale: float = 3.0pag_adaptive_scale: float = 0.0 ) → ImagePipelineOutput or tuple

パラメータ

  • prompt (str または list[str]、省略可) — 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに prompt_embeds を渡す必要があります。
  • negative_prompt (str または list[str]、省略可) — 画像生成をガイドしないプロンプトです。未定義の場合、代わりに negative_prompt_embeds を渡す必要があります。ガイダンスを使用していない場合は無視されます(guidance_scale が 1 未満の場合は無視されます)。
  • num_inference_steps (int、任意、デフォルト値は 100) — デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • timesteps (list[int], 任意) — timesteps 引数をサポートするスケジューラーの set_timesteps メソッドで、デノイジングプロセスに使用するカスタムタイムステップ。未定義の場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。降順で指定する必要があります。
  • sigmas (list[float]、任意) — set_timesteps メソッドで sigmas 引数を受け付けるスケジューラーにおいて、デノイジングプロセスに使用するカスタムのシグマです。定義されていない場合、num_inference_steps が渡された際のデフォルトの動作が使用されます。
  • guidance_scale (float、任意、デフォルト値は 4.5) — Classifier-Free Diffusion Guidance で定義されているガイダンススケールです。guidance_scale は、Imagen Paper の数式 2 の w として定義されています。guidance_scale > 1 を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、prompt のテキストと密接に関連する画像の生成が促されますが、通常は画像の品質が低下する傾向があります。
  • num_images_per_prompt (int、任意、デフォルトは 1) — プロンプトごとに生成する画像の数。
  • height (int、任意、デフォルトは self.unet.config.sample_size) — 生成される画像のピクセル単位の縦幅。
  • width (int、任意、デフォルトは self.unet.config.sample_size)— 生成される画像の幅(ピクセル単位)。
  • 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 入力引数からテキスト埋め込みが生成されます。
  • prompt_attention_mask (torch.Tensor, 任意) — テキスト埋め込み用の事前生成されたアテンションマスク。
  • negative_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブテキストの埋め込みです。PixArt-Sigma の場合、このネガティブプロンプトは "" である必要があります。指定されない場合、negative_prompt 入力引数から negative_prompt_embeds が生成されます。
  • negative_prompt_attention_mask (torch.Tensor, 任意) — ネガティブなテキスト埋め込み用の事前生成されたアテンションマスクです。
  • output_type (str、任意、デフォルトは "pil") — 画像生成の出力形式です。PIL: PIL.Image.Image または np.array から選択します。
  • return_dict (bool、省略可能、デフォルトは True) — ~pipelines.stable_diffusion.IFPipelineOutput を返すか、プレーンなタプルを返すかを指定します。
  • callback (Callable, 省略可) — 推論中に callback_steps ステップごとに呼び出される関数です。この関数は、以下の引数とともに呼び出されます: callback(step: int, timestep: int, latents: torch.Tensor)。
  • callback_steps (int、任意、デフォルトは 1) — callback 関数が呼び出される頻度です。指定しない場合、callback はすべてのステップで呼び出されます。
  • clean_caption (bool、任意、デフォルトは True) — 埋め込みを作成する前にキャプションをクリーンアップするかどうか。beautifulsoup4 と ftfy のインストールが必要です。依存関係がインストールされていない場合、埋め込みは生のプロンプトから作成されます。
  • use_resolution_binning (bool、デフォルトは True) — True に設定すると、要求された高さおよび幅は、ASPECT_RATIO_1024_BIN を使用して最も近い解像度にマッピングされます。生成された潜在変数が画像にデコードされた後、要求された解像도에リサイズされます。正方形でない画像の生成に有用です。
  • max_sequence_length (int、デフォルト値は 300)— prompt に使用する最大シーケンス長。
  • pag_scale (float、任意、デフォルト値は 3.0) — Perturbed attention guidance のスケール係数です。0.0 に設定すると、perturbed attention guidance は使用されません。
  • pag_adaptive_scale (float, 任意、デフォルト値は 0.0) — パーターブド・アテンション・ガイダンス用の適応スケール係数です。0.0 に設定されている場合、pag_scale が使用されます。

戻り値

ImagePipelineOutput または tuple

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

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

例:

>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "PixArt-alpha/PixArt-Sigma-XL-2-1024-MS",
...     torch_dtype=torch.float16,
...     pag_applied_layers=["blocks.14"],
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "A small cactus with a happy face in the Sahara desert"
>>> image = pipe(prompt, pag_scale=4.0, guidance_scale=1.0).images[0]

encode_prompt

< >

( prompt: str | list[str]do_classifier_free_guidance: bool = Truenegative_prompt: str = ''num_images_per_prompt: int = 1device: typing.Optional[torch.device] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Noneclean_caption: bool = Falsemax_sequence_length: int = 300**kwargs )

パラメータ

  • prompt (str または list[str]、省略可能) — エンコードするプロンプト
  • negative_prompt (str または list[str]、省略可) — 画像生成を導かないためのプロンプトです。未定義の場合、代わりに negative_prompt_embeds を渡す必要があります。ガイダンスを使用していない場合は無視されます(つまり、guidance_scale が 1 未満の場合は無視されます)。PixArt-Alpha の場合は、"" に設定してください。
  • do_classifier_free_guidance (bool、任意、デフォルトは True) — classifier free guidance を使用するかどうか
  • num_images_per_prompt (int、任意、デフォルトは 1) — プロンプトごとに生成する画像の数
  • device — (torch.device, 任意): 生成される埋め込みを配置する torch デバイス
  • prompt_embeds (torch.Tensor, 任意) — 事前に生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt 入力引数からテキスト埋め込みが生成されます。
  • negative_prompt_embeds (torch.Tensor, 任意) — 事前に生成されたネガティブなテキスト埋め込み。PixArt-Alpha の場合は、"" 文字列の埋め込みである必要があります。
  • clean_caption (bool、デフォルトは False) — True の場合、エンコード前に提供されたキャプションを前処理してクリーニングします。
  • max_sequence_length (int、デフォルト値は 300) — プロンプトに使用する最大シーケンス長。

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

Update on GitHub