SageAttention Documentation

repository·main·Indexed 25 days ago

https://github.com/thu-ml/sageattention

A high-performance attention library providing accurate 8-bit and quantized attention kernels for Ampere, Ada, and Hopper GPUs. It supports plug-and-play replacement of PyTorch's scaled_dot_product_attention (SDPA) and offers specialized APIs like sageattn and sageattn3_blackwell for microscaling FP4 attention. Compatible with models such as CogVideoX, WAN, HunyuanVideo, Mochi, LTX-Video, Flux, and Stable-Diffusion3.5.

Tokens
2K
Snippets
8
Records
11
Agent score
87%

What's inside SageAttention

  1. Modify Attention implementation for finer control

    main

    For more granular control, you can replace specific attention processors in your model source code. For example, in Mochi models, you can replace the MochiAttnProcessor2_0 from diffusers with a custom attention class.

    HunyuanVideo Workaround: Because HunyuanVideo uses attention_mask (which sageattn does not support), you must modify the official attention implementation to split text tokens from image tokens. Apply SageAttention only to the large, mask-free image-token self-attention, while keeping the masked text part on SDPA or FlashAttention.

  2. Install SageAttention

    main

    Base Environment Requirements

    • python>=3.9
    • torch>=2.3.0
    • triton>=3.0.0
    • flash-attn (for benchmarking)

    CUDA Version Requirements

    • >=12.8 for Blackwell or SageAttention2++
    • >=12.4 for fp8 support on Ada
    • >=12.3 for fp8 support on Hopper
    • >=12.0 for Ampere

    Installation Methods

    To use SageAttention 2.2.0 (which includes SageAttention2++):

    pip install sageattention==2.2.0 --no-build-isolation

    To use SageAttention V1 (Triton-based, slower):

    pip install sageattention==1.0.6

    From Source

    git clone https://github.com/thu-ml/SageAttention.git
    cd SageAttention 
    # Optional: set build flags for faster compilation
    export EXT_PARALLEL=4 NVCC_APPEND_FLAGS="--threads 8" MAX_JOBS=32 
    python setup.py install
    pip install sageattention==2.2.0 --no-build-isolation
  3. Setup Parallel SageAttention Inference

    main

    To run parallel SageAttention inference, you must install the latest xfuser (xDiT) and a specific development version of diffusers from source.

    Follow these steps:

    1. Install xfuser with flash_attn support.
    2. Clone and install the latest diffusers from GitHub.
    3. Run the parallel inference script.

    Note: diffusers must be version >=0.32.0.dev0 to be compatible with the latest xDiT.

    # install latest xDiT(xfuser).
    pip install "xfuser[flash_attn]"
    
    # install latest diffusers (>=0.32.0.dev0), need by latest xDiT.
    git clone https://github.com/huggingface/diffusers.git
    cd diffusers && python3 setup.py bdist_wheel && cd dist && python3 -m pip install *.whl
    
    # then run parallel sage attention inference.
    ./run_parallel.sh
  4. Model compatibility and hybrid usage for SageAttention3

    main

    SageAttention3 is optimized for specific model types.

    Supported Models:

    • Video generation: CogVideoX-2B, HunyuanVideo, Mochi.
    • Image generation: Flux, Stable-Diffusion3.5, and almost all other image generation models.

    Hybrid Approach for Lossless Acceleration: SageAttention3 does not guarantee lossless acceleration for all models. For other video generation models, you can achieve lossless acceleration by using a hybrid approach:

    1. Apply SageAttention2++ only at the first and last timesteps.
    2. Use SageAttention3 for all other timesteps.
  5. Install SageAttention3 from source

    main

    SageAttention3 requires a specific base environment and must be compiled from source.

    Base Environment Requirements:

    • python >= 3.13
    • torch >= 2.8.0
    • CUDA >= 12.8

    Installation Steps: Clone the repository, navigate to the sageattention3_blackwell directory, and run the setup script.

    git clone https://github.com/thu-ml/SageAttention
    cd SageAttention/sageattention3_blackwell 
    python setup.py install
  6. Use SageAttention as a plug-and-play replacement for SDPA

    main

    You can replace PyTorch's scaled_dot_product_attention (SDPA) with sageattn by monkey-patching torch.nn.functional.F. This allows you to use SageAttention in existing models like CogVideoX without significant code changes.

    Supported Models:

    Important Notes:

    • If using --compile, the first run will be slower. Run twice for accurate speed measurements.
    • torch.compile is generally incompatible with enable_sequential_cpu_offload(). Do not use them together.
    from sageattention import sageattn
    import torch.nn.functional as F
    
    F.scaled_dot_product_attention = sageattn
  7. Run CogVideoX inference with SageAttention

    main

    To run inference for CogVideoX using SageAttention, navigate to the example directory and use the cogvideox_infer.py script with the --attention_type sage flag.

    Example command:

    cd example
    python cogvideox_infer.py --model cogvideox-2b --compile --attention_type sage

    Output videos will be saved to ./example/videos/<model>/<attention_type>/.

  8. Replace scaled_dot_product_attention for plug-and-play acceleration

    main

    You can achieve plug-and-play acceleration by monkey-patching torch.nn.functional.scaled_dot_product_attention with sageattn.

    Note: Not all models support this direct replacement. For complex models (like image/video DiT models), you may need to modify the specific Attention Class of the target model instead.

    import torch.nn.functional as F
    from sageattention import sageattn
    
    F.scaled_dot_product_attention = sageattn
  9. Use the sageattn API

    main

    The sageattn function automatically selects the optimal kernel based on your GPU to balance performance and accuracy.

    Input Requirements:

    • q, k, v must be FP16/BF16 dtype.
    • Default shape: (batch_size, head_num, seq_len, head_dim) with tensor_layout="HND".
    • For shape (batch_size, seq_len, head_num, head_dim), set tensor_layout="NHD".
    from sageattention import sageattn
    attn_output = sageattn(q, k, v, tensor_layout="HND", is_causal=False)
  10. Use the sageattn3_blackwell API

    main

    The sageattn3_blackwell function provides microscaling FP4 attention.

    Arguments:

    • q, k, v: Tensors with FP16/BF16 dtype and shape (batch_size, head_num, seq_len, head_dim).
    • is_causal: Boolean determining whether to use a causal mask.

    Returns:

    • attn_output: The result of the attention operation.
    from sageattn3 import sageattn3_blackwell
    attn_output = sageattn3_blackwell(q, k, v, is_causal=False)
  11. Reference SageAttention available APIs

    main

    SageAttention provides several specialized kernels for different quantization and backend requirements:

    APIDescription
    sageattnAutomatically selects the optimal kernel based on GPU.
    sageattn_qk_int8_pv_fp16_tritonINT8 quantization for $QK^ op$ and FP16 for $PV$ using Triton backend.
    sageattn_qk_int8_pv_fp16_cudaINT8 quantization for $QK^ op$ and FP16 for $PV$ using CUDA backend.
    sageattn_qk_int8_pv_fp8_cudaINT8 quantization for $QK^ op$ and FP8 for $PV$ using CUDA backend.
    sageattn_qk_int8_pv_fp8_cuda_sm90INT8 quantization for $QK^ op$ and FP8 for $PV$ using CUDA backend, optimized for Hopper GPUs.
    sageattn_varlenINT8 quantization for $QK^ op$ and FP16 for $PV$ using Triton backend. Supports varying sequence lengths in a batch.