Diffusers 文件
Framepack
並獲得增強的文件體驗
開始使用
Framepack
Lvmin Zhang 和 Maneesh Agrawala 的論文《在影片生成模型中打包輸入幀上下文以進行下一幀預測》。
我們提出了一種名為 FramePack 的神經網路結構,用於訓練影片生成的下一幀(或下一幀部分)預測模型。FramePack 壓縮輸入幀,使 Transformer 上下文長度固定,無論影片長度如何。因此,我們能夠使用影片擴散處理大量幀,其計算瓶頸類似於影像擴散。這也使得訓練影片批次大小顯著提高(批次大小變得與影像擴散訓練相當)。我們還提出了一種反漂移取樣方法,以反向時間順序生成幀,並設定早期建立的端點,以避免曝光偏差(迭代中誤差累積)。最後,我們展示了現有影片擴散模型可以透過 FramePack 進行微調,並且它們的視覺質量可能會得到改善,因為下一幀預測支援更平衡的擴散排程器,具有更小的極端流偏移時間步。
可用模型
模型名稱 | 描述 |
---|---|
- lllyasviel/FramePackI2V_HY | 使用論文中描述的“反向反漂移”策略進行訓練。推理時需要將 sampling_type 設定為 "inverted_anti_drifting" 。 |
- lllyasviel/FramePack_F1_I2V_HY_20250503 | 使用新型反漂移策略進行訓練,但推理採用論文中描述的“香草”策略。推理時需要將 sampling_type 設定為 "vanilla" 。 |
用法
請參閱管道文件以獲取基本使用示例。以下部分包含解除安裝、不同取樣方法、量化等示例。
首尾幀到影片
以下示例演示瞭如何使用 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", 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,
)
# 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", 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,
)
# 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,可能不會對生成時間造成額外開銷。如果您的視訊記憶體非常低,此方法可能適合您,具體取決於可用的 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", 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,
)
# 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)
< 源 >
類 diffusers.HunyuanVideoFramepackPipeline
< 原始碼 >( text_encoder: LlamaModel tokenizer: LlamaTokenizerFast transformer: HunyuanVideoFramepackTransformer3DModel vae: AutoencoderKLHunyuanVideo scheduler: FlowMatchEulerDiscreteScheduler text_encoder_2: CLIPTextModel tokenizer_2: CLIPTokenizer image_encoder: SiglipVisionModel feature_extractor: SiglipImageProcessor )
引數
- 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 進行文字到影片生成的管道。
此模型繼承自 DiffusionPipeline。請檢視超類文件,瞭解所有管道實現的通用方法(下載、儲存、在特定裝置上執行等)。
__call__
< 原始碼 >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] last_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str]] = None negative_prompt: typing.Union[str, typing.List[str]] = None negative_prompt_2: typing.Union[str, typing.List[str]] = None height: int = 720 width: int = 1280 num_frames: int = 129 latent_window_size: int = 9 num_inference_steps: int = 50 sigmas: typing.List[float] = None true_cfg_scale: float = 1.0 guidance_scale: float = 6.0 num_videos_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None image_latents: typing.Optional[torch.Tensor] = None last_image_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: typing.Optional[str] = 'pil' return_dict: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] prompt_template: typing.Dict[str, typing.Any] = {'template': '<|start_header_id|>system<|end_header_id|>\n\n描述影片時請詳細說明以下幾個方面:1. 影片的主要內容和主題。2. 影片中物體的顏色、形狀、大小、紋理、數量、文字和空間關係。3. 物體的動作、事件、行為、時間關係、物理運動變化。4. 背景環境、光線、風格和氛圍。5. 影片中使用的攝像機角度、運動和過渡:<|eot_id|><|start_header_id|>使用者<|end_header_id|>\n\n{}<|eot_id|>', 'crop_start': 95} max_sequence_length: int = 256 sampling_type: FramepackSamplingType = <FramepackSamplingType.INVERTED_ANTI_DRIFTING: 'inverted_anti_drifting'> ) → ~HunyuanVideoFramepackPipelineOutput
或 元組
引數
- 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
) — 生成影片中的幀數。 - 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
時,啟用真實的無分類器指導。 - 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) — 每個 prompt 生成的影像數量。 - generator (
torch.Generator
或List[torch.Generator]
, 可選) — 用於使生成具有確定性的torch.Generator
。 - image_latents (
torch.Tensor
, 可選) — 預編碼的影像潛在。如果未提供,影像將使用 VAE 進行編碼。 - last_image_latents (
torch.Tensor
, 可選) — 預編碼的最後一個影像潛在。如果未提供,最後一個影像將使用 VAE 進行編碼。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入(prompt 權重)。如果未提供,文字嵌入將從prompt
輸入引數生成。 - pooled_prompt_embeds (
torch.FloatTensor
, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如 prompt 權重。如果未提供,池化文字嵌入將從prompt
輸入引數生成。 - negative_prompt_embeds (
torch.FloatTensor
, 可選) — 預生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如 prompt 權重。如果未提供,負面 prompt 嵌入將從negative_prompt
輸入引數生成。 - negative_pooled_prompt_embeds (
torch.FloatTensor
, 可選) — 預生成的負面池化文字嵌入。可用於輕鬆調整文字輸入,例如 prompt 權重。如果未提供,池化負面 prompt 嵌入將從negative_prompt
輸入引數生成。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。在PIL.Image
或np.array
之間選擇。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回HunyuanVideoFramepackPipelineOutput
而不是普通元組。 - attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,則作為引數傳遞給 diffusers.models.attention_processor 中self.processor
下定義的AttentionProcessor
。 - clip_skip (
int
, 可選) — 在計算 prompt 嵌入時,從 CLIP 中跳過的層數。值為 1 表示將使用倒數第二層的輸出計算 prompt 嵌入。 - 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
引數傳遞。您只能包含 pipeline 類._callback_tensor_inputs
屬性中列出的變數。
返回
~HunyuanVideoFramepackPipelineOutput
或 tuple
如果 return_dict
為 True
,則返回 HunyuanVideoFramepackPipelineOutput
,否則返回一個 tuple
,其中第一個元素是生成的影像列表,第二個元素是一個 bool
列表,指示相應的生成影像是否包含“不適合工作”(nsfw)內容。
用於生成的管道的呼叫函式。
示例
影像到影片
>>> 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)
停用切片 VAE 解碼。如果之前啟用了 enable_vae_slicing
,此方法將返回一步計算解碼。
停用平鋪 VAE 解碼。如果之前啟用了 enable_vae_tiling
,此方法將恢復一步計算解碼。
啟用切片 VAE 解碼。啟用此選項後,VAE 會將輸入張量分片,分步計算解碼。這有助於節省一些記憶體並允許更大的批次大小。
啟用平鋪 VAE 解碼。啟用此選項後,VAE 將把輸入張量分割成瓦片,分多步計算編碼和解碼。這對於節省大量記憶體和處理更大的影像非常有用。
HunyuanVideoPipelineOutput
class diffusers.pipelines.hunyuan_video.pipeline_output.HunyuanVideoPipelineOutput
< 來源 >( frames: Tensor )
HunyuanVideo pipelines 的輸出類。