Diffusers documentation

缓存

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

and get access to the augmented documentation experience

to get started

缓存

缓存通过在不同去噪步骤之间复用中间层输出来加速推理。它会占用更多内存,且无需训练。在支持缓存的 transformer 上,通过配置启用某种方法。

选择缓存方法

请根据您需要设置的配置量以及所需的适配程度来选择方法。每种方法在速度、内存以及输出与未缓存运行结果的匹配度之间都有不同的权衡。在依赖某种方法之前,请在您自己的提示词上比较使用缓存和未使用缓存时的输出结果。

方法使用时备注
文本 KV 缓存NucleusMoE 图像,跨步骤复用文本 K/V 投影目前挂钩了 NucleusMoE 图像块
SeaCacheCosmos 3 视频生成设置通常无法在不同模型之间迁移
FirstBlockCache想要为已注册的 transformer 设置一个主要的速度/质量调节旋钮一个threshold控制跳过步骤的频率
MagCache您的检查点和调度器是否有幅度比率,还是先进行校准比例因检查点和调度器而异
TaylorSeer想要从较早的步骤预测后续的激活值更高的 max_order 会使用更多内存
PAB视频,愿意调整注意力复用(按注意力类型设置块和时间步跳过范围)跳过范围需要针对每个模型进行调优
FasterCache与 PAB 类似,外加可选的 CFG 分支跳过实验性

Pyramid Attention Broadcast 和 FasterCache 会从去噪器的 cache_context 中读取当前时间步。 在编写自定义去噪循环时,请使用 model.cache_context("cond", timestep=t) 包裹每次去噪器调用。 为每个引导分支使用独立的上下文名称,或者对于合并的批次使用 "cond_uncond",并在开始新的生成之前调用 model._reset_stateful_cache()。下面的流水线示例已为您处理了这些操作。

金字塔注意力广播

Pyramid Attention Broadcast (PAB) 通过在部分块和时间步上复用注意力输出,而非在每个步骤都重新计算,来近似去噪步骤间的注意力。当模型包含多种注意力类型时,Config 会将它们分开(空间、时间、交叉)。并非所有视频模型都暴露这三种类型,请仅设置与您拥有的块相匹配的范围。

每种类型都使用 *_attention_block_skip_range(窗口内重新计算与复用的频率)和 *_attention_timestep_skip_range(哪些去噪时间步可以跳过)。更宽或更激进的跳过通常意味着更高的速度和更大的质量风险。

传入 PyramidAttentionBroadcastConfig 以启用它。

import torch
from diffusers import CogVideoXPipeline, PyramidAttentionBroadcastConfig

pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", dtype=torch.bfloat16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

config = PyramidAttentionBroadcastConfig(
    spatial_attention_block_skip_range=2,
    spatial_attention_timestep_skip_range=(100, 800),
)
pipe.transformer.enable_cache(config)

FasterCache

FasterCache 会缓存并复用注意力特征,其方式与 PAB 类似。此外,在分类器自由引导(classifier-free guidance)下,它还可以跳过无条件分支,并在连续潜变量冗余度足够时,从条件分支对其进行估计。

传入 FasterCacheConfig 以启用该功能。与 PAB 类似,请针对您所使用的注意力类型设置 *_attention_block_skip_range 和 *_attention_timestep_skip_range,并在需要时配置 CFG 分支的跳过选项。

import torch
from diffusers import CogVideoXPipeline, FasterCacheConfig

pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", dtype=torch.bfloat16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

config = FasterCacheConfig(
    spatial_attention_block_skip_range=2,
    spatial_attention_timestep_skip_range=(-1, 681),
    attention_weight_callback=lambda _: 0.3,
    unconditional_batch_skip_range=5,
    unconditional_batch_timestep_skip_range=(-1, 781),
    tensor_format="BFCHW",
)
pipe.transformer.enable_cache(config)

SeaCache

