# Hunyuan-DiT と ControlNet

HunyuanDiTControlNetPipeline は [Hunyuan-DiT](https://huggingface.co/papers/2405.08748) 向けの ControlNet の実装です。

ControlNetは、Lvmin Zhang、Anyi Rao、Maneesh Agrawalaによる論文[Adding Conditional Control to Text-to-Image Diffusion Models](https://huggingface.co/papers/2302.05543)で提案されました。

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

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

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

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

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

## HunyuanDiTControlNetPipeline[[diffusers.HunyuanDiTControlNetPipeline]]

#### diffusers.HunyuanDiTControlNetPipeline[[diffusers.HunyuanDiTControlNetPipeline]]

```python
diffusers.HunyuanDiTControlNetPipeline(vae: AutoencoderKL, text_encoder: BertModel, tokenizer: BertTokenizer, transformer: HunyuanDiT2DModel, scheduler: DDPMScheduler, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, controlnet: 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.HunyuanDiT2DMultiControlNetModel, text_encoder_2: transformers.models.t5.modeling_t5.T5EncoderModel | None = None, tokenizer_2: transformers.models.t5.tokenization_t5.T5Tokenizer | None = None, requires_safety_checker: bool = True)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py#L165)

**パラメータ:**

vae ([AutoencoderKL](/docs/diffusers/main/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための Variational Auto-Encoder (VAE) モデルです。`sdxl-vae-fp16-fix` を使用します。

text_encoder (`~transformers.BertModel`、`~transformers.CLIPTextModel` | None) : 凍結されたテキストエンコーダー([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14))。HunyuanDiT は、ファインチューニングされた [bilingual CLIP] を使用しています。

tokenizer (`~transformers.BertTokenizer`、`~transformers.CLIPTokenizer` | None) : テキストをトークン化するための`BertTokenizer`または`CLIPTokenizer`。

transformer ([HunyuanDiT2DModel](/docs/diffusers/main/ja/api/models/hunyuan_transformer2d#diffusers.HunyuanDiT2DModel)) : Tencent Hunyuan によって設計された HunyuanDiT モデルです。

text_encoder_2 (`T5EncoderModel`) : mT5エンベッダーです。具体的には、't5-v1_1-xxl'です。

tokenizer_2 (`T5Tokenizer`) : mT5エンベッダー用のトークナイザー。

scheduler ([DDPMScheduler](/docs/diffusers/main/ja/api/schedulers/ddpm#diffusers.DDPMScheduler)) : HunyuanDiT と組み合わせて使用し、エンコードされた画像の潜在変数をデノイズするためのスケジューラ。

controlnet ([HunyuanDiT2DControlNetModel](/docs/diffusers/main/ja/api/models/controlnet_hunyuandit#diffusers.HunyuanDiT2DControlNetModel) または `list[HunyuanDiT2DControlNetModel]` または [HunyuanDiT2DControlNetModel](/docs/diffusers/main/ja/api/models/controlnet_hunyuandit#diffusers.HunyuanDiT2DControlNetModel)) : デノイジング処理中に `unet` へ追加の条件付けを提供します。リストとして複数の ControlNet を設定した場合、各 ControlNet の出力が加算され、1 つの統合された追加条件付けが作成されます。

HunyuanDiT を使用した英語/中国語から画像生成を行う Pipeline。

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

HunyuanDiTは2つのテキストエンコーダーを使用しています:[mT5](https://huggingface.co/google/mt5-base)と[bilingual CLIP](独自にファインチューニング済み)

#### __call__[[diffusers.HunyuanDiTControlNetPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, height: int | None = None, width: int | None = None, num_inference_steps: int | None = 50, guidance_scale: float | None = 5.0, 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, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float | None = 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_embeds_2: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds_2: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, prompt_attention_mask_2: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask_2: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], guidance_rescale: float = 0.0, original_size: tuple[int, int] | None = (1024, 1024), target_size: tuple[int, int] | None = None, crops_coords_top_left: tuple[int, int] = (0, 0), use_resolution_binning: bool = True)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py#L632)

**パラメータ:**

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](https://huggingface.co/papers/2010.02502)論文のパラメータ eta (η) に対応します。[DDIMScheduler](/docs/diffusers/main/ja/api/schedulers/ddim#diffusers.DDIMScheduler)でのみ適用され、他のスケジューラーでは無視されます。

generator (`torch.Generator` または `list[torch.Generator]`、*任意*) : 生成を決定論的にするための [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html)。

latents (`torch.Tensor`, *任意*) : 画像生成の入力として使用される、ガウス分布からサンプリングされた事前生成されたノイジー・ラテンツ。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム`generator`を使用してサンプリングを行い、ラテンツのテンソルが生成されます。

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_embeds` は `negative_prompt` 入力引数から生成されます。

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](/docs/diffusers/main/ja/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.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](https://huggingface.co/papers/2305.08891). See Section 3.4

original_size (`tuple[int, int]`、*任意*、デフォルトは`(1024, 1024)`) : 画像の元のサイズ。time ids の計算に使用されます。

target_size (`tuple[int, int]`、*optional*) : 画像のターゲットサイズ。time ids の計算に使用されます。

crops_coords_top_left (`tuple[int, int]`、*optional*、デフォルトは`(0, 0)`) : クロップの左上座標。time ids の計算に使用されます。

use_resolution_binning (`bool`、*任意*、デフォルトは`True`) : 解像度バインニングを使用するかどうかを指定します。`True`の場合、入力解像度は最も近い標準解像度に変換されます。サポートされている解像度は、1024x1024、1280x1280、1024x768、1152x864、1280x960、768x1024、864x1152、960x1280、1280x768、768x1280です。この値を`True`に設定することを推奨します。

**戻り値:** [StableDiffusionPipelineOutput](/docs/diffusers/main/ja/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) または `tuple`

If `return_dict` is `True`, [StableDiffusionPipelineOutput](/docs/diffusers/main/ja/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.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 `bool`s indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.

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

例:
```py
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[[diffusers.HunyuanDiTControlNetPipeline.encode_prompt]]

```python
encode_prompt(prompt: str, device: device = None, dtype: dtype = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | None = 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, max_sequence_length: int | None = None, text_encoder_index: int = 0)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py#L276)

**パラメータ:**

prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト

device : (`torch.device`): torch デバイス

dtype (`torch.dtype`) : torch dtype

num_images_per_prompt (`int`) : プロンプトごとに生成すべき画像の数

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`, *optional*) : 使用するテキストエンコーダーのインデックス。clip は `0`、T5 は `1` です。

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

