Introduction
Long-context modeling is increasingly important as a core capability for next-generation large language models, driven by real-world applications such as deep reasoning, repository-level code generation, and multi-turn autonomous agent systems.
However, as sequence length grows, the high complexity of vanilla attention becomes a key latency bottleneck.
Theoretical estimates show that attention computation using softmax architectures accounts for 70–80% of total latency when decoding 64k-length contexts, highlighting the urgent need for more efficient attention mechanisms.

Figure 1 | Comparison of performance and efficiency between Full Attention model and NSA.
A natural approach to efficient long-context modeling is to exploit the sparsity inherent in softmax attention: by selectively computing key query-key pairs, we can significantly reduce computational overhead while maintaining performance. Recent work has demonstrated this potential through a variety of strategies: KV cache eviction, blockwise KV cache selection, and selection based on sampling, clustering, or hashing.
Despite their promise, existing sparse attention methods often fall short in real-world deployment.
To address these limitations, deploying effective sparse attention must tackle two key challenges:
- Hardware-aligned inference acceleration: turning theoretical compute reductions into real speedups requires hardware-friendly algorithm design in both prefill and decoding phases to alleviate memory-access and hardware-scheduling bottlenecks;
- Training-aware algorithm design: enable end-to-end computation through trainable operators to lower training costs while maintaining model performance. These requirements are critical to making fast long-context inference or training practical. Existing methods still leave a clear gap on both fronts.
NSA (Native Sparse Attention)

