Skip to content
Projets

HKUSTDial/flash-sparse-attention

Voir sur GitHub

À propos

Attention clairsemée entraînable, rapide et économe en mémoire

Systèmes et infrastructure

Comment ces chiffres sont mesurés

What you can do

  • Forward and backward passes for dense and sparse attention
  • Regular batched inputs and varlen inputs
  • Causal attention and local window attention
  • Arbitrary combinations of Q and KV sequence lengths

Progression mesurée des étoiles

in 24h
+3
in 7 days
+1
in 15 days
+4
in 1 month
Historique en cours

Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.

README.md

Original
flash-algo

English | 简体中文

Flash-Sparse-Attention is a high-performance trainable sparse attention implementation that combines Flash Attention's memory efficiency with sparse computation for handling extremely long sequences in Transformer models.

Key Features

[!NOTE] Support for arbitrary mask and bias shapes is available in this branch. The current main branch no longer maintains that feature set.

Supported Features

  • Forward and backward passes for dense and sparse attention
  • Regular batched inputs and varlen inputs
  • Causal attention and local window attention
  • Arbitrary combinations of Q and KV sequence lengths
  • Grouped Query Attention and Multi Query Attention
  • Sparse softmax threshold control
  • Flex Local Window Attention with per-head arbitrary window sizes and local ranges
  • Split-KV for workload balancing in forward and decode workloads
  • Split-QO for workload balancing in backward workloads
  • Packed GQA for decode workloads

Backend Support

Backend Selection
Gluon Default on SM80 and SM90
Triton Default on other architectures

For complete API documentation, please refer to here

Installation

Requirements

  • Linux: Ubuntu 22.04 or later
  • Device: NVIDIA GPU
  • Python: 3.12 or later
  • PyTorch: 2.5.1 or later
  • Triton: current main branch with Gluon support

Install

Install from PyPI:

pip install flash-sparse-attn

To install from source:

git clone https://github.com/HKUSTDial/flash-sparse-attention.git
cd flash-sparse-attention
pip install .

Quick Start

Basic Usage

Below are examples for forward, backward, and decode.

import torch
from flash_sparse_attn import flash_attn_func, flash_attn_varlen_func

dtype = torch.bfloat16
device = torch.device("cuda")
batch_size, seqlen, num_heads, num_kv_heads, head_dim = 2, 4096, 32, 8, 128

Forward

Combine local, sparse, and split.

query = torch.randn(batch_size, seqlen, num_heads, head_dim, dtype=dtype, device=device)
key = torch.randn(batch_size, seqlen, num_kv_heads, head_dim, dtype=dtype, device=device)
value = torch.randn(batch_size, seqlen, num_kv_heads, head_dim, dtype=dtype, device=device)

output = flash_attn_func(
    query, key, value,
    is_causal=True,
    is_sparse=True,
    is_local=True,
    is_split_kv=True,
)

Backward

Combine local, sparse, and split.

query = torch.randn(batch_size, seqlen, num_heads, head_dim, dtype=dtype, device=device, requires_grad=True)
key = torch.randn(batch_size, seqlen, num_kv_heads, head_dim, dtype=dtype, device=device, requires_grad=True)
value = torch.randn(batch_size, seqlen, num_kv_heads, head_dim, dtype=dtype, device=device, requires_grad=True)

output = flash_attn_func(
    query, key, value,
    is_causal=True,
    is_sparse=True,
    is_local=True,
    is_split_qo=True,
)

output.sum().backward()

Decode

Combine local, sparse, and split.

query = torch.randn(batch_size, 1, num_heads, head_dim, dtype=dtype, device=device)
key = torch.randn(batch_size, seqlen, num_kv_heads, head_dim, dtype=dtype, device=device)
value = torch.randn(batch_size, seqlen, num_kv_heads, head_dim, dtype=dtype, device=device)

def fsa_decode_fn():
    return flash_attn_func(
        query, key, value,
        is_local=True,
        is_sparse=True,
        is_split_kv=True,
    )

# Warmup
for _ in range(3):
    fsa_decode_fn()
torch.cuda.synchronize()

# Capture Graph
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
    output = fsa_decode_fn()

# Replay
graph.replay()

Explicit Backend Selection

The package-level import is recommended for normal use. Import a backend directly when comparing implementations or when an application requires Triton-only functionality.

from flash_sparse_attn.ops.gluon.interface import flash_attn_func as gluon_flash_attn_func
from flash_sparse_attn.ops.triton.interface import flash_attn_func as triton_flash_attn_func

Benchmarking

Benchmark scripts are located under tests, covering forward, backward, and decoding performance.

Forward Performance

# Triton backend
python tests/benchmark_forward.py --backend triton

# Gluon backend
python tests/benchmark_forward.py --backend gluon

# CuTe backend
python tests/benchmark_forward_cute.py

Backward Performance

# Triton backend
python tests/benchmark_backward.py --backend triton

# Gluon backend
python tests/benchmark_backward.py --backend gluon

# CuTe backend
python tests/benchmark_backward_cute.py

Decode Performance

# Triton backend
python tests/benchmark_decode.py --backend triton

# Gluon backend
python tests/benchmark_decode.py --backend gluon

# CuTe backend
python tests/benchmark_decode_cute.py

Correctness Tests

python -m pytest tests --backend triton
python -m pytest tests --backend gluon

Citation

If you use FSA in your research, please cite:

@misc{shi2026cowindowattentioncausalcoverage,
      title={CoWindow Attention: Full Causal Coverage Is a Collective Property}, 
      author={Jingze Shi and Zhangyang Peng and Xianduo Li and Yanlin Qi and Xiaotian Lin and Haoxian Chen and Liangdong Wang and Guang Liu and Yuyu Luo},
      year={2026},
      eprint={2609.32704},
      archivePrefix={arXiv},
      primaryClass={cs.AI},
      url={https://arxiv.org/abs/2609.32704}, 
}

@misc{shi2026massallocattentionletattention,
      title={MassAlloc Attention: Let Attention Allocate Its Own Compute}, 
      author={Jingze Shi and Zhangyang Peng and Xianduo Li and Yanlin Qi and Xiaotian Lin and Haoxian Chen and Liangdong Wang and Guang Liu and Yuyu Luo},
      year={2026},
      eprint={2609.32712},
      archivePrefix={arXiv},
      primaryClass={cs.AI},
      url={https://arxiv.org/abs/2609.32712}, 
}

@misc{shi2025trainabledynamicmasksparse,
      title={Trainable Dynamic Mask Sparse Attention},
      author={Jingze Shi and Yifan Wu and Bingheng Wu and Yiran Peng and Liangdong Wang and Guang Liu and Yuyu Luo},
      year={2025},
      eprint={2508.02124},
      archivePrefix={arXiv},
      primaryClass={cs.AI},
      url={https://arxiv.org/abs/2508.02124},
}

Acknowledgments

This project builds upon and integrates several excellent works:

We thank the open-source community for its contributions to efficient Transformer implementations. 🤗

Explorer des projets similaires

Chargement…