SeaCache 比较连续去噪步骤之间的 Spectral Evolution Aware (SEA) 指标。当累积变化低于阈值时,它会跳过 transformer 块堆栈,并从缓存的残差中预测输出。该方法是一种近似方法,专为视频生成而设计。

SeaCache 的内置适配器包括:

  • Cosmos 3 是主要经过优化和基准测试的集成方案。
  • Wan T2V 使用通用的重复块路径作为演示,展示如何将原始视觉潜在变量提供给 SeaCache。相同的缓存参数可能无法迁移到 Wan 或其他 Wan 变体。

在 transformer 上启用 SeaCache。Cosmos 3 的去噪循环会将调度器步长、sigma 和步数附加到每个 cache_context 中,因此无需额外参数。

from diffusers import Cosmos3OmniPipeline, SeaCacheConfig

pipe = Cosmos3OmniPipeline.from_pretrained("nvidia/Cosmos3-Nano")
pipe.transformer.enable_cache(SeaCacheConfig(threshold=0.2, max_consecutive_cached=2))

SeaCache 可能会改变输出。当您需要每一步都运行完整的 transformer 时,请调用 pipe.transformer.disable_cache()。相同的启用调用也适用于 Cosmos3OmniPipeline、Cosmos3OmniModularPipeline 和 Cosmos3DistilledModularPipeline。

要将 SeaCache 与其他视频 Transformer 配合使用,请遵循 为新模型添加缓存。SeaCache 还需要在每个 cache_context 中提供 step_index、sigma 和 num_inference_steps,并且在没有内置适配器时需要 raw_vision_callback。请根据具体的模型和调度器调整参数。

FirstBlockCache

FirstBlockCacheConfig 会检查去噪器(denoiser)的早期层在相邻时间步之间的变化程度。如果变化较小,模型将跳过代价高昂的后续层,并复用之前的输出。

通过 enable_cache 启用它,以便 disable_cache 和 is_cache_enabled 保持同步。默认的 threshold 为 0.05。更高的值(例如 0.2)会更频繁地跳过,从而获得额外的速度提升,但生成质量可能会下降。

import torch
from diffusers import DiffusionPipeline, FirstBlockCacheConfig

pipe = DiffusionPipeline.from_pretrained(
    "Qwen/Qwen-Image", dtype=torch.bfloat16
)
pipe.transformer.enable_cache(FirstBlockCacheConfig(threshold=0.2))

TaylorSeer 缓存

TaylorSeer Cache 通过跨去噪步骤的泰勒级数展开来加速扩散推理。它利用早期步骤的激活值预测后续步骤的激活值,并在多个步骤中复用这些预测值,从而减少 Transformer 的完整计算量。

  • cache_interval:在执行完整前向传播之前,复用缓存输出的步数
  • disable_cache_before_step:初始步骤,使用完整计算来收集用于近似的数据
  • max_order:更高的泰勒阶数可能更精确,但会占用更多内存。除非有特定原因需要更改,否则请保持为 1。
import torch
from diffusers import FluxPipeline, TaylorSeerCacheConfig

pipe = FluxPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-dev",
    dtype=torch.bfloat16,
).to("cuda")  # or "mps", "xpu", "cpu"

config = TaylorSeerCacheConfig(
    cache_interval=5,
    max_order=1,
    disable_cache_before_step=10,
    taylor_factors_dtype=torch.bfloat16,
)
pipe.transformer.enable_cache(config)

MagCache

MagCache 根据残差更新的幅度来跳过 Transformer 块。更新幅度在去噪过程中会按可预测的方式衰减,MagCache 通过跟踪基于预计算幅度比(mag_ratios)得出的误差预算,来决定何时可以安全地复用。这些比率与特定的检查点和调度器相关。可以从高步数下的比率插值出较少步数下的比率。

捆绑的 FLUX_MAG_RATIOS 是在 FLUX.1 上测量的。其他模型,包括 Flux2 和 Flux2 Klein,需要各自进行校准运行。