Figure 2 | Overview of NSA’s architecture.
As shown in Figure 2, left: the framework processes the input sequence through three parallel attention branches. For a given query, the forward keys and values are processed by compressed attention to handle coarse-grained patterns, selected attention to handle important token blocks, and sliding attention to handle local context.
Right: visualization of the different attention patterns produced by each branch. Green areas indicate regions where attention scores must be computed, while white areas indicate regions that can be skipped.
NSA reduces the computation per query by organizing keys and values into temporal blocks and processing them through three attention paths: compressed coarse-grained tokens, selectively retained fine-grained tokens, and a sliding window for local context. It then implements specialized kernels to maximize practical efficiency.
NSA introduces two core innovations that address the key requirements above:
- Hardware-aligned system: optimize blockwise sparse attention for Tensor Core utilization and memory access, ensuring balanced arithmetic intensity.
- Training-aware design: achieve stable end-to-end training through efficient algorithms and backward operations. This optimization enables NSA to support both efficient deployment and end-to-end training.
We evaluate NSA through comprehensive experiments on real-world language corpora. After pretraining a 27B-parameter transformer backbone on 260B tokens, we evaluated NSA on general language benchmarks, long-context benchmarks, and chain-of-thought reasoning benchmarks.
We also compared kernel speed using an optimized Triton implementation (Tillet et al., 2019) on A100 GPUs. Experimental results show that NSA outperforms existing sparse attention methods while achieving performance comparable to or better than the full-attention baseline.
In addition, compared with full attention, NSA delivers significant speedups in decoding, forward, and backward phases, and the speedup grows with longer sequences. These results confirm that our hierarchical sparse attention design effectively balances model capability and computational efficiency.
Rethinking Sparse Attention Methods
Modern sparse attention methods have made significant progress in reducing the theoretical computational complexity of Transformer models. However, most methods apply sparsity mainly during inference while keeping a pretrained full-attention backbone, which can introduce architectural bias and limit their ability to fully exploit the advantages of sparse attention.
We systematically analyze these limitations through two key lenses.
The Illusion of Efficient Inference
Although they achieve sparsity in attention computation, many methods fail to deliver corresponding reductions in inference latency, mainly due to two challenges:
Phase-Restricted Sparsity.
For example, methods such as H2O apply sparsity during autoregressive decoding but require compute-intensive preprocessing for prefill, such as attention-map computation and index construction. By contrast, methods such as MInference focus only on prefill sparsity. These methods fail to accelerate all inference phases because at least one phase has a computational cost comparable to full attention. This phase specialization reduces their speedup potential on prefill-heavy workloads (such as book summarization and code completion) or decode-heavy workloads (such as long chain-of-thought reasoning).
Incompatibility with Advanced Attention Architecture.
They are incompatible with modern decode-efficient architectures such as Multi-Query Attention (MQA) and Grouped-Query Attention (GQA), which significantly reduce memory-access bottlenecks during decoding by sharing KV across multiple query heads.
For example, in methods such as Quest, each attention head independently selects its KV-cache subset. Although this demonstrates consistent computational sparsity and memory-access sparsity in multi-head attention (MHA) models, in models based on architectures such as GQA, the KV-cache memory access corresponds to the union of the selections made by all query heads in the same GQA group. This architectural property means that while these methods can reduce compute operations, the required KV-cache memory access remains relatively high. This limitation forces a critical trade-off: although some sparse attention methods reduce computation, their scattered memory-access patterns conflict with the efficient memory-access designs of advanced architectures.
These limitations arise because many existing sparse attention methods focus on KV-cache reduction or theoretical compute reduction but struggle to achieve meaningful latency reductions in advanced frameworks or backends. This motivated us to develop algorithms that combine advanced architectures with hardware-efficient implementations to fully exploit sparsity for model efficiency.
The Myth of Trainable Sparsity
Our motivation for pursuing natively trainable sparse attention comes from two key insights gained by analyzing inference-only methods:
- Performance degradation. Applying sparsity post hoc forces the model away from its pretraining optimization trajectory. As Chen et al. (2024) show, the top 20% of attention covers only 70% of the total attention score, making structures such as retrieval heads in pretrained models vulnerable to pruning during inference.
- Training-efficiency requirements. Handling long-sequence training efficiently is essential for modern LLM development. This includes pretraining on longer documents to increase model capacity, as well as subsequent adaptation stages such as long-context fine-tuning and reinforcement learning.
However, existing sparse attention methods target inference and largely leave the computational challenges of training unaddressed. This limitation hinders the development of more capable long-context models through efficient training. Moreover, attempts to adapt existing sparse attention to training expose additional challenges:
Non-Trainable Components
Discrete operations in methods such as ClusterKV (including k-means clustering) and MagicPIG (including SimHash-based selection) create discontinuities in the computational graph. These non-trainable components prevent gradients from flowing through the token-selection process, limiting the model's ability to learn optimal sparse patterns.
Inefficient Back-propagation
Some theoretically trainable sparse attention methods are inefficient in actual training. Token-granularity selection strategies, as used in methods such as HashAttention, require loading a large number of individual tokens from the KV cache during attention computation. This non-contiguous memory access prevents the effective adaptation of fast attention techniques such as FlashAttention, which rely on contiguous memory access and block-level computation for high throughput. As a result, implementations are forced to fall back to low hardware utilization, significantly reducing training efficiency.
Native Sparsity as an Imperative
These limitations in inference efficiency and training feasibility motivated us to fundamentally redesign sparse attention. We propose NSA, a native sparse attention framework that addresses both computational efficiency and training requirements.
Algorithm Design
Token Compression
By aggregating contiguous key or value blocks into block-level representations, we obtain compressed keys and values that capture information from the entire block. The compressed representation captures coarser, higher-level semantic information and reduces the computational burden of attention.
Token Selection
Using only compressed keys and values may lose important fine-grained information, which motivates selectively retaining individual keys and values. Below we describe our efficient token-selection mechanism, which identifies and retains the most relevant tokens with low computational overhead.
Blockwise Selection
Our selection strategy processes key and value sequences in spatially contiguous blocks, driven by two key factors: hardware-efficiency considerations and the intrinsic distribution pattern of attention scores.
To implement blockwise selection, we first partition the key-value sequence into selection blocks. To determine which blocks matter most for attention computation, we need to assign an importance score to each block.
Importance Score Computation
Computing importance scores for computation blocks can introduce significant overhead. Fortunately, attention computation over compressed tokens produces intermediate attention scores that we can leverage to derive importance scores for selection blocks.
Top-𝑛 Block Selection
After obtaining importance scores for selection blocks, we retain the tokens in the top n sparse blocks ranked by block importance score.
Sliding Window
In attention mechanisms, local patterns often adapt faster and can dominate the learning process, preventing the model from learning effectively from compressed and selected tokens. To address this, we introduce a dedicated sliding-window branch that explicitly handles local context, allowing the other branches (compression and selection) to focus on learning their respective features without being constrained by local patterns.
Specifically, we maintain the most recent tokens in a window and isolate attention computation for different information sources (compressed tokens, selected tokens, and the sliding window) into separate branches. The outputs of these branches are then aggregated through a learned gating mechanism.
To further prevent cross-branch indirect learning with marginal computational overhead, we give the three branches independent keys and values. This architectural design enables stable learning with minimal overhead by preventing gradient interference between local and long-range pattern recognition.
Kernel Design
To achieve FlashAttention-level speedups during training and prefill, we implemented a hardware-aligned sparse attention kernel in Triton.
Given that MHA is memory-intensive and inefficient for decoding, we focus on architectures with shared KV caches, such as GQA and MQA, which are used by current state-of-the-art LLMs.
Although compressed and sliding-window attention computation is compatible with existing FlashAttention-2 kernels, we introduce a dedicated kernel design for sparse selection attention. If we followed FlashAttention's strategy of loading temporally contiguous query blocks into SRAM, memory access would be inefficient because queries within a block may require non-contiguous KV blocks.
To solve this, our key optimization is a different query-grouping strategy: for each position in the query sequence, we load all query heads within a GQA group—which share the same sparse KV blocks—into SRAM.

