Search

Search papers and lessons

Native Sparse Attention: Hardware-Aligned and Natively Trainable Sparse Atten...

Jingyang Yuan, Huazuo Gao, Damai Dai et al. · 2025

NSA makes sparse attention trainable from the start: each query reads three sparse views of the past, mixed by learned gates, with kernels fast enough to beat full attention at 64k tokens.

On this page

  • Colour = topic mix
  • Calculus
  • Discrete math
  • Neural network basics
  • Linear algebra
  • Probability
  • Architectures
  • ReadReady to readNot yet

TL;DR

Long prompts make attention expensive, because every new token must look back at every earlier token. Earlier sparse attention methods cut that cost mostly at inference time, on models that were trained with full attention, and they often did not run faster in practice. NSA (Native Sparse Attention) trains the sparse pattern from the first pretraining step. Each query reads three compact views of the past: compressed blocks for the global picture, a few whole blocks chosen by score for detail, and a sliding window for the nearby tokens. A learned gate mixes the three. The authors report a 27B-parameter model that matches or beats full attention on their benchmarks and kernels that run up to 9.0 times faster than a FlashAttention-2 kernel on forward passes at 64k tokens.

Builds on: Sparse Attention, Sliding Window Attention, FlashAttention: Fast and Memory-Efficient Exact Attention · Leads to: Sparse Attention (its trainable, hardware-aligned form)

Why it mattered

Long-context work is now routine: models read whole codebases, long reports and long chains of reasoning. In that regime the cost of the key-value cache during decoding, and the cost of attention during training and prefill, dominate. The paper argues that attention alone accounts for 70 to 80 percent of decoding latency at 64k-token contexts, based on theoretical estimates it cites. NSA trains its sparsity end to end from pretraining onward, and it pairs the algorithm with kernels designed around GPU memory access. The authors position the design against the inference-only methods it cites, such as H2O, Quest and InfLLM, which prune an already trained full-attention model.

The problem

Full attention lets query qt\mathbf{q}_t weigh all tt earlier keys. The cost grows with tt, and during decoding every step must read the whole key-value cache from memory. The paper names two obstacles to making sparse attention pay off.

Inference speed does not follow sparsity. Methods that sparsify only decoding, such as H2O, still pay full cost during prefill. Methods that sparsify only prefill, such as MInference, do not help decoding. Methods that select a different KV subset per query head are a poor fit for grouped-query attention, because the memory that must be read is the union of the selections of all heads in a group.

Sparsity is not trained. A pretrained full-attention model is pruned after the fact, which the paper says pushes the model away from the optimum it found during training. Trainable alternatives cause other trouble: clustering and hashing steps break the gradient path, and token-by-token selection reads scattered memory, so it cannot use the contiguous block loads that make FlashAttention fast.

NSA is designed so that the selection is differentiable through a learned gate, and so that every memory access is block-contiguous.

History

Attention was introduced for machine translation in the mid-2010s, and the transformer made it the core of language models in 2017. Its cost grows with the square of the sequence length during training and linearly per token during decoding, so long contexts became a central engineering problem. Through 2023 and 2024, many groups proposed sparse or compressed attention for inference, including the eviction and selection methods the paper cites. Those methods often kept the full-attention model unchanged and reduced memory, but they rarely gave a matching speedup in the serving stack. NSA, posted to arXiv in 2025, addresses training and serving with one design: a three-branch structure, block-level selection and GQA-aware scoring, with kernels built on the same blockwise memory pattern that FlashAttention uses.

How it works

The walkthrough uses the paper's notation and its published configuration. Symbols are defined in the math section below. For the general idea of sparse attention, see Sparse Attention.

  1. Split the past into blocks. Keys and values are grouped into blocks of length ll = 32, one new block starting every dd = 16 positions. Overlapping blocks means each position appears in more than one block.
  2. Compress each block. A learned MLP φ\varphi turns the 32 keys of one block into one compressed key, and the same for values. A query sees one short summary per block, which is about 16 times fewer items than the raw tokens. This is the compression branch: coarse, global, cheap.
  3. Score the blocks with the compressed attention. The attention weights that the query puts on the compressed keys are already computed in step 2's branch. They are reused as an importance score for each block. No separate scoring network is needed.
  4. Select the top blocks. Keys and values are also grouped into selection blocks of length l′l' = 64. The query keeps the nn = 16 highest-scoring selection blocks. Within those 16, the paper fixes one initial block and two local blocks. This is the selection branch: fine-grained, but only where the score says it matters.
  5. Slide a window. The last ww = 512 tokens are kept in full. This is the sliding window branch, for local text the other two branches might smooth over.
  6. Run attention three times with separate keys and values. Each branch has its own key and value tensors, so the branches cannot shortcut each other during training. The paper says this prevents the local pattern from dominating learning.
  7. Mix the three outputs with gates. Each branch output is multiplied by a gate gtcg_t^c between 0 and 1, which an MLP and a sigmoid compute from the input, and the results are summed.

