Diffusers documentation
Framepack
Framepack
Lvmin Zhang と Maneesh Agrawala による 動画生成のための次フレーム予測モデルにおける入力フレームコンテキストのパッキング
動画生成のための次フレーム(または次フレームセクション)予測モデルを訓練するためのニューラルネットワーク構造、FramePack を提案します。FramePack は入力フレームを圧縮することで、動画の長さに依存せず、transformer のコンテキスト長を固定した数にします。その結果、計算上のボトルネックが画像拡散と類似した状態で、動画拡散を用いて大量のフレームを処理できるようになります。これにより、訓練時の動画バッチサイズを大幅に高めることも可能になります(バッチサイズが画像拡散の訓練と同等のレベルになります)。また、露出バイアス(反復に伴う誤差の蓄積)を回避するために、早期に確立された端点を用いて逆の時間順序でフレームを生成する、ドリフト防止サンプリング手法も提案します。最後に、既存の動画拡散モデルを FramePack でファインチューニングできることを示し、次フレーム予測により、より極端なフローシフトタイムステップを持つ、よりバランスの取れた拡散スケジューラをサポートできるため、視覚的な品質が向上する可能性があることを示します。
スケジューラーのトレードオフ、すなわち速度と品質のバランスをどのように探求するかを学ぶには、ガイドを必ずご確認ください。また、同じコンポーネントを複数のパイプラインに効率的に読み込む方法については、パイプライン間でコンポーネントを再利用するセクションを参照してください。
利用可能なモデル
| モデル名 | 説明 |
|---|---|
- lllyasviel/FramePackI2V_HY | 論文に記載されている「inverted anti-drifting」戦略を用いて学習されています。パイプラインの実行時に、推論にはsampling_type="inverted_anti_drifting"を設定する必要があります。 |
- lllyasviel/FramePack_F1_I2V_HY_20250503 | 新しいアンチドリフティング戦略で訓練されていますが、推論は論文で説明されている「バニラ」戦略で行われます。推論には、パイプラインの実行時にsampling_type="vanilla"を設定する必要があります。 |
使用方法
基本的な使用例については、pipelineのドキュメントを参照してください。次のセクションでは、オフローディング、異なるサンプリング手法、量子化などの例を掲載しています。
最初のフレームと最後のフレームから動画へ
Framepack を開始画像と終了画像の制御とともに使用する方法を示す例を以下に示します。ここでは、逆転ドリフト防止サンプリングモデルを使用しています。
import torch
from diffusers import HunyuanVideoFramepackPipeline, HunyuanVideoFramepackTransformer3DModel
from diffusers.utils import export_to_video, load_image
from transformers import SiglipImageProcessor, SiglipVisionModel
transformer = HunyuanVideoFramepackTransformer3DModel.from_pretrained(
"lllyasviel/FramePackI2V_HY", dtype=torch.bfloat16
)
feature_extractor = SiglipImageProcessor.from_pretrained(
"lllyasviel/flux_redux_bfl", subfolder="feature_extractor"
)
image_encoder = SiglipVisionModel.from_pretrained(
"lllyasviel/flux_redux_bfl", subfolder="image_encoder", dtype=torch.float16
)
pipe = HunyuanVideoFramepackPipeline.from_pretrained(
"hunyuanvideo-community/HunyuanVideo",
transformer=transformer,
feature_extractor=feature_extractor,
image_encoder=image_encoder,
dtype=torch.float16,
)
# Enable memory optimizations
pipe.enable_model_cpu_offload()
pipe.vae.enable_tiling()
prompt = "CG animation style, a small blue bird takes off from the ground, flapping its wings. The bird's feathers are delicate, with a unique pattern on its chest. The background shows a blue sky with white clouds under bright sunshine. The camera follows the bird upward, capturing its flight and the vastness of the sky from a close-up, low-angle perspective."
first_image = load_image(
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_first_frame.png"
)
last_image = load_image(
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_last_frame.png"
)
output = pipe(
image=first_image,
last_image=last_image,
prompt=prompt,
height=512,
width=512,
num_frames=91,
num_inference_steps=30,
guidance_scale=9.0,
generator=torch.Generator().manual_seed(0),
sampling_type="inverted_anti_drifting",
).frames[0]
export_to_video(output, "output.mp4", fps=30)バニラサンプリング
Framepack を F1 モデルに使用する方法を示す例を以下に示します。このモデルは、バニラサンプリングで訓練されていますが、ドリフト防止には新しいレギュレーションアプローチが採用されています。
import torch
from diffusers import HunyuanVideoFramepackPipeline, HunyuanVideoFramepackTransformer3DModel
from diffusers.utils import export_to_video, load_image
from transformers import SiglipImageProcessor, SiglipVisionModel
transformer = HunyuanVideoFramepackTransformer3DModel.from_pretrained(
"lllyasviel/FramePack_F1_I2V_HY_20250503", dtype=torch.bfloat16
)
feature_extractor = SiglipImageProcessor.from_pretrained(
"lllyasviel/flux_redux_bfl", subfolder="feature_extractor"
)
image_encoder = SiglipVisionModel.from_pretrained(
"lllyasviel/flux_redux_bfl", subfolder="image_encoder", dtype=torch.float16
)
pipe = HunyuanVideoFramepackPipeline.from_pretrained(
"hunyuanvideo-community/HunyuanVideo",
transformer=transformer,
feature_extractor=feature_extractor,
image_encoder=image_encoder,
dtype=torch.float16,
)
# Enable memory optimizations
pipe.enable_model_cpu_offload()
pipe.vae.enable_tiling()
image = load_image(
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/penguin.png"
)
output = pipe(
image=image,
prompt="A penguin dancing in the snow",
height=832,
width=480,
num_frames=91,
num_inference_steps=30,
guidance_scale=9.0,
generator=torch.Generator().manual_seed(0),
sampling_type="vanilla",
).frames[0]
export_to_video(output, "output.mp4", fps=30)グループオフローディング
グループオフローディング(apply_group_offloading())は、モデルの内部要素をCPUへオフロードするための積極的なメモリ最適化を提供します。これにより、生成時間への追加オーバーヘッドが発生しない場合があります。利用可能なVRAMが非常に少ない場合、利用可能なCPU RAMの量によっては、このアプローチが適している可能性があります。
import torch
from diffusers import HunyuanVideoFramepackPipeline, HunyuanVideoFramepackTransformer3DModel
from diffusers.hooks import apply_group_offloading
from diffusers.utils import export_to_video, load_image
from transformers import SiglipImageProcessor, SiglipVisionModel
transformer = HunyuanVideoFramepackTransformer3DModel.from_pretrained(
"lllyasviel/FramePack_F1_I2V_HY_20250503", dtype=torch.bfloat16
)
feature_extractor = SiglipImageProcessor.from_pretrained(
"lllyasviel/flux_redux_bfl", subfolder="feature_extractor"
)
image_encoder = SiglipVisionModel.from_pretrained(
"lllyasviel/flux_redux_bfl", subfolder="image_encoder", dtype=torch.float16
)
pipe = HunyuanVideoFramepackPipeline.from_pretrained(
"hunyuanvideo-community/HunyuanVideo",
transformer=transformer,
feature_extractor=feature_extractor,
image_encoder=image_encoder,
dtype=torch.float16,
)
# Enable group offloading
onload_device = torch.device("cuda")
offload_device = torch.device("cpu")
list(map(
lambda x: apply_group_offloading(x, onload_device, offload_device, offload_type="leaf_level", use_stream=True, low_cpu_mem_usage=True),
[pipe.text_encoder, pipe.text_encoder_2, pipe.transformer]
))
pipe.image_encoder.to(onload_device)
pipe.vae.to(onload_device)
pipe.vae.enable_tiling()
image = load_image(
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/penguin.png"
)
output = pipe(
image=image,
prompt="A penguin dancing in the snow",
height=832,
width=480,
num_frames=91,
num_inference_steps=30,
guidance_scale=9.0,
generator=torch.Generator().manual_seed(0),
sampling_type="vanilla",
).frames[0]
print(f"Max memory: {torch.cuda.max_memory_allocated() / 1024**3:.3f} GB")
export_to_video(output, "output.mp4", fps=30)HunyuanVideoFramepackPipeline
class diffusers.HunyuanVideoFramepackPipeline
< source >( text_encoder: LlamaModeltokenizer: LlamaTokenizertransformer: HunyuanVideoFramepackTransformer3DModelvae: AutoencoderKLHunyuanVideoscheduler: FlowMatchEulerDiscreteSchedulertext_encoder_2: CLIPTextModeltokenizer_2: CLIPTokenizerimage_encoder: SiglipVisionModelfeature_extractor: SiglipImageProcessorPil )
パラメータ
- 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__
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]last_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneprompt: 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 = 129latent_window_size: int = 9num_inference_steps: int = 50sigmas: list[float] = Nonetrue_cfg_scale: float = 1.0guidance_scale: float = 6.0num_videos_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneimage_latents: typing.Optional[torch.Tensor] = Nonelast_image_latents: 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[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 = 256sampling_type: FramepackSamplingType = <FramepackSamplingType.INVERTED_ANTI_DRIFTING: 'inverted_anti_drifting'> ) → ~HunyuanVideoFramepackPipelineOutput or tuple
パラメータ
- image (
PIL.Image.Imageまたはnp.ndarrayまたはtorch.Tensor) — 動画生成の起点として使用される画像。 - last_image (
PIL.Image.Imageまたはnp.ndarrayまたはtorch.Tensor、省略可) — 動画生成の終了点として使用する任意の最後の画像です。これは、2つの画像間のトランジションを生成する際に役立ちます。 - 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) — 生成される動画のフレーム数です。 - latent_window_size (
int, デフォルトは9) — Framepack サンプリングウィンドウごとに生成される潜在フレームの数です。 - num_inference_steps (
int、デフォルトは50) — デノイジングのステップ数です。ステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。 - sigmas (
list[float]、任意) —set_timestepsメソッドでsigmas引数を受け付けるスケジューラーにおいて、デノイジングプロセスに使用するカスタムのシグマです。定義されていない場合、num_inference_stepsが渡された際のデフォルトの動作が使用されます。 - true_cfg_scale (
float、任意、デフォルト値は 1.0)— 1.0 より大きく、かつnegative_promptが指定されている場合、true classifier-free guidance を有効にします。 - guidance_scale (
float、デフォルト値は6.0) — Classifier-Free Diffusion Guidance で定義されているガイダンススケールです。guidance_scaleは、Imagen Paper の数式 2 のwとして定義されています。guidance_scale > 1を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、promptのテキストと密接に関連する画像の生成が促されますが、通常は画像の品質が低下する傾向があります。なお、利用可能な HunyuanVideo モデルはすべて CFG-distilled であり、無条件と条件付きの潜在変数の間の従来のガイダンスは適用されません。 - num_videos_per_prompt (
int、省略可能、デフォルト値は 1)— プロンプトごとに生成する画像の数。 - generator (
torch.Generatorまたはlist[torch.Generator]、省略可) — 生成を決定論的にするためのtorch.Generator。 - image_latents (
torch.Tensor, 任意) — 事前エンコードされた画像の潜在変数です。指定されない場合、VAE を使用して画像がエンコードされます。 - last_image_latents (
torch.Tensor, 任意) — 事前エンコード済みの最後の画像の潜在変数です。指定されない場合、最後の画像は VAE を使用してエンコードされます。 - 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) —HunyuanVideoFramepackPipelineOutputを返すか、プレーンなタプルを返すかを指定します。 - attention_kwargs (
dict, 省略可) — 指定された場合、diffusers.models.attention_processor で定義されているself.processor内のAttentionProcessorに渡される kwargs 辞書です。 - prompt_template (
dict, 任意) — エンコード前にプロンプトを整形するために使用されるテンプレート。デフォルトでは、モデルのデフォルトテンプレートが使用されます。 - max_sequence_length (
int、任意、デフォルトは 256) — プロンプトエンコーダーに使用する最大シーケンス長。 - sampling_type (
FramepackSamplingType、任意) — 潜在ウィンドウを反復処理する際に使用する Framepack サンプリング戦略です。 - 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属性にリストされている変数のみを、このリストに含めることができます。
戻り値
~HunyuanVideoFramepackPipelineOutput または tuple
return_dict が True の場合、HunyuanVideoFramepackPipelineOutput が返され、それ以外の場合は tuple が返されます。この tuple の最初の要素は生成された画像のリストであり、2番目の要素は、対応する生成画像に「not-safe-for-work」(nsfw)コンテンツが含まれているかどうかを示す bool のリストです。
生成用の pipeline への呼び出し関数。
例:
画像から動画へ
>>> import torch
>>> from diffusers import HunyuanVideoFramepackPipeline, HunyuanVideoFramepackTransformer3DModel
>>> from diffusers.utils import export_to_video, load_image
>>> from transformers import SiglipImageProcessor, SiglipVisionModel
>>> transformer = HunyuanVideoFramepackTransformer3DModel.from_pretrained(
... "lllyasviel/FramePackI2V_HY", torch_dtype=torch.bfloat16
... )
>>> feature_extractor = SiglipImageProcessor.from_pretrained(
... "lllyasviel/flux_redux_bfl", subfolder="feature_extractor"
... )
>>> image_encoder = SiglipVisionModel.from_pretrained(
... "lllyasviel/flux_redux_bfl", subfolder="image_encoder", torch_dtype=torch.float16
... )
>>> pipe = HunyuanVideoFramepackPipeline.from_pretrained(
... "hunyuanvideo-community/HunyuanVideo",
... transformer=transformer,
... feature_extractor=feature_extractor,
... image_encoder=image_encoder,
... torch_dtype=torch.float16,
... )
>>> pipe.vae.enable_tiling()
>>> pipe.to("cuda")
>>> image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/penguin.png"
... )
>>> output = pipe(
... image=image,
... prompt="A penguin dancing in the snow",
... height=832,
... width=480,
... num_frames=91,
... num_inference_steps=30,
... guidance_scale=9.0,
... generator=torch.Generator().manual_seed(0),
... sampling_type="inverted_anti_drifting",
... ).frames[0]
>>> export_to_video(output, "output.mp4", fps=30)最初の画像と最後の画像から動画へ
>>> import torch
>>> from diffusers import HunyuanVideoFramepackPipeline, HunyuanVideoFramepackTransformer3DModel
>>> from diffusers.utils import export_to_video, load_image
>>> from transformers import SiglipImageProcessor, SiglipVisionModel
>>> transformer = HunyuanVideoFramepackTransformer3DModel.from_pretrained(
... "lllyasviel/FramePackI2V_HY", torch_dtype=torch.bfloat16
... )
>>> feature_extractor = SiglipImageProcessor.from_pretrained(
... "lllyasviel/flux_redux_bfl", subfolder="feature_extractor"
... )
>>> image_encoder = SiglipVisionModel.from_pretrained(
... "lllyasviel/flux_redux_bfl", subfolder="image_encoder", torch_dtype=torch.float16
... )
>>> pipe = HunyuanVideoFramepackPipeline.from_pretrained(
... "hunyuanvideo-community/HunyuanVideo",
... transformer=transformer,
... feature_extractor=feature_extractor,
... image_encoder=image_encoder,
... torch_dtype=torch.float16,
... )
>>> pipe.to("cuda")
>>> prompt = "CG animation style, a small blue bird takes off from the ground, flapping its wings. The bird's feathers are delicate, with a unique pattern on its chest. The background shows a blue sky with white clouds under bright sunshine. The camera follows the bird upward, capturing its flight and the vastness of the sky from a close-up, low-angle perspective."
>>> first_image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_first_frame.png"
... )
>>> last_image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_last_frame.png"
... )
>>> output = pipe(
... image=first_image,
... last_image=last_image,
... prompt=prompt,
... height=512,
... width=512,
... num_frames=91,
... num_inference_steps=30,
... guidance_scale=9.0,
... generator=torch.Generator().manual_seed(0),
... sampling_type="inverted_anti_drifting",
... ).frames[0]
>>> export_to_video(output, "output.mp4", fps=30)HunyuanVideoPipelineOutput
クラス diffusers.pipelines.hunyuan_video.pipeline_output.HunyuanVideoPipelineOutput
< source >( frames: Tensor )
HunyuanVideo パイプライン用の出力クラスです。