Figure 3 | Kernel design for NSA.
Figure 3 illustrates our forward-pass implementation. The kernel loads queries by GQA group (grid loop), fetches the corresponding sparse KV blocks (inner loop), and performs attention computation in SRAM. Green blocks represent data in SRAM, while blue blocks represent data in HBM.
The proposed kernel architecture has the following key features:
- Group-Centric Data Loading.
- Shared KV Fetching.
- Outer Loop on Grid.
This design achieves near-optimal arithmetic intensity by (1) eliminating redundant KV transfers through group sharing and (2) balancing computational workload across GPU streaming multiprocessors.
Performance Comparison
General Evaluation
Overall evaluation. We evaluated pretrained NSA and the full-attention baseline across a range of benchmarks covering knowledge, reasoning, and coding, including MMLU, MMLU-PRO, CMMLU, BBH, GSM8K, MATH, DROP, MBPP, and HumanEval. Results are shown in Table 1.
Table 1 | Pretraining performance comparison between the full attention baseline and NSA on general benchmarks
Despite being sparse, NSA delivers superior overall performance, beating all baselines—including full attention—on 7 of 9 metrics. This shows that although NSA may not fully exploit its efficiency advantages on shorter sequences, it still delivers strong performance.
Notably, NSA achieves significant gains on reasoning-related benchmarks (DROP: +0.042, GSM8K: +0.034), suggesting that our pretraining helps the model develop specialized attention mechanisms. This sparse-attention pretraining regime forces the model to focus on the most important information and may improve performance by filtering out noise from irrelevant attention paths. The system's stable performance across diverse evaluations also confirms the robustness of NSA as a general-purpose architecture.
Long-Context Evaluation

