Diffusers documentation

HunyuanVideo

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

and get access to the augmented documentation experience

to get started

LoRA

HunyuanVideo

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

すべてのオリジナルのHunyuanVideoチェックポイントは、Tencent組織の下で見つけることができます。

HunyuanVideo モデルのより多くの動画生成タスクの例については、右側のサイドバーをクリックしてください。

以下の例では、hunyuanvideo-community のチェックポイントを使用しています。これは、重みが Diffusers と互換性のあるレイアウトで保存されているためです。

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

メモリ
推論速度

メモリ使用量の削減に関する詳細については、メモリ使用量の削減ガイドを参照してください。

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

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)

注記

  • HunyuanVideoは、load_lora_weights()によるLoRAをサポートしています。

    サンプルコードを表示
    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)
  • 推奨される推論値については、以下の表を参照してください。

    パラメータ推奨値
    テキストエンコーダーのdtypetorch.float16
    transformer dtypetorch.bfloat16
    VAEのdtypetorch.float16
    num_frames (k)4 * k + 1
  • 低解像度の動画には低いshift値(2.0から5.0)を、高解像度の画像には高いshift値(7.0から12.0)を使用してください。

HunyuanVideoPipeline

class diffusers.HunyuanVideoPipeline

< >

( text_encoder: LlamaModeltokenizer: LlamaTokenizertransformer: HunyuanVideoTransformer3DModelvae: AutoencoderKLHunyuanVideoscheduler: FlowMatchEulerDiscreteSchedulertext_encoder_2: CLIPTextModeltokenizer_2: CLIPTokenizer )

パラメータ

  • text_encoder (LlamaModel) — Llava Llama3-8B。
  • tokenizer (LlamaTokenizer) — Llava Llama3-8B の Tokenizer。
  • transformer (HunyuanVideoTransformer3DModel) — エンコードされた画像の潜在変数からノイズを除去するための条件付き Transformer です。
  • scheduler (FlowMatchEulerDiscreteScheduler) — transformer と組み合わせて、エンコードされた画像の潜在変数からノイズを除去するために使用するスケジューラ。
  • vae (AutoencoderKLHunyuanVideo) — 潜在表現へのエンコードとデコードを行う、動画用の変分オートエンコーダ (VAE) モデル。
  • text_encoder_2 (CLIPTextModel) — CLIP、具体的には clip-vit-large-patch14 バリアントです。
  • tokenizer_2 (CLIPTokenizer) — CLIPTokenizer クラスのトークナイザー。

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

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

__call__

< >

( prompt: str | list[str] = Noneprompt_2: str | list[str] = Nonenegative_prompt: str | list[str] = Nonenegative_prompt_2: str | list[str] = Noneheight: int = 720width: int = 1280num_frames: int = 129num_inference_steps: int = 50sigmas: list = Nonetrue_cfg_scale: float = 1.0guidance_scale: float = 6.0num_videos_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']prompt_template: dict = {'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 ) → ~HunyuanVideoPipelineOutput or tuple

パラメータ

  • 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-distilled モデルは、guidance_scale > 1 の場合に、真の classifer-free guidance を近似します。詳細については、論文を参照してください。

  • num_videos_per_prompt (int、省略可能、デフォルト値は 1)— プロンプトごとに生成する画像の数。
  • generator (torch.Generator または list[torch.Generator]、省略可) — 生成を決定論的にするための torch.Generator。
  • latents (torch.Tensor, 任意) — ガウス分布からサンプリングされた事前生成されたノイズ付き latents。画像生成のインプットとして使用します。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム generator を用いてサンプリングを行い、latents テンソルが生成されます。
  • 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 で定義されている 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 への呼び出し関数。

例:

>>> 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

< >

( frames: Tensor )

パラメータ

  • frames (torch.Tensor, np.ndarray, or list[list[PIL.Image.Image]]) — 動画出力のリストです。batch_size, 長のネストされたリストであり、各サブリストが num_frames. 長のノイズ除去済み PIL 画像シーケンスを含む形式をとることもできます。また、(batch_size, num_frames, channels, height, width) の形状を持つ NumPy 配列や Torch テンソルとしても指定できます。

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

Update on GitHub