Diffusers documentation

ParaAttention

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

ParaAttention

大型图像和视频生成模型(例如 FLUX.1-dev 和 HunyuanVideo)由于体积庞大,在实时应用和部署中可能带来推理方面的挑战。

ParaAttention 是一个实现了 context parallelism 和 first block cache 的库,并且可以与其他技术(torch.compile、fp8 动态量化)结合使用,以加速推理。

本指南将展示如何在 NVIDIA L20 GPU 上对 FLUX.1-dev 和 HunyuanVideo 应用 ParaAttention。 我们的基线基准测试未应用任何优化,但 HunyuanVideo 除外,以避免内存溢出错误。

我们的基线基准测试表明,FLUX.1-dev 能够在 28 步内以 26.36 秒生成 1024x1024 分辨率的图像,而 HunyuanVideo 能够在 30 步内以 3675.71 秒生成 720p 分辨率的 129 帧视频。

若需借助上下文并行实现更快的推理速度,建议(在可用的情况下)使用支持 NVLink 的 NVIDIA A100 或 H100 GPU,尤其是在 GPU 数量较多的场景下。

第一块缓存

缓存模型中 transformers 块的输出并在后续推理步骤中复用它们,可以降低计算成本并加快推理速度。

然而,很难确定何时复用缓存,以确保生成的图像或视频的质量。ParaAttention 直接使用 第一个 Transformer 块输出的残差差异 来近似模型输出之间的差异。当差异足够小时,就会复用之前推理步骤的残差差异。换句话说,即跳过去噪步骤。

这使 FLUX.1-dev 和 HunyuanVideo 的推理速度提升了 2 倍,且质量非常好。

Cache in Diffusion Transformer
AdaCache 的工作原理,First Block Cache 是它的一个变体
FLUX-1.dev
HunyuanVideo

要在 FLUX.1-dev 上应用第一块缓存,请按照下方所示调用 apply_cache_on_pipe。0.08 是 FLUX 模型的默认残差差异值。

import time
import torch
from diffusers import FluxPipeline

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

from para_attn.first_block_cache.diffusers_adapters import apply_cache_on_pipe

apply_cache_on_pipe(pipe, residual_diff_threshold=0.08)

# Enable memory savings
# pipe.enable_model_cpu_offload()
# pipe.enable_sequential_cpu_offload()

begin = time.time()
image = pipe(
    "A cat holding a sign that says hello world",
    num_inference_steps=28,
).images[0]
end = time.time()
print(f"Time: {end - begin:.2f}s")

print("Saving image to flux.png")
image.save("flux.png")
优化原始FBCache rdt=0.06FBCache rdt=0.08FBCache rdt=0.10FBCache rdt=0.12
预览OriginalFBCache rdt=0.06FBCache rdt=0.08FBCache rdt=0.10FBCache rdt=0.12
实际耗时(秒)26.3621.8317.0116.0013.78

First Block Cache 将推理速度从基线降低至 17.01 秒,即速度提升了 1.55 倍,同时几乎未造成质量损失。

fp8 量化

使用动态量化的 fp8 可进一步加速推理并降低内存占用。若要使用 8 位 NVIDIA Tensor Cores,激活值和权重都必须进行量化。

使用 float8_weight_only 和 float8_dynamic_activation_float8_weight 对文本编码器和 transformer 模型进行量化。

默认的量化方法是按张量量化,但如果您的 GPU 支持按行量化,您也可以尝试使用它以获得更高的精度。

使用以下命令安装 torchao。

pip3 install -U torch torchao

使用 torch.compile 并设置 mode="max-autotune-no-cudagraphs" 或 mode="max-autotune" 可以选择性能最佳的 kernel。如果模型是首次被调用,编译过程可能会耗时较长,但一旦模型完成编译,其收益是值得的。

此示例仅对 transformer 模型进行量化,但您也可以对文本编码器进行量化,以进一步降低内存占用。

动态量化可能会显著改变模型输出的分布,因此你需要将 residual_diff_threshold 更改为更大的值,使其生效。

FLUX-1.dev
HunyuanVideo
import time
import torch
from diffusers import FluxPipeline

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

from para_attn.first_block_cache.diffusers_adapters import apply_cache_on_pipe

apply_cache_on_pipe(
    pipe,
    residual_diff_threshold=0.12,  # Use a larger value to make the cache take effect
)

from torchao.quantization import quantize_, float8_dynamic_activation_float8_weight, float8_weight_only

