HyScale: Scaling Long-Context Training for Learned Sparse Attention
Abstract: We present HyScale, a long-context training system for learned sparse attention. Learned sparse attention is a promising architecture for million-token contexts, widely adopted in production since DeepSeek-V3.2. Selection, however, grows into the training bottleneck. For each query, it scores every previous token whereas sparse attention reads only ; worse, current systems materialize a full score table and repeat selection during recomputation. Our key insight is that the output of selection is not an activation, but rather a set of indices. Building on it, HyScale introduces HyTopK and selection replay. HyTopK finds each query's exact top- on the fly without a score table, while selection replay reuses forward-pass selection in recomputation. Together with holistic system optimizations tackling end-to-end training challenges, HyScale speeds up GLM-5.1 training on 1M-token sequences by 2.07 over Megatron-LM on 512 H20 GPUs. It also speeds up the CSA layers of DeepSeek-V4-Flash and the QSA layers of Qwen3.8-Flash-Next by 2.01 and 1.57 at 1M tokens on 32 H800 GPUs.
Paper Prompts
Sign up for free to create and run prompts on this paper.
Explain it Like I'm 14
1. What is this paper about?
This paper introduces HyScale, a computer system designed to train LLMs on extremely long texts—up to one million tokens at a time.
A token can be a word, part of a word, or a punctuation mark. Training with one million tokens is useful for working with whole books, large computer programs, or long records of an AI agent’s actions.
The paper focuses on making learned sparse attention faster. Attention is the part of an LLM that helps each word decide which earlier words are important. Instead of looking at every earlier word, sparse attention tries to look at only a small number of useful ones.
2. What questions are the researchers asking?
The researchers mainly want to answer these questions:
- How can the model quickly choose the most important previous tokens?
- How can it avoid storing huge amounts of unnecessary information during training?
- How can it avoid repeating the same work when it needs to recompute information?
- Can these improvements work across different kinds of sparse attention?
- Can the system train models faster without using much more GPU memory?
The problem is that sparse attention reduces the amount of information the model uses, but current systems still spend a lot of time checking every possible previous token.
3. How did the researchers approach the problem?
Learned sparse attention
Imagine that every word in a very long document wants to ask:
“Which earlier words should I pay attention to?”
A learned sparse attention system gives each earlier token a score. It then keeps only the best k tokens—for example, the best 2,048 tokens—and ignores the rest.
This is similar to searching through a huge list but keeping only the top results.
The process has two stages:
- Selection: Score all possible earlier tokens and choose the top ones.
- Sparse attention: Use only those chosen tokens to calculate the model’s answer.
Although the second stage is small, the first stage can still be very expensive because it may score millions of tokens.
Problem 1: Storing every score
Older systems first create a giant table containing the score of every query against every possible token. Most of these scores are thrown away because only the top few are needed.
For a 1-million-token context, this table can use about 32 gigabytes of memory on one GPU in the example studied.
It is like writing down the scores of every student in a huge school even though you only need to know the top 10 students.
Problem 2: Repeating the selection
During training, computers sometimes use a technique called activation recomputation. They delete some temporary information to save memory, then calculate it again later when needed.
In existing systems, this means repeating the expensive selection process. The system finds the same important tokens twice, even though the answer has not changed.
HyTopK
The first main idea is called HyTopK.
Instead of calculating and storing every score, HyTopK checks scores one at a time and keeps only promising candidates. It works like a very fast competition:
- Estimate roughly how high a score must be to reach the top
k. - Ignore scores that are clearly too low.
- Keep likely winners in a small buffer.
- If the estimate was wrong for a query, redo that query carefully.
This avoids creating the giant score table.
HyTopK also makes sure the result is:
- Exact: It still finds the true top
k. - Deterministic: The same input gives exactly the same result every time.
- Compatible with context parallelism: Multiple GPUs can share the work on a long sequence.
Selection replay
The second main idea is called selection replay.
Instead of selecting the important tokens again during recomputation, the system saves their positions from the first pass. Later, it simply reuses those positions and recalculates only the scores it actually needs.
This is like saving the page numbers of important information in a book instead of searching the whole book again.
Other system improvements
HyScale also includes two additional optimizations:
- Decoupled communication: Different GPUs transfer information while other calculations are happening, reducing waiting time.
- Locality-aware sparse kernels: Nearby queries often choose many of the same tokens. HyScale processes nearby queries together so shared information is loaded only once.
A kernel here means a small computer program that runs directly on the GPU.
4. What did the researchers find?
The main result is that HyScale makes long-context training much faster.
Faster GLM-5.1 training
When training GLM-5.1 with 1-million-token sequences on 512 H20 GPUs, HyScale was:
- 2.07 times faster than Megatron-LM.
Its improvement increased with longer contexts:
| Context length | HyScale speedup |
|---|---|
| 256K tokens | 1.23× |
| 512K tokens | 1.44× |
| 1M tokens | 2.07× |
The system achieved this while using about the same amount of GPU memory.
Faster other attention designs
HyScale also worked with systems that select blocks of tokens rather than individual tokens:
- It made the CSA layers of DeepSeek-V4-Flash 2.01× faster.
- It made the QSA layers of Qwen3.8-Flash-Next 1.57× faster.
This suggests that HyScale is not limited to one particular model design.
Selection replay saved a large amount of work
At 1-million-token context length:
- Forward selection time fell from about 35.9 seconds to 20.8 seconds using HyTopK.
- Recomputed selection time fell from about 37.0 seconds to 1.0 second using selection replay.
This is important because repeated selection had been one of the largest parts of the training time.
Better scaling across GPUs
HyScale also continued to improve when more GPUs were added. In one test, at very large context sizes, HyScale became more than 20 times faster than the older system.
The older system eventually stopped getting faster because communication and repeated setup work became too expensive.
Small cost for accuracy and repeatability
HyTopK’s recovery process was rarely needed. When it was needed, it added only a small amount of extra time.
The extra sorting needed to make results deterministic added only about 0.8% to selection time.
5. Why are these results important?
Training an LLM with very long contexts is difficult because the amount of work grows rapidly as the context becomes longer. Even if the model only needs a small number of tokens, older systems still spend a lot of time examining and storing information that will later be discarded.
HyScale improves this by recognizing an important fact:
The system mainly needs the positions of the selected tokens, not every score used to find them.
This simple change allows the system to:
- Avoid storing huge score tables.
- Avoid repeating the same search.
- Use GPU memory more efficiently.
- Reduce communication between GPUs.
- Make better use of shared information between nearby queries.
Conclusion and potential impact
HyScale could make it more practical to train LLMs that understand extremely long documents and tasks. Faster training could reduce the time and cost needed to build these models.
In the future, improvements like this may help AI systems work with:
- Entire books or research collections.
- Large software projects.
- Long legal or medical documents.
- Extended conversations.
- Long-running plans and records from AI agents.
The paper’s broader lesson is that speeding up AI is not always about using more powerful hardware. It can also come from noticing what information is truly necessary and avoiding work that does not affect the final answer.
Practical Applications
Immediate Applications
- Faster training of million-token LLMs — AI infrastructure and cloud computing.
- long-document LLMs;
- codebase-scale models;
- models trained on agent trajectories, logs, or multimodal sequences;
- production models using DSA, CSA, QSA, or related top- sparse-attention mechanisms.
- Dependencies: access to compatible NVIDIA GPU clusters, CUDA-level kernel engineering, context parallelism, and models whose attention selection is top- based and non-differentiable.
- Drop-in optimization for existing distributed training workflows — software engineering.
Because HyScale is implemented on top of Megatron-LM and preserves the surrounding training stack, organizations can use it as an attention-layer replacement rather than redesigning the complete training system. A practical workflow would be:
- replace dense score-table selection with
HyTopK; - enable selection replay during activation recomputation;
- activate decoupled context-parallel communication;
- use locality-aware sparse kernels for forward and backward passes. Dependencies: compatibility with the model’s indexer loss, sparse-attention layout, tensor shapes, and distributed optimizer.
- replace dense score-table selection with
Reduced GPU memory pressure during long-context training — cloud and data-center operations.
- larger batch sizes;
- longer sequences on the same GPUs;
- fewer query chunks and fewer kernel launches;
- reduced need for expensive high-memory accelerators.
- The paper reports that the full score table can require 32 GiB per GPU for a representative 1M-token configuration, whereas selected indices require roughly 64 MiB.
- Dependencies: host-to-device transfer must be effectively overlapped with computation; poor overlap or slow CPU memory could reduce the benefit.
- More scalable context parallelism — distributed systems and HPC.
- scaling training across larger GPU counts;
- reducing exposed collective-communication time;
- training sequences beyond 1M tokens;
- improving utilization in multi-node GPU clusters.
- The paper reports substantially better scaling than the baseline, including up to 22.3× speedup at 8M context in a layer-level weak-scaling experiment.
- Dependencies: adequate interconnect bandwidth and enough local query work to hide communication; benefits decline when each GPU handles too few queries.
- Acceleration of block-level learned sparse attention — model architecture and compiler tooling.
- compressed sparse attention;
- mean-pooled block attention;
- token-group or hierarchical retrieval attention;
- other exact top- block-selection mechanisms.
- The paper reports 2.01× acceleration for CSA and 1.57× for QSA at 1M-token context.
- Dependencies: the architecture must expose selected block indices and require gradients only through selected scores or values. Gains may be smaller when the number of candidate blocks is already low.
- Reproducible and debuggable sparse-attention training — academia and industrial ML operations.
- bitwise-reproducible experiments;
- reliable checkpoint comparison;
- debugging of loss spikes and hardware faults;
- regression testing for custom GPU kernels;
- reproducible ablation studies.
- This is particularly valuable in large distributed runs where nondeterministic selection can make failures difficult to reproduce.
- Dependencies: reproducibility still depends on deterministic behavior in the remainder of the training stack, including collective operations, reductions, data ordering, and optimizer kernels.
- Open-source GPU-kernel and compiler components — academia and software tooling.
- memory-efficient exact top- operators;
- sparse-attention autograd primitives;
- context-parallel communication schedulers;
- profiling tools for selection locality and candidate-buffer failures.
- Dependencies: portability beyond the evaluated NVIDIA H20/H800 platforms must be validated; kernel performance may vary substantially across GPU generations.
- Training of long-context models for document and code workflows — enterprise AI.
- legal or regulatory archives;
- scientific papers and technical manuals;
- software repositories;
- enterprise knowledge bases;
- multi-step tool-use and agent traces.
- The practical benefit is faster iteration on models that must learn dependencies across hundreds of thousands or millions of tokens.
- Dependencies: sparse attention must preserve task quality. The reported results primarily establish systems efficiency, not universal equivalence in downstream accuracy.
- Lower training cost and energy consumption — data-center sustainability. If a training run completes in roughly half the time without requiring proportionally more hardware, HyScale can reduce GPU-hours, cooling demand, and electricity consumption. It can also allow operators to use existing clusters for longer-context experiments that would otherwise be infeasible. Dependencies: actual energy savings depend on cluster utilization, communication overhead, GPU power behavior, and whether the saved time is used to run larger experiments.
Long-Term Applications
- Training models with multi-million- or billion-token contexts — advanced AI systems.
HyScale’s improvements could support models operating over entire repositories, book collections, long-lived agent histories, or continuously accumulated interaction logs. Selection replay reduces recomputation from a context-dependent cost toward a selected- cost, while
HyTopKavoids score-table growth. Potential products and workflows: repository-wide coding assistants, persistent personal agents, automated legal discovery, full scientific-literature reasoning, and enterprise memory systems. Dependencies: communication and storage costs will eventually dominate; the method must be validated at larger contexts, larger GPU counts, and different parallelism strategies. Model quality may also degrade if sparse selection misses information needed for rare long-range dependencies. - Unified training and inference runtimes for learned sparse attention — AI systems software.
- exact top- kernels;
- deterministic selection policies;
- block and token selection abstractions;
- memory-management and KV-gathering infrastructure;
- adaptive thresholds for both training and serving.
- This could produce end-to-end systems in which a model is trained and deployed using consistent sparse-attention semantics.
- Dependencies: training and inference have different latency, batching, determinism, and fault-tolerance requirements. The optimistic-threshold and recovery strategy would need dedicated serving benchmarks.
- Adaptive computation and dynamic context budgeting — model design. HyScale could facilitate models that dynamically vary by query, layer, token type, or uncertainty. For example, routine tokens could use small selections, while ambiguous queries or retrieval-heavy layers could receive larger budgets. Potential tools: per-query candidate budgets, confidence-aware attention, learned latency controllers, and hardware-aware sparse-attention schedulers. Dependencies: the current design assumes a fixed or structured top- selection. Variable- selection complicates buffer sizing, deterministic replay, load balancing, and gradient computation.
- Sparse attention for multimodal and structured sequences — robotics, healthcare, and scientific computing.
- long-horizon robot trajectories;
- medical records combining notes, imaging tokens, and lab results;
- genomic or molecular sequences;
- industrial sensor histories;
- multimodal video-LLMs.
- Dependencies: the selection-locality assumption may not hold across modalities or irregular event streams. New kernels may be required for variable-size entries, spatial layouts, and heterogeneous memory formats.
- Learned sparse attention in real-time robotics and edge systems — robotics and embedded AI.
- onboard planning over long histories;
- warehouse and autonomous-vehicle control;
- robot fleet coordination;
- wearable or edge-based assistants.
- Dependencies: the paper demonstrates training acceleration rather than real-time inference. Edge deployment requires low-latency kernels, smaller memory footprints, predictable worst-case recovery costs, and hardware support outside large NVIDIA GPUs.
- Automatic architecture search for sparse-attention models — academia and ML platforms.
- token-level versus block-level selection;
- different values;
- indexer dimensions and head counts;
- query grouping strategies;
- layer-specific sparsity patterns.
- An automated system could jointly optimize model quality, training cost, memory use, and hardware efficiency.
- Dependencies: faster training does not by itself establish that a selected sparsity pattern preserves accuracy. Architecture search would require robust quality benchmarks and cost-aware objectives.
- Hardware co-design for learned sparse attention — semiconductors and accelerators.
- accelerator support for fused score-and-top- operations;
- on-chip candidate buffers;
- hardware primitives for deterministic segmented selection;
- cache designs optimized for shared sparse entries;
- interconnect protocols tailored to decoupled selection and KV transfers.
- Dependencies: hardware gains depend on the stability of selection locality across models and workloads. Architectures with low locality or highly irregular access patterns may not benefit from paired-query kernels.
- Policy and infrastructure planning for long-context AI — public-sector and institutional policy.
- energy and carbon costs of long-context models;
- infrastructure requirements for public research models;
- reproducibility standards for large-scale training;
- cost and access implications of million-token AI systems.
- Dependencies: efficiency claims should be reported with full-system metrics, including GPU type, cluster networking, energy consumption, model quality, and total training time—not only kernel or layer speedups.
- Efficient continual learning over persistent histories — personal assistants and enterprise software. Future systems could train or periodically adapt models using long histories of interactions, documents, and tool outcomes without repeatedly paying the full cost of dense attention. Selection replay is particularly relevant when repeated forward computations occur during memory-efficient training. Dependencies: privacy, retention, and data-governance constraints are substantial. In addition, persistent histories may contain distribution shifts that reduce the locality assumptions and stability of learned selection.
- Formal verification and reliability analysis of sparse selection — academia and safety-critical AI.
- verified sparse-attention kernels;
- certification of reproducibility;
- numerical-error analysis;
- safety testing for healthcare, finance, and autonomous systems.
- Dependencies: exactness of index selection does not guarantee identical model outputs under all floating-point execution orders or distributed reductions. Broader verification must cover the entire attention and training pipeline.
Glossary
- Activation recomputation: A memory-saving technique that discards intermediate activations and recalculates them during backpropagation. “At long context that storage can exceed GPU memory, so training often uses activation recomputation”
- All-gather: A collective communication operation in which every GPU obtains data from all other GPUs. “Before selection, the forward pass synchronously all-gathers the indexer keys”
- Atomic operation: A hardware-supported operation that completes indivisibly, commonly used to safely update shared memory. “Their scoring kernel appends the passing keys to each query’s buffer with atomic operations”
- Backward pass: The phase of neural-network training that computes gradients using the chain rule. “The backward pass requires neither the intermediate score table nor a re-run of top-k search.”
- BF16: Brain floating-point 16-bit arithmetic, a reduced-precision format used to accelerate deep-learning computation. “All runs use BF16, zigzag all-gather CP, and full activation recomputation unless noted otherwise.”
- Candidate buffer: A temporary fixed-capacity memory region holding items that may belong to a final selected set. “writes only the keys that pass to a small candidate buffer per query”
- Context parallelism (CP): A distributed-training strategy that partitions a long sequence across multiple GPUs. “context parallelism (CP) splits a sequence of length L across a group of P GPUs”
- Continuous activation: A differentiable numerical intermediate produced by a neural-network operation. “the output of selection is not a continuous activation, but rather a discrete set of indices.”
- CUDA: NVIDIA’s platform and programming model for executing general-purpose computations on GPUs. “HyScale is implemented on top of Megatron-LM with about 3.4K lines of Python and 14.7K lines of GPU kernels (CUDA, Triton, CuTe DSL).”
- CuTe DSL: A domain-specific language for expressing high-performance CUDA tensor operations. “14.7K lines of GPU kernels (CUDA, Triton, CuTe DSL).”
- cuDNN: NVIDIA’s optimized library of primitives for deep neural-network computation. “Megatron Core 0.19.2 with the cuDNN DSA backend.”
- Decoupled CP overlap: A scheduling technique that overlaps separate context-parallel communication operations with computations that do not depend on the transferred data. “Decoupled CP overlap builds on the fact that selection and sparse attention consume different CP data”
- Detached tensor: A tensor treated as constant for gradient computation, preventing derivatives from propagating through it. “Both pt and the indexer’s inputs are detached”
- Deterministic selection: A selection procedure that produces exactly the same result for identical inputs across executions. “HyTopK keeps the fast atomic writes in its kernels and restores determinism afterwards.”
- Distributed optimizer: An optimizer implementation that partitions optimizer state or computation across multiple GPUs. “Both systems force balanced MoE routing and use momentum-free SGD with Megatron-LM’s distributed optimizer.”
- Forward pass: The phase of neural-network execution that computes outputs from inputs before gradient calculation. “The forward pass scores all L keys and selects the top-k as in §3.2”
- FLOP: A floating-point arithmetic operation, used as a unit for estimating computational work. “Recomputation (FLOP)”
- Gradient: A derivative that indicates how a model parameter should change to reduce a loss. “The backward pass reduce-scatters their gradients.”
- Host synchronization: Coordination between CPU-side execution and GPU-side execution that can pause asynchronous computation. “The first two techniques remove host synchronizations.”
- Index replay: A recomputation strategy that stores selected indices and rescoring only the entries they identify. “Index replay keeps only the k indices of each query and rescores only the k entries they point to.”
- Indexer: A learned component that scores candidate tokens or blocks for sparse attention. “For each query, it scores every previous token whereas sparse attention reads only k”
- Indexer loss: A training loss that updates the learned indexer using the scores of selected entries. “the indexer loss differentiates through only the k selected scores.”
- Kernel fusion: Combining multiple GPU operations into a single kernel to reduce launch overhead and memory traffic. “HyScale fuses chains of elementwise operators, such as the indexer’s KL loss, normalizations, and RoPE.”
- L2 cache: A second-level cache on a GPU that stores recently accessed data to reduce memory-access latency. “the L2 cache runs at 53–65% of its peak throughput”
- Latency: The delay between initiating an operation and obtaining its result. “The faster attention layers also halve the pipeline wait”
- Learned sparse attention: An attention mechanism that uses a learned selector to restrict each query to a small subset of tokens or blocks. “Learned sparse attention lets each query attend to a few entries chosen by a learned indexer.”
- Lightning indexer: A lightweight learned indexer used to score candidate tokens efficiently. “DSA (DeepSeek-AI et al., 2025) takes single tokens as entries and scores them with a lightning indexer”
- Locality-aware sparse kernel: A GPU kernel that exploits the tendency of neighboring queries to access overlapping entries. “We propose locality-aware sparse kernels.”
- Matrix multiplication: An operation that multiplies two matrices and is highly optimized on GPUs. “score it in one matrix multiplication.”
- Memory traffic: The movement of data between different levels of a computer’s memory hierarchy. “a cost that grows with the context.”
- Multi-head latent attention (MLA): An attention architecture in which multiple attention heads share a compressed key-value representation. “Its sparse attention uses multi-head latent attention (MLA)”
- Non-differentiable: Not possessing a usable derivative for gradient-based optimization. “top-k selection is non-differentiable”
- Optimistic threshold: A threshold estimate that may be higher than the true safe lower bound but is efficient and recoverable when incorrect. “HyTopK via an on-the-fly top-k selection operator via optimistic thresholding.”
- Pipeline parallelism (PP): A distributed-training method that assigns different layers or stages of a model to different GPUs. “PP8×CP32×DP2 at 256K”
- Pinned host memory: CPU memory allocated so that GPU transfers can occur efficiently and asynchronously. “the kept indices can be offloaded to pinned host memory with nearly zero overhead.”
- Radix select: A selection algorithm based on processing digits or bits of keys to identify order statistics. “the select kernel runs a radix select”
- Radix sort: A non-comparison sorting algorithm that orders values by processing their digits or bits. “a radix sort (Merrill & Grimshaw, 2011) orders the k entries”
- Reduce-scatter: A collective operation that combines values across GPUs and distributes portions of the result among them. “The backward pass reduce-scatters their gradients.”
- ReLU: The rectified linear unit activation function, defined as . “Score(qI t , kI u) = HI Xh=1 wt,h ReLU”
- RoPE: Rotary positional embedding, a method that encodes token positions by rotating query and key representations. “Megatron-LM’s RoPE synchronizes with the host in every call”
- Sparse kernel: A GPU kernel optimized for computation involving mostly omitted or irregularly accessed data. “learned sparse attention adds three sparse kernels to training”
- Strided sampling: Sampling elements at regular intervals across a larger ordered collection. “HyTopK gives up the guarantee and estimates each query’s threshold from a strided sample of its own context”
- Tensor core: Specialized GPU hardware for accelerated matrix and tensor operations. “the tensor cores stay underused.”
- Threshold underestimation: Choosing a filtering threshold that is too low, causing too many candidates to be retained. “threshold underestimation overflows fixed buffers”
- Top-k selection: The operation of retaining the highest-scoring items from a set. “Selection scores every entry and keeps the k highest”
- Token-level attention: Sparse attention that selects individual tokens rather than contiguous token blocks. “Beyond token-level DSA, HyScale generalizes seamlessly to block-level architectures”
- Triton: A programming language and compiler framework for writing efficient GPU kernels. “14.7K lines of GPU kernels (CUDA, Triton, CuTe DSL).”
- Warp: A group of GPU threads that execute instructions together in a SIMD-like manner. “warps stall on memory in 40–44% of their cycles”
- Weak scaling: A scalability analysis that increases the problem size proportionally with the number of processors. “Second, weak scaling fixes the queries per GPU and grows the context with the GPUs.”