Diffusers documentation
Framepack
Framepack
Lvmin Zhang 和 Maneesh Agrawala 的《Packing Input Frame Context in Next-Frame Prediction Models for Video Generation》
我们提出了一种名为 FramePack 的神经网络结构,用于训练视频生成的下一帧(或下一帧片段)预测模型。FramePack 对输入帧进行压缩,使得无论视频长度如何,Transformer 的上下文长度都保持为一个固定值。因此,我们能够使用视频扩散模型处理大量帧,其计算瓶颈与图像扩散模型相当。这也使得训练时的视频批次大小显著提高(批次大小可与图像扩散训练相媲美)。我们还提出了一种抗漂移采样方法,该方法以倒序时间顺序生成帧,并预先建立端点,以避免暴露偏差(即迭代过程中的误差累积)。最后,我们展示了现有的视频扩散模型可以通过 FramePack 进行微调,并且由于下一帧预测支持更均衡的扩散调度器以及更极端的流形时间步,其视觉质量可能会得到提升。
请务必参阅 调度器指南,了解如何探索调度器速度与质量之间的权衡,并查看 跨流水线复用组件 部分,了解如何高效地将相同组件加载到多个流水线中。
可用模型
| 模型名称 | 描述 |
|---|---|
- lllyasviel/FramePackI2V_HY | 采用论文中描述的“反转抗漂移”策略进行训练。在运行流水线时,推理需要设置 sampling_type="inverted_anti_drifting"。 |
- lllyasviel/FramePack_F1_I2V_HY_20250503 | 该模型采用一种新颖的抗漂移策略进行训练,但推理过程则按照论文中所述采用“vanilla”策略执行。在运行 pipeline 时,需要将 sampling_type="vanilla" 设置为该值以进行推理。 |
用法
请参阅 pipeline 文档以了解基本用法示例。以下部分包含有关 offloading、不同采样方法、量化等的示例。
首帧和尾帧转视频
以下示例展示了如何使用 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
类 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 的分词器。 - 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。有关为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等),请参阅父类文档。
__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 = 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 = ['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 = 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,可选) — 用于视频生成的可选最后一帧图像,作为视频的结束点。这在生成两张图像之间的过渡效果时非常有用。 - 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],可选) — 用于在支持sigmas参数的调度器的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 蒸馏的,这意味着不会应用无条件和条件潜在变量之间的传统引导。 - 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_embeds 将根据negative_prompt输入参数生成。 - 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, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中定义的AttentionProcessor,该处理器在self.processor下定义。 - 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,其中第一个元素是包含生成图像的列表,第二个元素是 bool 列表,用于指示对应的生成图像是否包含“不适合工作场所”(nsfw)内容。
用于生成的 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
class diffusers.pipelines.hunyuan_video.pipeline_output.HunyuanVideoPipelineOutput
< source >( frames: Tensor )
HunyuanVideo 管道的输出类。