#
# Apache License, Version 2.0（「ライセンス」）の下でライセンスされています。
# このファイルは、ライセンスに準拠した場合にのみ使用できます。
# ライセンスのコピーは以下から入手できます
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 適用される法律で要求される場合、または書面による合意がある場合を除き、ソフトウェア
# ライセンスに基づき配布される本ソフトウェアは、「現状のまま」
# 明示的または黙示的を問わず、いかなる種類の保証や条件も付随しません。
# 権限を管理する特定の言語については、ライセンスを参照してください。
# ライセンスの下での制限。-->

  
    
      
    
  

# HunyuanVideo

[HunyuanVideo](https://huggingface.co/papers/2412.03603) は、クローズドソースの動画基盤モデルと競争力を持ち、より広いコミュニティへのアクセスを可能にするよう設計された、13B パラメータの拡散トランスフォーマーモデルです。このモデルは「デュアルストリームからシングルストリームへ」のアーキテクチャを採用し、まず動画トークンとテキストトークンをそれぞれ個別に処理した上で、それらを連結してトランスフォーマーに投入し、マルチモーダル情報を融合します。エンコーダーには事前学習済みのマルチモーダル大規模言語モデル（MLLM）が使用されており、これは画像とテキストの整合性、画像の詳細な記述および推論能力が優れているためです。また、ユーザープロンプトにシステム指示を追加することで、ゼロショットラーナーとしても利用できます。最後に、HunyuanVideo は 3D 因果的変分オートエンコーダーを使用し、元の解像度とフレームレートで動画データをより効率的に処理します。

すべてのオリジナルのHunyuanVideoチェックポイントは、[Tencent](https://huggingface.co/tencent)組織の下で見つけることができます。

> [!TIP]
> HunyuanVideo モデルのより多くの動画生成タスクの例については、右側のサイドバーをクリックしてください。
>
> 以下の例では、[hunyuanvideo-community](https://huggingface.co/hunyuanvideo-community) のチェックポイントを使用しています。これは、重みが Diffusers と互換性のあるレイアウトで保存されているためです。

以下の例では、メモリまたは推論速度に最適化されたビデオを生成する方法を示しています。

メモリ使用量の削減に関する詳細については、[メモリ使用量の削減](../../optimization/memory)ガイドを参照してください。

以下の量子化されたHunyuanVideoモデルには、約14GBのVRAMが必要です。

```py
import torch
from diffusers import AutoModel, HunyuanVideoPipeline
from diffusers.quantizers import PipelineQuantizationConfig
from diffusers.utils import export_to_video

# quantize weights to int4 with bitsandbytes
pipeline_quant_config = PipelineQuantizationConfig(
    quant_backend="bitsandbytes_4bit",
    quant_kwargs={
      "load_in_4bit": True,
      "bnb_4bit_quant_type": "nf4",
      "bnb_4bit_compute_dtype": torch.bfloat16
      },
    components_to_quantize="transformer"
)

pipeline = HunyuanVideoPipeline.from_pretrained(
    "hunyuanvideo-community/HunyuanVideo",
    quantization_config=pipeline_quant_config,
    dtype=torch.bfloat16,
)

# model-offloading and tiling
pipeline.enable_model_cpu_offload()
pipeline.vae.enable_tiling()

prompt = "A fluffy teddy bear sits on a bed of soft pillows surrounded by children's toys."
video = pipeline(prompt=prompt, num_frames=61, num_inference_steps=30).frames[0]
export_to_video(video, "output.mp4", fps=15)
```

[Compilation](../../optimization/fp16#torchcompile)は初回に時間がかかりますが、その後のpipeline呼び出しは高速になります。

```py
import torch
from diffusers import AutoModel, HunyuanVideoPipeline
from diffusers.quantizers import PipelineQuantizationConfig
from diffusers.utils import export_to_video

# quantize weights to int4 with bitsandbytes
pipeline_quant_config = PipelineQuantizationConfig(
    quant_backend="bitsandbytes_4bit",
    quant_kwargs={
      "load_in_4bit": True,
      "bnb_4bit_quant_type": "nf4",
      "bnb_4bit_compute_dtype": torch.bfloat16
      },
    components_to_quantize="transformer"
)

pipeline = HunyuanVideoPipeline.from_pretrained(
    "hunyuanvideo-community/HunyuanVideo",
    quantization_config=pipeline_quant_config,
    dtype=torch.bfloat16,
)

# model-offloading and tiling
pipeline.enable_model_cpu_offload()
pipeline.vae.enable_tiling()

# torch.compile
pipeline.transformer.to(memory_format=torch.channels_last)
pipeline.transformer = torch.compile(
    pipeline.transformer, mode="max-autotune", fullgraph=True
)

prompt = "A fluffy teddy bear sits on a bed of soft pillows surrounded by children's toys."
video = pipeline(prompt=prompt, num_frames=61, num_inference_steps=30).frames[0]
export_to_video(video, "output.mp4", fps=15)
```

## 注記

- HunyuanVideoは、[load_lora_weights()](/docs/diffusers/main/ja/api/loaders/lora#diffusers.loaders.HunyuanVideoLoraLoaderMixin.load_lora_weights)によるLoRAをサポートしています。

  
  サンプルコードを表示

  ```py
  import torch
  from diffusers import AutoModel, HunyuanVideoPipeline
  from diffusers.quantizers import PipelineQuantizationConfig
  from diffusers.utils import export_to_video

  # quantize weights to int4 with bitsandbytes
  pipeline_quant_config = PipelineQuantizationConfig(
      quant_backend="bitsandbytes_4bit",
      quant_kwargs={
        "load_in_4bit": True,
        "bnb_4bit_quant_type": "nf4",
        "bnb_4bit_compute_dtype": torch.bfloat16
        },
      components_to_quantize="transformer"
  )

  pipeline = HunyuanVideoPipeline.from_pretrained(
      "hunyuanvideo-community/HunyuanVideo",
      quantization_config=pipeline_quant_config,
      dtype=torch.bfloat16,
  )

  # load LoRA weights
  pipeline.load_lora_weights("https://huggingface.co/lucataco/hunyuan-steamboat-willie-10", adapter_name="steamboat-willie")
  pipeline.set_adapters("steamboat-willie", 0.9)

  # model-offloading and tiling
  pipeline.enable_model_cpu_offload()
  pipeline.vae.enable_tiling()

  # use "In the style of SWR" to trigger the LoRA
  prompt = """
  In the style of SWR. A black and white animated scene featuring a fluffy teddy bear sits on a bed of soft pillows surrounded by children's toys.
  """
  video = pipeline(prompt=prompt, num_frames=61, num_inference_steps=30).frames[0]
  export_to_video(video, "output.mp4", fps=15)
  ```

  

- 推奨される推論値については、以下の表を参照してください。

  | パラメータ | 推奨値 |
  |---|---|
  | テキストエンコーダーのdtype | `torch.float16` |
  | transformer dtype | `torch.bfloat16` |
  | VAEのdtype | `torch.float16` |
  | `num_frames (k)` | 4 * `k` + 1 |

- 低解像度の動画には低い`shift`値(`2.0`から`5.0`)を、高解像度の画像には高い`shift`値(`7.0`から`12.0`)を使用してください。

## HunyuanVideoPipeline[[diffusers.HunyuanVideoPipeline]]

#### diffusers.HunyuanVideoPipeline[[diffusers.HunyuanVideoPipeline]]

```python
diffusers.HunyuanVideoPipeline(text_encoder: LlamaModel, tokenizer: LlamaTokenizer, transformer: HunyuanVideoTransformer3DModel, vae: AutoencoderKLHunyuanVideo, scheduler: FlowMatchEulerDiscreteScheduler, text_encoder_2: CLIPTextModel, tokenizer_2: CLIPTokenizer)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py#L144)

**パラメータ:**

text_encoder (`LlamaModel`) : [Llava Llama3-8B](https://huggingface.co/xtuner/llava-llama-3-8b-v1_1-transformers)。

tokenizer (`LlamaTokenizer`) : [Llava Llama3-8B](https://huggingface.co/xtuner/llava-llama-3-8b-v1_1-transformers)のTokenizer。

transformer ([HunyuanVideoTransformer3DModel](/docs/diffusers/main/ja/api/models/hunyuan_video_transformer_3d#diffusers.HunyuanVideoTransformer3DModel)) : エンコードされた画像の潜在変数をデノイズするための条件付き Transformer。

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

vae ([AutoencoderKLHunyuanVideo](/docs/diffusers/main/ja/api/models/autoencoder_kl_hunyuan_video#diffusers.AutoencoderKLHunyuanVideo)) : 動画を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ（VAE）モデル。

text_encoder_2 (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)、具体的には [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) バリアントです。

tokenizer_2 (`CLIPTokenizer`) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) の Tokenizer。

HunyuanVideo を使用したテキストから動画への生成を行う Pipeline です。

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

#### __call__[[diffusers.HunyuanVideoPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] = None, negative_prompt: str | list[str] = None, negative_prompt_2: str | list[str] = None, height: int = 720, width: int = 1280, num_frames: int = 129, num_inference_steps: int = 50, sigmas: list[float] = None, true_cfg_scale: float = 1.0, guidance_scale: float = 6.0, num_videos_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_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, attention_kwargs: dict[str, typing.Any] | None = None, 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'], prompt_template: dict[str, typing.Any] = {'template': '<|start_header_id|>system<|end_header_id|>\n\nDescribe the video by detailing the following aspects: 1. The main content and theme of the video.2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects.3. Actions, events, behaviors temporal relationships, physical movement changes of the objects.4. background environment, light, style and atmosphere.5. camera angles, movements, and transitions used in the video:<|eot_id|><|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>', 'crop_start': 95}, max_sequence_length: int = 256)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py#L438)

**パラメータ:**

prompt (`str` または `list[str]`、*省略可*) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。

prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。定義されていない場合、代わりに `prompt` が使用されます。

negative_prompt (`str` または `list[str]`、*省略可能*) : 画像生成をガイドしないプロンプトです。未定義の場合、代わりに `negative_prompt_embeds` を渡す必要があります。ガイダンスを使用していない場合は無視されます（`true_cfg_scale` が `1` 以下の場合に無視されます）。

negative_prompt_2 (`str` または `list[str]`、*任意*) : 画像生成を誘導しないプロンプト、またはプロンプトのリストです。`tokenizer_2` および `text_encoder_2` に送信されます。定義されていない場合、すべてのテキストエンコーダーで `negative_prompt` が使用されます。

height (`int`、デフォルトは`720`) : 生成される画像のピクセル単位の縦幅。

width (`int`、デフォルトは`1280`) : 生成される画像の幅（ピクセル単位）。

num_frames (`int`、デフォルトは`129`) : 生成される動画のフレーム数。

num_inference_steps (`int`、デフォルトは`50`) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。

sigmas (`list[float]`, *任意*) : `set_timesteps` メソッドで `sigmas` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムシグマ。`num_inference_steps` が渡された場合のデフォルトの動作が使用されます。

true_cfg_scale (`float`、*任意*、デフォルト値は 1.0) : `true_cfg_scale` > 1 かつ `negative_prompt` が指定されている場合、True classifier-free guidance（guidance scale）が有効になります。

guidance_scale (`float`、デフォルトは`6.0`) : `guidance_scale` > 1 を設定することで、埋め込み型ガイダンススケールが有効になります。`guidance_scale` を高くすると、`prompt` により一貫性のある画像を生成するようモデルが促されますが、画像の品質が低下する可能性があります。ガイダンス蒸留モデルは、`guidance_scale` > 1 に対して、真のクラスフリーガイダンスを近似します。詳細については、[論文](https://huggingface.co/papers/2210.03142)を参照してください。

num_videos_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。

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` 入力引数からテキスト埋め込みが生成されます。

pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。

negative_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたネガティブなテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`negative_prompt` 入力引数から negative_prompt_embeds が生成されます。

negative_pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたネガティブなプールのテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`negative_prompt` 入力引数からプールの negative_prompt_embeds が生成されます。

prompt_attention_mask (`torch.Tensor`、*任意*) : `prompt_embeds`用のアテンションマスク。`prompt_embeds`が直接渡される場合に必要です。

negative_prompt_attention_mask (`torch.Tensor`, *任意*) : `negative_prompt_embeds`用のアテンションマスク。`negative_prompt_embeds`が直接渡される場合に必要です。

output_type (`str`、*任意*、デフォルトは`"pil"`) : 生成された画像の出力形式。`PIL.Image`または`np.array`から選択します。

return_dict (`bool`、*任意*、デフォルトは`True`) : プレーンなタプルではなく`HunyuanVideoPipelineOutput`を返すかどうか。

attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。

prompt_template (`dict`, *任意*) : エンコード前にプロンプトを整形するために使用されるテンプレート。デフォルトでは、モデルのデフォルトテンプレートが使用されます。

max_sequence_length (`int`、*任意*、デフォルトは 256) : プロンプトエンコーダーに使用する最大シーケンス長。

callback_on_step_end (`Callable`、`PipelineCallback`、`MultiPipelineCallbacks`、*任意*) : 推論中の各デノイジングステップの終了時に呼び出される関数、または `PipelineCallback` または `MultiPipelineCallbacks` のサブクラスです。以下の引数を持ちます: `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` 属性に列挙された変数のみを、リストに含めることができます。

**戻り値:** `~HunyuanVideoPipelineOutput` または `tuple`

`return_dict` が `True` の場合、`HunyuanVideoPipelineOutput` が返され、それ以外の場合は `tuple` が返されます。この `tuple` の最初の要素は生成された画像のリストであり、2番目の要素は、対応する生成画像に「not-safe-for-work」（nsfw）コンテンツが含まれているかどうかを示す `bool` のリストです。

生成用の pipeline への呼び出し関数。

例:
```python
>>> import torch
>>> from diffusers import HunyuanVideoPipeline, HunyuanVideoTransformer3DModel
>>> from diffusers.utils import export_to_video

>>> model_id = "hunyuanvideo-community/HunyuanVideo"
>>> transformer = HunyuanVideoTransformer3DModel.from_pretrained(
...     model_id, subfolder="transformer", torch_dtype=torch.bfloat16
... )
>>> pipe = HunyuanVideoPipeline.from_pretrained(model_id, transformer=transformer, torch_dtype=torch.float16)
>>> pipe.vae.enable_tiling()
>>> pipe.to("cuda")

>>> output = pipe(
...     prompt="A cat walks on the grass, realistic",
...     height=320,
...     width=512,
...     num_frames=61,
...     num_inference_steps=30,
... ).frames[0]
>>> export_to_video(output, "output.mp4", fps=15)
```

## HunyuanVideoPipelineOutput[[diffusers.pipelines.hunyuan_video.pipeline_output.HunyuanVideoPipelineOutput]]

#### diffusers.pipelines.hunyuan_video.pipeline_output.HunyuanVideoPipelineOutput[[diffusers.pipelines.hunyuan_video.pipeline_output.HunyuanVideoPipelineOutput]]

```python
diffusers.pipelines.hunyuan_video.pipeline_output.HunyuanVideoPipelineOutput(frames: Tensor)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/hunyuan_video/pipeline_output.py#L11)

**パラメータ:**

frames (`torch.Tensor`、`np.ndarray`、または list[list[PIL.Image.Image]]) : 動画出力のリスト - `batch_size,` 長のネストされたリストであり、各サブリストには `num_frames.` 長のデノイズ済み PIL 画像シーケンスが含まれる場合があります。また、`(batch_size, num_frames, channels, height, width)` の形状を持つ NumPy 配列や Torch テンソルである場合もあります。

HunyuanVideo パイプライン用の出力クラスです。

