Buckets:

hf-doc-build/doc / diffusers /main /ja /api /pipelines /controlnet_sana.md
mishig's picture
|
download
raw
18.9 kB

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[[diffusers.SanaControlNetPipeline]]

diffusers.SanaControlNetPipeline[[diffusers.SanaControlNetPipeline]]

diffusers.SanaControlNetPipeline(tokenizer: GemmaTokenizer, text_encoder: Gemma2PreTrainedModel, vae: AutoencoderDC, transformer: SanaTransformer2DModel, controlnet: SanaControlNetModel, scheduler: DPMSolverMultistepScheduler)

ソース

Sana を使用したテキストから画像への生成パイプライン。

call[[diffusers.SanaControlNetPipeline.call]]

__call__(prompt: str | list[str] = None, negative_prompt: str = '', num_inference_steps: int = 20, timesteps: list[int] = None, sigmas: list[float] = None, guidance_scale: float = 4.5, control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, controlnet_conditioning_scale: float | list[float] = 1.0, num_images_per_prompt: int | None = 1, height: int = 1024, width: int = 1024, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, clean_caption: bool = False, use_resolution_binning: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 300, complex_human_instruction: list[str] = ["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: '])

ソース

パラメータ:

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]、任意) : set_timesteps メソッドで 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, optional, デフォルトは 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](/docs/diffusers/main/ja/api/schedulers/ddim#diffusers.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[[diffusers.SanaControlNetPipeline.encode_prompt]]

encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, negative_prompt: str = '', num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, clean_caption: bool = False, max_sequence_length: int = 300, complex_human_instruction: list[str] | None = None, lora_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、optional、デフォルトは 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 instruction を使用します。

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

SanaPipelineOutput[[diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput]]

diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput[[diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput]]

diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray)

ソース

パラメータ:

images (list[PIL.Image.Image] または np.ndarray) : 長さ batch_size のデノイズ済み PIL イメージのリスト、または形状 (batch_size, height, width, num_channels) の numpy 配列。PIL イメージまたは numpy 配列は、拡散パイプラインのデノイズ済みイメージを表します。

Sana パイプライン用の出力クラス。

Xet Storage Details

Size:
18.9 kB
·
Xet hash:
4a0ff1c20684dd144b3e5b3800715b2fbc4ecd8c903b0079c6cb25a8e5cd54f2

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.