Diffusers documentation

Hunyuan-DiT と ControlNet

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.43.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Hunyuan-DiT と ControlNet

HunyuanDiTControlNetPipeline は Hunyuan-DiT 向けの ControlNet の実装です。

ControlNetは、Lvmin Zhang、Anyi Rao、Maneesh Agrawalaによる論文Adding Conditional Control to Text-to-Image Diffusion Modelsで提案されました。

ControlNetモデルを使用すると、追加の制御画像を指定してHunyuan-DiTの生成を条件付け・制御できます。例えば、深度マップを指定すると、ControlNetモデルは深度マップの空間情報を保持した画像を生成します。これは、画像生成プロセスをより柔軟かつ正確に制御する方法です。

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

本稿では、大規模な事前学習済みテキストから画像への拡散モデルに空間的条件付け制御を追加するためのニューラルネットワークアーキテクチャであるControlNetを提案します。ControlNetは、実運用可能な大規模拡散モデルを固定し、数十億枚の画像で事前学習された深く頑健なエンコーディング層を強力なバックボーンとして再利用することで、多様な条件付け制御のセットを学習します。このニューラルアーキテクチャは、「ゼロ畳み込み」(ゼロ初期化された畳み込み層)によって接続されており、パラメータをゼロから段階的に増加させ、有害なノイズがファインチューニングに影響を与えないことを保証します。Stable Diffusionを用いて、エッジ、深度、セグメンテーション、人間のポーズなどの様々な条件付け制御を、プロンプトの有無にかかわらず、単一または複数の条件を用いてテストしました。ControlNetの学習は、小規模(<50k)および大規模(>1m)のデータセットのいずれにおいても頑健であることが示されています。広範な結果から、ControlNetは画像拡散モデルの制御に関するより幅広いアプリケーションを促進し得ることが示されました。

このコードは Tencent Hunyuan Team によって実装されています。Hunyuan-DiT ControlNets の事前学習済みチェックポイントは Tencent Hunyuan で入手できます。

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

HunyuanDiTControlNetPipeline

class diffusers.HunyuanDiTControlNetPipeline

< >

( vae: AutoencoderKLtext_encoder: BertModeltokenizer: BertTokenizertransformer: HunyuanDiT2DModelscheduler: DDPMSchedulersafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilcontrolnet: diffusers.models.controlnets.controlnet_hunyuan.HunyuanDiT2DControlNetModel | list[diffusers.models.controlnets.controlnet_hunyuan.HunyuanDiT2DControlNetModel] | tuple[diffusers.models.controlnets.controlnet_hunyuan.HunyuanDiT2DControlNetModel] | diffusers.models.controlnets.controlnet_hunyuan.HunyuanDiT2DMultiControlNetModeltext_encoder_2: transformers.models.t5.modeling_t5.T5EncoderModel | None = Nonetokenizer_2: transformers.models.t5.tokenization_t5.T5Tokenizer | None = Nonerequires_safety_checker: bool = True )

パラメータ

  • 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 と組み合わせて使用し、エンコードされた画像の潜在変数からノイズを除去するためのスケジューラ。
  • controlnet (HunyuanDiT2DControlNetModel または list[HunyuanDiT2DControlNetModel] または HunyuanDiT2DControlNetModel) — デノイジング処理中に unet に追加の条件付けを提供します。リストとして複数の ControlNet を設定した場合、各 ControlNet の出力が加算され、1 つの統合された追加条件付けが作成されます。

HunyuanDiT を使用した英語/中国語から画像生成を行う 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 | None = 50guidance_scale: float | None = 5.0control_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.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float | None = 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 | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']guidance_rescale: float = 0.0original_size: tuple[int, int] | None = (1024, 1024)target_size: tuple[int, int] | None = Nonecrops_coords_top_left: tuple[int, int] = (0, 0)use_resolution_binning: bool = True ) → 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 が有効になります。
  • 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 が指定されている場合、対応するスケールをリストとして設定できます。
  • 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 に設定することを推奨します。

戻り値

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

例:

from diffusers import HunyuanDiT2DControlNetModel, HunyuanDiTControlNetPipeline
import torch

controlnet = HunyuanDiT2DControlNetModel.from_pretrained(
    "Tencent-Hunyuan/HunyuanDiT-v1.1-ControlNet-Diffusers-Canny", torch_dtype=torch.float16
)

pipe = HunyuanDiTControlNetPipeline.from_pretrained(
    "Tencent-Hunyuan/HunyuanDiT-v1.1-Diffusers", controlnet=controlnet, torch_dtype=torch.float16
)
pipe.to("cuda")

from diffusers.utils import load_image

cond_image = load_image(
    "https://huggingface.co/Tencent-Hunyuan/HunyuanDiT-v1.1-ControlNet-Diffusers-Canny/resolve/main/canny.jpg?download=true"
)

## You may also use English prompt as HunyuanDiT supports both English and Chinese
prompt = "在夜晚的酒店门前,一座古老的中国风格的狮子雕像矗立着,它的眼睛闪烁着光芒,仿佛在守护着这座建筑。背景是夜晚的酒店前,构图方式是特写,平视,居中构图。这张照片呈现了真实摄影风格,蕴含了中国雕塑文化,同时展现了神秘氛围"
# prompt="At night, an ancient Chinese-style lion statue stands in front of the hotel, its eyes gleaming as if guarding the building. The background is the hotel entrance at night, with a close-up, eye-level, and centered composition. This photo presents a realistic photographic style, embodies Chinese sculpture culture, and reveals a mysterious atmosphere."
image = pipe(
    prompt,
    height=1024,
    width=1024,
    control_image=cond_image,
    num_inference_steps=50,
).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 です。

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

Update on GitHub