Diffusers documentation
ControlNet
ControlNet
ControlNetは、Lvmin Zhang、Anyi Rao、Maneesh Agrawalaによる論文Adding Conditional Control to Text-to-Image Diffusion Modelsで提案されました。
ControlNetモデルを使用すると、Stable Diffusionの生成を条件付け・制御するための追加の制御画像を指定できます。例えば、深度マップを指定すると、ControlNetモデルは深度マップの空間情報を保持した画像を生成します。これは、画像生成プロセスをより柔軟かつ正確に制御する方法です。
論文の抄録は以下の通りです:
本稿では、大規模な事前学習済みテキストから画像への拡散モデルに空間的条件付け制御を追加するためのニューラルネットワークアーキテクチャであるControlNetを提案します。ControlNetは、実運用可能な大規模拡散モデルを固定し、数十億枚の画像で事前学習された深く頑健なエンコーディング層を強力なバックボーンとして再利用することで、多様な条件付け制御のセットを学習します。このニューラルアーキテクチャは、「ゼロ畳み込み」(ゼロ初期化された畳み込み層)によって接続されており、パラメータをゼロから段階的に増加させ、有害なノイズがファインチューニングに影響を与えないことを保証します。Stable Diffusionを用いて、エッジ、深度、セグメンテーション、人間のポーズなどの様々な条件付け制御を、プロンプトの有無にかかわらず、単一または複数の条件を用いてテストしました。ControlNetの学習は、小規模(<50k)および大規模(>1m)のデータセットのいずれにおいても頑健であることが示されています。広範な結果から、ControlNetは画像拡散モデルの制御に関するより幅広いアプリケーションを促進し得ることが示されました。
このパイプラインは ishan24 によって貢献されました。❤️ 元のコードベースは NVlabs/Sana で確認でき、公式の ControlNet チェックポイントは Efficient-Large-Model の Hub プロファイルで確認できます。
SanaControlNetPipeline
class diffusers.SanaControlNetPipeline
< source >( tokenizer: GemmaTokenizertext_encoder: Gemma2PreTrainedModelvae: AutoencoderDCtransformer: SanaTransformer2DModelcontrolnet: SanaControlNetModelscheduler: DPMSolverMultistepScheduler )
Sana を使用したテキストから画像への生成パイプライン。
__call__
< source >( prompt: str | list[str] = Nonenegative_prompt: str = ''num_inference_steps: int = 20timesteps: list = Nonesigmas: list = Noneguidance_scale: float = 4.5control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonecontrolnet_conditioning_scale: float | list[float] = 1.0num_images_per_prompt: int | None = 1height: int = 1024width: int = 1024eta: 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 = Trueclean_caption: bool = Falseuse_resolution_binning: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 300complex_human_instruction: list = ["Given a user prompt, generate an 'Enhanced prompt' that provides detailed visual descriptions suitable for image generation. Evaluate the level of detail in the user prompt:", '- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, and spatial relationships to create vivid and concrete scenes.', '- If the prompt is already detailed, refine and enhance the existing details slightly without overcomplicating.', 'Here are examples of how to transform or refine prompts:', '- User Prompt: A cat sleeping -> Enhanced: A small, fluffy white cat curled up in a round shape, sleeping peacefully on a warm sunny windowsill, surrounded by pots of blooming red flowers.', '- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps, a diverse crowd of people in colorful clothing, and a double-decker bus passing by towering glass skyscrapers.', 'Please generate only the enhanced description for the prompt below and avoid including any additional commentary or evaluations:', 'User Prompt: '] ) → SanaPipelineOutput or tuple
パラメータ
- prompt (
strまたはlist[str]、省略可) — 画像生成をガイドするためのプロンプトです。未定義の場合、代わりにprompt_embedsを渡す必要があります。 - negative_prompt (
strまたはlist[str]、省略可) — 画像生成をガイドしないプロンプトです。未定義の場合、代わりにnegative_prompt_embedsを渡す必要があります。ガイダンスを使用していない場合は無視されます(guidance_scaleが1未満の場合は無視されます)。 - num_inference_steps (
int、任意、デフォルト値は 20)— デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。 - 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のテキストと密接に関連する画像の生成が促されますが、通常は画像の品質が低下する傾向があります。 - 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]]): 生成時にunetへのガイダンスを提供するための ControlNet の入力条件です。型がtorch.Tensorとして指定されている場合、ControlNet にそのまま渡されます。画像としてPIL.Image.Imageも受け付けられます。出力画像の寸法は、デフォルトでimageの寸法になります。高さおよび/または幅が渡された場合、imageはそれに応じてリサイズされます。initで複数の ControlNet が指定されている場合、各 ControlNet への入力が正しくバッチ処理できるよう、リストとして画像を渡す必要があります。 - controlnet_conditioning_scale (
floatまたはlist[float]、任意、デフォルト値は 1.0) — ControlNet の出力は、元のunetの残差に加算される前にcontrolnet_conditioning_scale倍されます。initで複数の ControlNet が指定されている場合、対応するスケールをリストとして設定できます。 - 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を返すか、プレーンなタプルを返すかを指定します。 - attention_kwargs —
指定された場合、diffusers.models.attention_processor で定義されている
self.processor配下のAttentionProcessorに渡される kwargs 辞書。 - clean_caption (
bool、任意、デフォルトはTrue) — 埋め込みを作成する前にキャプションをクリーンアップするかどうか。beautifulsoup4とftfyのインストールが必要です。依存関係がインストールされていない場合、埋め込みは生のプロンプトから作成されます。 - use_resolution_binning (
bool、デフォルトはTrue) —Trueに設定すると、要求された高さおよび幅は、ASPECT_RATIO_1024_BINを使用して最も近い解像度にマッピングされます。生成された潜在変数が画像にデコードされた後、要求された解像도에リサイズされます。正方形でない画像の生成に有用です。 - 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、デフォルトは300) —promptに使用する最大シーケンス長。 - complex_human_instruction (
list[str]、省略可) — 複雑な人間の注意に関する指示: https://github.com/NVlabs/Sana/blob/main/configs/sana_app_config/Sana_1600M_app.yaml#L55。
戻り値
SanaPipelineOutput または tuple
return_dict が True の場合、SanaPipelineOutput が返され、それ以外の場合は、最初の要素が生成された画像のリストである tuple が返されます。
生成用のパイプラインを呼び出したときに実行される関数。
例:
>>> import torch
>>> from diffusers import SanaControlNetPipeline
>>> from diffusers.utils import load_image
>>> pipe = SanaControlNetPipeline.from_pretrained(
... "ishan24/Sana_600M_1024px_ControlNetPlus_diffusers",
... variant="fp16",
... torch_dtype={"default": torch.bfloat16, "controlnet": torch.float16, "transformer": torch.float16},
... device_map="balanced",
... )
>>> cond_image = load_image(
... "https://huggingface.co/ishan24/Sana_600M_1024px_ControlNet_diffusers/resolve/main/hed_example.png"
... )
>>> prompt = 'a cat with a neon sign that says "Sana"'
>>> image = pipe(
... prompt,
... control_image=cond_image,
... ).images[0]
>>> image.save("output.png")encode_prompt
< source >( 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 = 300complex_human_instruction: list[str] | None = Nonelora_scale: float | None = None )
パラメータ
- 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, 任意) — 事前生成されたネガティブテキストの埋め込み。Sana の場合は、"" 文字列の埋め込みである必要があります。 - clean_caption (
bool、デフォルトはFalse) —Trueの場合、エンコード前に提供されたキャプションを前処理してクリーニングします。 - max_sequence_length (
int、デフォルト値は 300) — プロンプトに使用する最大シーケンス長。 - complex_human_instruction (
list[str]、デフォルトはcomplex_human_instruction) —complex_human_instructionが空でない場合、プロンプトに複雑な Human 指示を使用します。
プロンプトをテキストエンコーダーの隠れ状態にエンコードします。
SanaPipelineOutput
クラス diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput
< source >( images: list[PIL.Image.Image] | numpy.ndarray )
Sana パイプライン用の出力クラス。