Tiny trace, with invented numbers for illustration (not the paper's): suppose the three branches return 2.0, 4.0 and 1.0, and the gates are 0.5, 0.3 and 0.2.

  • Compression: 0.5×2.0=1.00.5 \times 2.0 = 1.0. Check: the branch is weighted by its gate.
  • Selection: 0.3×4.0=1.20.3 \times 4.0 = 1.2. Check: 1.0 plus 1.2 is 2.2 so far.
  • Window: 0.2×1.0=0.20.2 \times 1.0 = 0.2. Check: 2.2 plus 0.2 gives 2.4, the output.

Diagram of the data flow:

flowchart LR
  Q["query q_t"] --> C["compression: block summaries"]
  Q --> S["selection: top n blocks"]
  Q --> W["sliding window: last w tokens"]
  C -->|"scores reused"| S
  C --> G["gates g_t from an MLP and sigmoid"]
  S --> G
  W --> G
  G --> O["output o_t: weighted sum"]

The math

The paper first writes full attention as a weighted average over all keys. For query qt\mathbf{q}_t with keys and values up to position tt:

Attn⁡(qt,k:t,v:t)=∑i=1tαt,ivi∑j=1tαt,j,αt,i=exp⁡(qt⊤kidk)\operatorname{Attn}(\mathbf{q}_t,\mathbf{k}_{:t},\mathbf{v}_{:t})=\sum_{i=1}^{t}\frac{\alpha_{t,i}\mathbf{v}_i}{\sum_{j=1}^{t}\alpha_{t,j}},\quad \alpha_{t,i}=\exp\left(\frac{\mathbf{q}_t^{\top}\mathbf{k}_i}{\sqrt{d_k}}\right)

Here αt,i\alpha_{t,i} is the weight of key ii, and dkd_k is the key dimension. The denominator makes the weights sum to 1, which is why this is a weighted average.

Step 2 in symbols

Compression maps the keys to one key per block:

K~tcmp={φ(kid+1:id+l) | 0≤i≤⌊t−ld⌋}\tilde{K}^{\text{cmp}}_{t}=\left\{\varphi(\mathbf{k}_{id+1:id+l})\ \middle|\ 0\le i\le\left\lfloor\frac{t-l}{d}\right\rfloor\right\}

The number of compressed keys is ⌊(t−l)/d⌋+1\lfloor (t-l)/d \rfloor + 1. Here ll is the block length, dd the stride, and φ\varphi the learned MLP. The paper uses d<ld < l so that a token falls into several blocks.

Step 3 in symbols

The block scores are the softmax of the query against the compressed keys:

ptcmp=Softmax⁡(qt⊤K~tcmp)\mathbf{p}_t^{\text{cmp}}=\operatorname{Softmax}\left(\mathbf{q}_t^{\top}\tilde{K}^{\text{cmp}}_t\right)

When the selection blocks have the same size and stride as the compression blocks, these scores are the selection scores directly. In a grouped-query model, the scores of the HH query heads in one group are summed, so that all heads select the same blocks and the group loads each KV block once:

ptslc′=∑h=1Hptslc,(h){\mathbf{p}_t^{\text{slc}}}'=\sum_{h=1}^{H}\mathbf{p}_t^{\text{slc},(h)}

Step 4 in symbols

The selected index set keeps the nn largest scores, and the selected keys are the concatenation of those blocks:

It={i∣rank⁡(ptslc′[i])≤n},K~tslc=Cat⁡[{kil′+1:(i+1)l′∣i∈It}]\mathcal{I}_t=\{i\mid \operatorname{rank}({\mathbf{p}_t^{\text{slc}}}'[i])\le n\},\qquad \tilde{K}^{\text{slc}}_t=\operatorname{Cat}\left[\{\mathbf{k}_{il'+1:(i+1)l'}\mid i\in\mathcal{I}_t\}\right]

Rank 1 is the highest score. The selected set has n l′n\,l' keys, which is 16 times 64 = 1024 in the paper's configuration.

Step 5 and step 7 in symbols

The window keeps the last ww keys, K~twin=kt−w:t\tilde{K}^{\text{win}}_t=\mathbf{k}_{t-w:t}, and the three branch outputs are combined with gates:

ot∗=∑c∈{cmp,slc,win}gtc⋅Attn⁡ ⁣(qt,K~tc,V~tc),gtc∈[0,1]\mathbf{o}^{*}_t=\sum_{c\in\{\text{cmp},\text{slc},\text{win}\}} g_t^{c}\cdot\operatorname{Attn}\!\left(\mathbf{q}_t,\tilde{K}^{c}_t,\tilde{V}^{c}_t\right),\qquad g_t^c\in[0,1]

The paper keeps the total number of keys read small, Nt=∑csize[K~tc]≪tN_t=\sum_c \text{size}[\tilde{K}^c_t] \ll t. Because the gates come from a sigmoid, they need not sum to 1. This differs from the toy trace above, where they did.

Worked examples

Example
Counting compressed keys (tiny, by hand)
  1. Take block length l=4l=4, stride d=2d=2, and a sequence of t=10t=10 tokens.
  2. Compute ⌊(t−l)/d⌋=⌊(10−4)/2⌋=⌊3⌋=3\lfloor (t-l)/d\rfloor = \lfloor (10-4)/2\rfloor = \lfloor 3 \rfloor = 3.
  3. The index ii runs from 0 to 3, which is 4 values, so there are 4 compressed keys.
  4. Interpretation: 10 tokens became 4 summaries. Each summary covers 4 tokens, and neighbouring summaries overlap by 2.
Example
The paper's configuration at 8,192 tokens (standard)
  1. Use the paper's compression block l=32l=32, stride d=16d=16, and a context t=8192t=8192.
  2. Compressed keys, by the paper's bound on the cache read per decoding step: ⌊(8192−32)/16⌋=⌊8160/16⌋=510\lfloor (8192-32)/16\rfloor = \lfloor 8160/16 \rfloor = 510.
  3. Selected keys: n l′=16×64=1024n\,l' = 16 \times 64 = 1024.
  4. Window keys: w=512w = 512.
  5. Total keys read per decoding step: 510+1024+512=2046510 + 1024 + 512 = 2046. The paper's Table 4 reports 2048 for this length. The text does not explain the 2-token difference, so this lesson uses the formula's count, 2046.
  6. Interpretation: a query at position 8192 reads about a quarter of the 8192 keys that full attention reads. That is the point of the design: the work per query is set by n l′n\,l' and ww, not by the full length.
Example
Reading the paper's decoding speedup (realistic)

Table 4 of the paper gives the memory accessed per decoding step as 3584 tokens for NSA at 32,768 context and 32,768 for full attention, and reports an expected speedup of 9.1 times at that length. The paper explains that decoding is memory bound, so speed follows the volume of memory read.

  1. Compute the ratio of full to NSA memory access at 32,768 tokens: 32768/358432768 / 3584.
  2. Divide: 32768/3584=9.14…32768 / 3584 = 9.14\ldots.
  3. Round to one decimal place: 9.1.
  4. Interpretation: the paper's 9.1 times figure is this ratio. It is an estimate from memory traffic, not a measured time. The measured kernel speedups in Section 5.1 are separate numbers.

Try it: repeat steps 1 to 3 for 65,536 tokens, using NSA's 5632 tokens read. Answer: 65536/5632=11.6…65536/5632 = 11.6\ldots, which rounds to 11.6, matching the paper's largest decoding figure.

Results

The paper reports four groups of results. Each number below is copied from the paper's text or tables.

  • General benchmarks (Table 1). A 27B-total, 3B-active mixture-of-experts model with grouped-query attention, pretrained on 260 billion tokens of 8k-length text and then extended to 32k with YaRN. NSA averages 0.456 and full attention 0.443 across nine benchmarks. NSA is best on 7 of 9 metrics. The gains on DROP (+0.042) and GSM8K (+0.034) are the largest.
  • Long-context benchmarks (Table 2, LongBench). NSA averages 0.469, against 0.437 for full attention and 0.423 for the Exact-Top oracle. The sparse baselines were given a matched token budget of 2560 tokens per query.
  • Needle in a haystack. The paper reports perfect retrieval at every position of a 64k-token context.
  • Reasoning (Table 3, AIME 24). After supervised fine-tuning on 10 billion tokens of 32k-length reasoning traces distilled from DeepSeek-R1, NSA-R scores 0.121 against 0.046 for full attention with an 8k generation limit, and 0.146 against 0.092 with 16k. The authors use 16 samples per question, temperature 0.7 and top-p 0.95.
  • Speed (Section 5). Training kernel speedups of up to 9.0 times forward and 6.0 times backward at 64k, against a Triton FlashAttention-2 baseline on an 8-GPU A100 system. Decoding memory-access ratios of 4.0, 6.4, 9.1 and 11.6 times at 8k, 16k, 32k and 64k.

Limits. Every benchmark comparison is against the authors' own full-attention baseline, trained on the same data. The reasoning result depends on one distillation setup. The decoding speedups are estimates from memory volume. The kernel speedups compare Triton implementations with each other, so they do not measure the speed of production serving stacks. The model is 27B total parameters, and the paper does not show how the results scale to larger models.

Common mistakes and tradeoffs

It is tempting to think that NSA is just a fixed sliding window with a few extra tokens. In fact the selection branch is data dependent: the top 16 blocks change with each query, so the model can reach a distant but relevant passage. The sliding window is one of three branches, not the whole method.

It is tempting to read "9.0 times faster" as an end-to-end speedup. In fact the 9.0 times figure is the forward pass of a kernel compared with a Triton FlashAttention-2 kernel, at 64k tokens, on A100 GPUs. It does not include the rest of the model, and the paper's backward speedup at the same length is 6.0 times.

It is tempting to think that a sparse model is always a weaker model. The paper reports that, after pretraining with NSA, the model scores higher than the full-attention baseline on 7 of 9 general benchmarks, with an average of 0.456 against 0.443. The comparison is one 27B model against one full-attention baseline. The paper also notes that most general benchmark samples fit inside the sparse methods' local window, so those methods are effectively full attention there.

Tradeoffs. NSA is worth its extra machinery when contexts are long, when decoding dominates the cost, and when the model is trained from scratch or continued with the sparse pattern. It adds three branches, a learned gate, block-level selection and specialised kernels, so it is more to build and to debug than a sliding window. For short contexts, a plain full-attention model with an optimised kernel is simpler. The paper's decoding table starts at 8k tokens, so it gives no speed numbers below that. Simpler alternatives are the sliding window alone, which has no global reach, and inference-only pruning, which is cheap to add but, by the paper's argument, does not train the sparse pattern.

Reading guide

The paper's sections, in order, with the lessons each one needs.

Check yourself

QuestionWhy does NSA use a sliding window branch in addition to compression and selection?Show answer

The paper argues that local patterns adapt quickly and can dominate learning. Without a dedicated window, the compression and selection branches could learn to imitate nearby attention rather than learning long-range structure. Giving the window its own keys and values keeps the three branches from shortcutting each other.

QuestionA context has t=4096t = 4096 tokens, compression block length l=32l = 32 and stride d=16d = 16. How many compressed keys does the compression branch produce, counting the index 0?Show answer

⌊(4096−32)/16⌋=⌊4064/16⌋=254\lfloor (4096 - 32)/16 \rfloor = \lfloor 4064/16 \rfloor = 254. The index runs from 0 to 254, so there are 255 compressed keys.

QuestionIn a grouped-query model, why are the block scores of all query heads in one group summed before selection?Show answer

The keys and values of a group are shared, so every head in the group reads the same KV blocks from memory. If each head chose different blocks, the group would read the union of all choices. Summing the scores makes one shared choice, so each KV block is loaded once for the group.

QuestionUsing the paper's decoding table, what is the expected speedup at 16,384 tokens, and what does the figure measure?Show answer

At 16,384 tokens full attention reads 16,384 tokens and NSA reads 2560, so the ratio is 16384/2560=6.416384 / 2560 = 6.4. The figure measures the ratio of memory traffic per decoding step, which the paper uses as an estimate of speed because decoding is memory bound. It is not a measured wall-clock speedup.

QuestionYour colleague says NSA is a method that prunes a trained full-attention model at inference. Correct or not, and why?Show answer

Not correct. NSA is trained with its sparse pattern from pretraining onward, with gates and the three branches learned end to end. The paper contrasts itself with inference-only methods such as H2O, Quest and InfLLM, which prune an existing full-attention model.

Sources

Read the full paper

Jingyang Yuan, Huazuo Gao, Damai Dai et al., 2025. arXiv:2502.11089