quantize_(pipe.text_encoder, float8_weight_only())
quantize_(pipe.transformer, float8_dynamic_activation_float8_weight())
pipe.transformer = torch.compile(
   pipe.transformer, mode="max-autotune-no-cudagraphs",
)

# Enable memory savings
# pipe.enable_model_cpu_offload()
# pipe.enable_sequential_cpu_offload()

for i in range(2):
    begin = time.time()
    image = pipe(
        "A cat holding a sign that says hello world",
        num_inference_steps=28,
    ).images[0]
    end = time.time()
    if i == 0:
        print(f"Warm up time: {end - begin:.2f}s")
    else:
        print(f"Time: {end - begin:.2f}s")

print("Saving image to flux.png")
image.save("flux.png")

fp8 动态量化和 torch.compile 将推理速度降低至 7.56 秒,相较于基线快 3.48 倍。

上下文并行

Context Parallelism 对推理进行并行化,并可通过多块 GPU 进行扩展。ParaAttention 的组合式设计允许您将 Context Parallelism 与 First Block Cache 以及动态量化相结合。

有关如何使用多 GPU 扩展推理的详细说明和示例,请参阅 ParaAttention 仓库。

如果推理过程需要持久化并可对外提供服务,建议使用 torch.multiprocessing 编写自定义的推理处理器。这样可以消除启动进程以及加载和重新编译模型所带来的开销。

FLUX-1.dev
HunyuanVideo

下面的代码示例结合了 First Block Cache、fp8 动态量化、torch.compile 和 Context Parallelism,以实现最快的推理速度。

import time
import torch
import torch.distributed as dist
from diffusers import FluxPipeline

dist.init_process_group()

torch.cuda.set_device(dist.get_rank())

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

from para_attn.context_parallel import init_context_parallel_mesh
from para_attn.context_parallel.diffusers_adapters import parallelize_pipe
from para_attn.parallel_vae.diffusers_adapters import parallelize_vae

mesh = init_context_parallel_mesh(
    pipe.device.type,
    max_ring_dim_size=2,
)
parallelize_pipe(
    pipe,
    mesh=mesh,
)
parallelize_vae(pipe.vae, mesh=mesh._flatten())

from para_attn.first_block_cache.diffusers_adapters import apply_cache_on_pipe

apply_cache_on_pipe(
    pipe,
    residual_diff_threshold=0.12,  # Use a larger value to make the cache take effect
)

from torchao.quantization import quantize_, float8_dynamic_activation_float8_weight, float8_weight_only

quantize_(pipe.text_encoder, float8_weight_only())
quantize_(pipe.transformer, float8_dynamic_activation_float8_weight())
torch._inductor.config.reorder_for_compute_comm_overlap = True
pipe.transformer = torch.compile(
   pipe.transformer, mode="max-autotune-no-cudagraphs",
)

# Enable memory savings
# pipe.enable_model_cpu_offload(gpu_id=dist.get_rank())
# pipe.enable_sequential_cpu_offload(gpu_id=dist.get_rank())

for i in range(2):
    begin = time.time()
    image = pipe(
        "A cat holding a sign that says hello world",
        num_inference_steps=28,
        output_type="pil" if dist.get_rank() == 0 else "pt",
    ).images[0]
    end = time.time()
    if dist.get_rank() == 0:
        if i == 0:
            print(f"Warm up time: {end - begin:.2f}s")
        else:
            print(f"Time: {end - begin:.2f}s")

if dist.get_rank() == 0:
    print("Saving image to flux.png")
    image.save("flux.png")

dist.destroy_process_group()

将其保存为 run_flux.py,并使用 torchrun 启动。

# Use --nproc_per_node to specify the number of GPUs
torchrun --nproc_per_node=2 run_flux.py

与基线相比,使用 2 块 NVIDIA L20 GPU 时,推理速度降至 8.20 秒,即快 3.21 倍。使用 4 块 L20 时,推理速度为 3.90 秒,即快 6.75 倍。

基准测试

FLUX-1.dev
HunyuanVideo
GPU 类型GPU 数量优化实际耗时(秒)加速
NVIDIA L201基线26.361.00x
NVIDIA L201FBCache (rdt=0.08)17.011.55x
NVIDIA L201FP8 DQ13.401.96x
NVIDIA L201FBCache (rdt=0.12) + FP8 DQ7.563.48x
NVIDIA L202FBCache (rdt=0.12) + FP8 DQ + CP4.925.35x
NVIDIA L204FBCache (rdt=0.12) + FP8 DQ + CP3.906.75x
Update on GitHub