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 weigh all earlier keys. The cost grows with , 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.
- Split the past into blocks. Keys and values are grouped into blocks of length = 32, one new block starting every = 16 positions. Overlapping blocks means each position appears in more than one block.
- Compress each block. A learned MLP 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.
- 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.
- Select the top blocks. Keys and values are also grouped into selection blocks of length = 64. The query keeps the = 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.
- Slide a window. The last = 512 tokens are kept in full. This is the sliding window branch, for local text the other two branches might smooth over.
- 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.
- Mix the three outputs with gates. Each branch output is multiplied by a gate 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: . Check: the branch is weighted by its gate.
- Selection: . Check: 1.0 plus 1.2 is 2.2 so far.
- Window: . 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 with keys and values up to position :
Here is the weight of key , and 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:
The number of compressed keys is . Here is the block length, the stride, and the learned MLP. The paper uses 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:
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 query heads in one group are summed, so that all heads select the same blocks and the group loads each KV block once:
Step 4 in symbols
The selected index set keeps the largest scores, and the selected keys are the concatenation of those blocks:
Rank 1 is the highest score. The selected set has keys, which is 16 times 64 = 1024 in the paper's configuration.
Step 5 and step 7 in symbols
The window keeps the last keys, , and the three branch outputs are combined with gates:
The paper keeps the total number of keys read small, . 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
- Take block length , stride , and a sequence of tokens.
- Compute .
- The index runs from 0 to 3, which is 4 values, so there are 4 compressed keys.
- Interpretation: 10 tokens became 4 summaries. Each summary covers 4 tokens, and neighbouring summaries overlap by 2.
- Use the paper's compression block , stride , and a context .
- Compressed keys, by the paper's bound on the cache read per decoding step: .
- Selected keys: .
- Window keys: .
- Total keys read per decoding step: . 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.
- 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 and , not by the full length.
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.
- Compute the ratio of full to NSA memory access at 32,768 tokens: .
- Divide: .
- Round to one decimal place: 9.1.
- 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: , 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.
- Section 1 (Introduction) needs Attention Mechanism and Sparse Attention. Note the claim about decoding latency at 64k tokens, which is an estimate the paper cites.
- Section 2 (Rethinking sparse attention) needs KV Cache, Multi-Query Attention and Grouped-Query Attention. Section 2.1 is about how a KV subset interacts with grouped heads.
- Section 3.1 (Background) needs Attention Mechanism and Softmax. The paper's "arithmetic intensity" is the ratio of arithmetic to memory traffic; it is the reason training is compute bound and decoding is memory bound.
- Section 3.3 (Algorithm design) needs Sliding Window Attention and Sparse Attention for the window and selection ideas, and Softmax for the block scores.
- Section 3.4 (Kernel design) needs FlashAttention: Fast and Memory-Efficient Exact Attention, GPU Memory Hierarchy and Tensor Core.
- Section 4 (Experiments) needs Mixture of Experts, Rotary Position Embedding and Chain-of-Thought Prompting. The distillation step in 4.3 uses Knowledge Distillation.
- Section 5 (Efficiency) needs GPU Memory Hierarchy and KV Cache.
- Section 6 and 7 (Discussion and related work) need Attention Sink for the streaming-window baselines and Sparse Attention for the wider taxonomy.
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 tokens, compression block length and stride . How many compressed keys does the compression branch produce, counting the index 0?Show answer
. 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 . 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
- Yuan et al., "Native Sparse Attention: Hardware-Aligned and Natively Trainable Sparse Attention," arXiv:2502.11089, 2025. arxiv.org/abs/2502.11089
- DOI record for arXiv:2502.11089: doi.org/10.48550/arXiv.2502.11089