Native Sparse Attention (NSA) & KV-Cache Eviction at 1M+ Context
In Attention Engineering: From MHA to GQA, MLA & FlashAttention, we cut attention HBM traffic via tiled SRAM kernels and compressed KV latents – yet full attention still scales quadratically $O(T^2)$ in prefill and reads $O(T)$ KV bytes per decoded token. Post-hoc KV eviction heuristics (dropping low-attention tokens at inference) break down on needle-in-a-haystack reasoning because the model was never trained to survive sparse masks. Native Sparse Attention (NSA) (Yuan et al., DeepSeek-AI 2025, arXiv:2502.11089) solves both problems at once: it is end-to-end trainable from pretraining and hardware-aligned to GPU Tensor Cores.
1. The Three-Branch Hierarchical Sparse Decomposition
For every query $\mathbf{q}_t$, NSA constructs three complementary key-value representations – Coarse Compression ($\tilde{K}_{\text{cmp}}, \tilde{V}_{\text{cmp}}$), Fine-Grained Top-$n$ Block Selection ($\tilde{K}_{\text{slc}}, \tilde{V}_{\text{slc}}$), and a Local Sliding Window ($\tilde{K}_{\text{win}}, \tilde{V}_{\text{win}}$) – and blends their attention outputs with learned sigmoid gates:
Why keep the sliding window separate from block selection? If a single attention head handles both local syntax and distant retrieval, local tokens dominate the gradient early in training and starve the learned block selector. Decoupling the three branches with independent gates lets the sliding window handle local fluency while the compression and selection branches specialize purely in long-range retrieval.
2. Hardware Alignment: Why GQA Group-Shared Selection Matters
Naive token-level sparsity destroys GPU utilization: if each query head fetches different scattered tokens from HBM, memory coalescing collapses and Tensor Cores stall. NSA fixes this with two hardware rules:
- Contiguous Block Granularity ($l' = 64$): Loading contiguous 64-token KV blocks saturates HBM burst bandwidth and matches Triton MMA tile dimensions.
- GQA Head-Group Sharing: All $h = 16$ query heads sharing one KV head aggregate their compressed importance scores ($\mathbf{p}_{\text{slc}} = \sum_{m=1}^{h} \mathbf{p}_{\text{cmp}}^{(m)}$) and load the exact same top-$n$ KV blocks into SRAM – boosting arithmetic intensity by $16\times$!
💻 Python: Native Sparse Attention 3-Branch Compression & Gated FusionPyTorch
import torch
import torch.nn as nn
class NativeSparseAttentionBlock(nn.Module):
"""Simplified 3-branch Native Sparse Attention (Compress + Select + Window) with GQA group sharing."""
def __init__(self, d_model: int, n_heads: int, n_kv_heads: int,
block_len: int = 32, stride: int = 16, top_n: int = 16, window: int = 512):
super().__init__()
self.d_head = d_model // n_heads
self.n_heads, self.n_kv_heads = n_heads, n_kv_heads
self.block_len, self.stride, self.top_n, self.window = block_len, stride, top_n, window
self.compress_k = nn.Linear(block_len * self.d_head, self.d_head, bias=False)
self.compress_v = nn.Linear(block_len * self.d_head, self.d_head, bias=False)
self.gate_proj = nn.Linear(d_model, 3 * n_heads)
def compress_kv(self, k: torch.Tensor, v: torch.Tensor):
# k, v: [B, H_kv, T, D] -> coarse blocks [B, H_kv, N_blk, D]
B, H, T, D = k.shape
k_unf = k.unfold(2, self.block_len, self.stride).transpose(-1, -2).reshape(B, H, -1, self.block_len * D)
v_unf = v.unfold(2, self.block_len, self.stride).transpose(-1, -2).reshape(B, H, -1, self.block_len * D)
return self.compress_k(k_unf), self.compress_v(v_unf)
def combine_branches(self, x_q, o_cmp, o_slc, o_win):
# x_q: [B, T, d_model], o_*: [B, T, n_heads, d_head]
# Learned per-head sigmoid gates prevent gradient starvation between branches
g = torch.sigmoid(self.gate_proj(x_q)).view(*o_cmp.shape[:-1], 3, 1)
return g[..., 0, :] * o_cmp + g[..., 1, :] * o_slc + g[..., 2, :] * o_win
| Method | Trainable End-to-End? | Hardware-Aligned Tiles? | 64k Decode HBM Traffic |
|---|---|---|---|
| Full FlashAttention-2 | Yes | Yes | $100\%$ ($O(T)$ KV reads/token) |
| Post-Hoc Eviction (H2O / SnapKV) | No (inference heuristic) | Scattered tokens | $15$–$25\%$ (quality degrades on multi-hop) |
| Native Sparse Attention (NSA) | Yes (from pretraining) | Yes (GQA block tiles) | $\sim 8$–$12\%$ (matches/beats full attn) |