MagCache 遵循两个步骤:

  1. 校准:使用 calibrate=True 运行一次推理。该钩子会测量残差幅度并打印计算出的比率。
  2. 推理:禁用校准缓存,然后将这些比率传递给 MagCacheConfig 以实现加速。

Classifier-free guidance 可能会影响校准。使用真实 CFG 且采用顺序上下文的流水线(例如当 true_cfg_scale > 1 时的 Flux)会分别进入 cache_context("cond") 和 cache_context("uncond")。校准可能会为每个上下文打印一个数组,但在大多数情况下,您应使用条件数组。通过将条件输入和非条件输入拼接来批量处理 CFG 的流水线(例如 CogVideoX)会生成一个可直接使用的联合数组。

import torch
from diffusers import FluxPipeline, MagCacheConfig
from diffusers.hooks.mag_cache import FLUX_MAG_RATIOS

pipe = FluxPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-schnell",
    dtype=torch.bfloat16
).to("cuda")  # or "mps", "xpu", "cpu"

# 1. Calibration Step
# Run full inference to measure model behavior.
calib_config = MagCacheConfig(calibrate=True, num_inference_steps=4)
pipe.transformer.enable_cache(calib_config)

# Run a prompt to trigger calibration
pipe("A cat playing chess", num_inference_steps=4)
# Prints: [MagCache] Calibration Complete. Copy these values to MagCacheConfig(mag_ratios=...):

# 2. Inference Step
# Disable calibration hooks before enabling MagCache for inference.
pipe.transformer.disable_cache()

# Apply ratios from calibration, or use the Flux defaults:
# mag_ratios=FLUX_MAG_RATIOS
mag_config = MagCacheConfig(
    mag_ratios=[1.0, 1.37, 0.97, 0.87],
    num_inference_steps=4
)

pipe.transformer.enable_cache(mag_config)

image = pipe("A cat playing chess", num_inference_steps=4).images[0]

文本 KV 缓存

TextKVCacheConfig 会计算一次文本的 key 和 value 投影,并在每个去噪步骤中复用它们,而不是重新计算。apply_text_kv_cache() 目前仅支持 NucleusMoEImageTransformerBlock。通过 enable_cache 启用该功能。

import torch
from diffusers import NucleusMoEImagePipeline, TextKVCacheConfig

pipe = NucleusMoEImagePipeline.from_pretrained(
    "NucleusAI/NucleusMoE-Image", dtype=torch.bfloat16
)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

pipe.transformer.enable_cache(TextKVCacheConfig())

image = pipe("A cat holding a sign that says hello world", num_inference_steps=50).images[0]

为新模型添加缓存

缓存方法通过钩子(hooks)附加到模型上,而这些钩子依赖于模型类、其 Transformer 块以及流水线的去噪循环。在对新模型调用 enable_cache 之前,请先配置好这三者。

  1. 在 transformer 类中继承 CacheMixin。它会添加 enable_cache、disable_cache 和 cache_context。

  2. 在 hooks/_helpers.py 中的 _register_transformer_blocks_metadata 里注册 transformer 块的输出布局。跳过或复用整个块的方法(例如 FirstBlockCache、MagCache 和 SeaCache)会利用它来在块的输出中查找隐藏状态。

    TransformerBlockRegistry.register(
        model_class=MyTransformerBlock,
        metadata=TransformerBlockMetadata(
            return_hidden_states_index=0,
            return_encoder_hidden_states_index=None,
        ),
    )
  3. 在流水线的去噪循环中,使用 cache_context 包裹每次 transformer 调用。当分类器自由引导将条件分支和非条件分支作为独立调用运行时,请使用不同的名称,例如 "cond" 和 "uncond",以便每个分支保留其自身的缓存状态。

    with self.transformer.cache_context("cond", timestep=t):
        noise_pred = self.transformer(hidden_states=latents, timestep=timestep, ...)[0]

PAB 和 FasterCache 会从 cache_context 中读取当前时间步,因此请传入 timestep=t。请在新模型上检查输出质量,因为针对某个模型调优的缓存设置通常无法直接迁移到另一个模型。

Update on GitHub