# Hunyuan-DiT
![chinese elements understanding](https://github.com/gnobitab/diffusers-hunyuan/assets/1157982/39b99036-c3cb-4f16-bb1a-40ec25eda573)

Tencent Hunyuan による [Hunyuan-DiT : A Powerful Multi-Resolution Diffusion Transformer with Fine-Grained Chinese Understanding](https://huggingface.co/papers/2405.08748)

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

*We present Hunyuan-DiT, a text-to-image diffusion transformer with fine-grained understanding of both English and Chinese. To construct Hunyuan-DiT, we carefully design the transformer structure, text encoder, and positional encoding. We also build from scratch a whole data pipeline to update and evaluate data for iterative model optimization. For fine-grained language understanding, we train a Multimodal Large Language Model to refine the captions of the images. Finally, Hunyuan-DiT can perform multi-turn multimodal dialogue with users, generating and refining images according to the context. Through our holistic human evaluation protocol with more than 50 professional human evaluators, Hunyuan-DiT sets a new state-of-the-art in Chinese-to-image generation compared with other open-source models.*

元のコードベースは[Tencent/HunyuanDiT](https://github.com/Tencent/HunyuanDiT)、利用可能なすべてのチェックポイントは[Tencent-Hunyuan](https://huggingface.co/Tencent-Hunyuan/HunyuanDiT)で確認できます。

**ハイライト**: HunyuanDiTは中国語/英語から画像への生成、および複数解像度での生成に対応しています。

HunyuanDiTには、以下のコンポーネントが含まれます。
* diffusion transformerをバックボーンとして使用しています
* 2つのテキストエンコーダー、バイリンガルCLIPと多言語T5エンコーダーを組み合わせています。

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

> [!TIP]
> `HungyuanDiTPipeline`で生成された画像を[SDXL refiner](./stable_diffusion/stable_diffusion_xl#base-to-refiner-model)モデルに渡すことで、生成品質をさらに向上させることができます。

## 最適化

[最適化とスケーリング](../../optimization/overview#optimization-techniques)を参照して、他の最適化方法について学ぶことができます。torch.compile とフィードフォワードチャンクングを使用して、パイプラインの実行時間とメモリ消費量を最適化できます。

### 推論

[`torch.compile`](../../optimization/fp16#torchcompile) を使用して、推論のレイテンシを低減します。

まず、パイプラインを読み込みます:

```python
from diffusers import HunyuanDiTPipeline
import torch

pipeline = HunyuanDiTPipeline.from_pretrained(
	"Tencent-Hunyuan/HunyuanDiT-Diffusers", dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"
```

次に、パイプラインの `transformer` と `vae` コンポーネントのメモリレイアウトを `torch.channels-last` に変更します:

```python
pipeline.transformer.to(memory_format=torch.channels_last)
pipeline.vae.to(memory_format=torch.channels_last)
```

最後に、コンポーネントをコンパイルして推論を実行します。

```python
pipeline.transformer = torch.compile(pipeline.transformer, mode="max-autotune", fullgraph=True)
pipeline.vae.decode = torch.compile(pipeline.vae.decode, mode="max-autotune", fullgraph=True)

image = pipeline(prompt="一个宇航员在骑马").images[0]
```

80GB A100マシンでの[ベンチマーク](https://gist.github.com/sayakpaul/29d3a14905cfcbf611fe71ebd22e9b23)結果は以下の通りです:

```bash
With torch.compile(): Average inference time: 12.470 seconds.
Without torch.compile(): Average inference time: 20.570 seconds.
```

### メモリ最適化

T5テキストエンコーダーを8ビットで読み込むことで、GPU VRAMをわずか6 GB未満でパイプラインを実行できます。詳細は[このスクリプト](https://gist.github.com/sayakpaul/3154605f6af05b98a41081aaba5ca43e)を参照してください。

さらに、[enable_forward_chunking()](/docs/diffusers/main/ja/api/models/hunyuan_transformer2d#diffusers.HunyuanDiT2DModel.enable_forward_chunking) メソッドを使用してメモリ使用量を削減できます。フィードフォワードチャンクングでは、トランスフォーマーブロック内のフィードフォワード層を一度に実行するのではなく、ループ内で実行します。これにより、メモリ消費量と推論実行時間のトレードオフを調整できます。

```diff
+ pipeline.transformer.enable_forward_chunking(chunk_size=1, dim=1)
```

## HunyuanDiTPipeline[[diffusers.HunyuanDiTPipeline]]

#### diffusers.HunyuanDiTPipeline[[diffusers.HunyuanDiTPipeline]]

```python
diffusers.HunyuanDiTPipeline(vae: AutoencoderKL, text_encoder: BertModel, tokenizer: BertTokenizer, transformer: HunyuanDiT2DModel, scheduler: DDPMScheduler, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, requires_safety_checker: bool = True, text_encoder_2: transformers.models.t5.modeling_t5.T5EncoderModel | None = None, tokenizer_2: transformers.models.t5.tokenization_t5.T5Tokenizer | None = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py#L149)

**パラメータ:**

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 と組み合わせて使用し、エンコードされた画像の潜在変数をデノイズするためのスケジューラ。

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.HunyuanDiTPipeline.__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, 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/hunyuandit/pipeline_hunyuandit.py#L568)

**パラメータ:**

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](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
>>> import torch
>>> from diffusers import HunyuanDiTPipeline

>>> pipe = HunyuanDiTPipeline.from_pretrained(
...     "Tencent-Hunyuan/HunyuanDiT-Diffusers", torch_dtype=torch.float16
... )
>>> pipe.to("cuda")

>>> # You may also use English prompt as HunyuanDiT supports both English and Chinese
>>> # prompt = "An astronaut riding a horse"
>>> prompt = "一个宇航员在骑马"
>>> image = pipe(prompt).images[0]
```

#### encode_prompt[[diffusers.HunyuanDiTPipeline.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/hunyuandit/pipeline_hunyuandit.py#L248)

**パラメータ:**

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` です。

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