Figure 5 | Needle-in-a-Haystack retrieval accuracy across context positions with 64k context length.
As shown in Figure 5, NSA achieves perfect retrieval accuracy at all positions in the 64k-context needle-in-a-haystack test (Kamradt, 2023). This performance stems from our hierarchical sparse attention design, which combines compressed tokens for efficient context scanning with selected tokens for precise local information retrieval. Coarse-grained compression identifies relevant context blocks at low computational cost, while token-level attention over selected tokens ensures that critical fine-grained information is preserved. This design enables NSA to maintain both global awareness and local precision.
We also evaluated NSA against state-of-the-art sparse attention methods and the full-attention baseline on LongBench (Bai et al., 2023).
Table 2 | Performance comparison between our NSA and baselines on LongBench, including subsets in single document QA, multi-document QA, synthetic and code task categories. NSA outperformed most of the baselines including Full Attention.
As shown in Table 2, NSA achieves the highest average score of 0.469, outperforming all baselines (0.032 higher than full attention and 0.046 higher than Exact-Top).
This improvement stems from two key innovations:
- Our native sparse attention design enables the sparse pattern to be optimized end-to-end during pretraining, promoting synchronized adaptation between the sparse attention module and other model components;
- The hierarchical sparse attention mechanism balances local and global information processing.
Notably, NSA performs well on tasks requiring complex long-context reasoning. It improves over full attention by +0.087 and +0.051 on multi-hop QA tasks (HPQ and 2Wiki), respectively, surpasses the baseline on code understanding (LCC: +0.069), and outperforms other methods on paragraph retrieval (PassR-en: +0.075).
These results validate NSA's ability to handle a variety of long-context challenges, and its natively pretrained sparse attention provides an additional advantage when learning task-optimal patterns.
Chain-of-Thought Reasoning Evaluation
To evaluate NSA's compatibility with advanced downstream training paradigms, we study its ability to acquire chain-of-thought mathematical reasoning through post-training.
Given the limited effectiveness of reinforcement learning on smaller models, we use knowledge distillation from DeepSeek-R1, performing supervised fine-tuning (SFT) on 10B mathematical reasoning traces of length 32k. This yields two comparable models: Full Attention-R (the full-attention baseline) and NSA-R (our sparse variant).
To test the effect of reasoning depth, we ran two experiments with generation-context limits of 8k and 16k tokens, measuring whether extended reasoning chains improve accuracy.
Table 3 | AIME instruction-based evaluation after supervised fine-tuning.
As shown in Table 3, under the 8k-context setting, NSA-R achieves significantly higher accuracy than Full Attention-R (+0.075), and this advantage persists at 16k context (+0.054).
These results validate two key advantages of native sparse attention:
- Pretrained sparse attention patterns can efficiently capture the long-range logical dependencies essential for complex mathematical derivation.
- The hardware-aligned design of our architecture maintains sufficient content density to support increasing reasoning depth without catastrophic forgetting. The consistently strong performance across context lengths confirms the effectiveness of sparse attention for advanced reasoning tasks when it is natively integrated into the training pipeline.
Efficiency Analysis
We evaluated the computational efficiency of NSA versus full attention on an 8-GPU A100 system.
Training Speed
We compared our Triton-based NSA attention and full attention against Triton-based FlashAttention-2 to ensure a fair speed comparison on the same backend.
Figure 6 | Comparison of Triton-based NSA kernel with Triton-based FlashAttention-2 kernel.
As shown in Figure 6, our NSA achieves gradual speedups as context length increases, reaching 9.0× forward speedup and 6.0× backward speedup at a 64k context length. Notably, the speed advantage becomes more pronounced as sequence length grows. This acceleration comes from our hardware-aligned algorithm design, which maximizes the efficiency of the sparse attention architecture: (1) blockwise memory-access patterns maximize Tensor Core utilization through coalesced loads, and (2) fine-grained loop scheduling within the kernel eliminates redundant KV transfers.
Decoding Speed
Attention decoding speed depends mainly on the memory-access bottleneck, which is closely tied to the amount of KV-cache loading. At each decoding step, our NSA needs to load only the compressed tokens at most.

Table 4 | Memory access volume (in equivalent number of tokens) per attention operation during decoding.
As shown in Table 4, our method shows significantly lower latency as decoding length increases, achieving up to 11.6× speedup at a 64k context length. This advantage in memory-access efficiency also grows with sequence length.
Source of inspiration

Figure 8 | Visualization of Attention Map on a Full Attention transformer.
Light-colored regions indicate higher attention values. As shown, attention scores exhibit blockwise clustering.
To explore potential patterns in Transformer attention distributions and seek inspiration for our design, we visualized the attention maps of a pretrained 27B full-attention model in Figure 8.
The visualization reveals interesting patterns: attention scores tend to exhibit blockwise clustering, and nearby keys often show similar attention scores.
This observation inspired our design: selecting key blocks based on spatial contiguity may be a promising approach. The blockwise clustering phenomenon suggests that adjacent tokens in a sequence may share certain semantic relationships with the query token, although the exact nature of these relationships requires further study. This observation motivated us to explore a sparse attention mechanism that operates on contiguous token blocks rather than individual tokens, aiming to improve computational efficiency while preserving high-attention patterns.