Making Long-Context Training Practical
Preparing DeepSeek V4 for 1M context: rethink attention scores, communication, loss computation, graph lifetimes, and even integer indexing.
Note: I finished drafting most of this post about two months ago. The training framework discussed here has not been open-sourced yet, so this version omits its name and links to its repository and pull requests. I will restore them once it is public.
The training framework we have been working on is a lightweight, PyTorch-native stack for distributed training: you write the model, choose how to divide it across data, tensor, pipeline, and context parallelism, and the framework connects the pieces. For us, keeping the model easy to understand and modify matters. We are changing architectures as well as trying to train them efficiently.
Recently, much of my work has been about long context. I integrated FlashAttention-3, implemented generic Ring Attention, added length-aware packing, and rewrote the DeepSeek V4 context-parallel path. Along the way, I also changed how we compute the LM head and cross entropy, and how auxiliary-loss graphs are connected to the rest of training.
For DeepSeek V4, the goal behind these changes is to be ready for 1M context. That is a useful target to keep in mind even while working at shorter lengths. A temporary allocation that is inconvenient at 64K can become impossible at 1M. A small inefficiency repeated across every token and every layer can consume most of the memory we just worked hard to save.
The more I worked on this, the more the same questions kept coming up: why do we need the whole sequence here? Why do we produce this tensor only to immediately reduce it? Why is this loss still holding onto its graph? These are fairly ordinary implementation decisions. Long context makes their consequences much harder to ignore.
Integrating FlashAttention-3
Attention is an obvious place to start. For dense attention, doubling the sequence length roughly quadruples the work. FlashAttention avoids storing the full query-key score matrix by computing attention in tiles and keeping the statistics needed to combine them. FA3 makes better use of Hopper’s ability to overlap data movement, matrix multiplication, and softmax. Tri Dao’s explanation ↗ goes into the kernel design.
My part was integrating FA3 into our framework’s variable-length attention path. A packed sample can contain several documents, and varlen attention lets the kernel work on their individual lengths instead of treating the whole pack as one document. That both saves work and preserves document isolation.
I put FA3 behind the shared attention.varlen interface. The model describes the attention it wants to compute; the backend supplies the implementation. This also gives distributed attention a useful building block: once we know how to compute one block correctly, we can decide how to move those blocks between GPUs.
Why we needed Ring Attention
The practical reason I needed Ring Attention came from our first 30B-A3B training run. We were using Ulysses for context parallelism, and had reached CP4. Ulysses redistributes attention heads across GPUs, so the head count constrains how far that split can go. The Qwen3-30B-A3B configuration ↗ has 32 query heads but only four KV heads. Those four KV heads were the limit for our Ulysses path. At Ulysses4, each rank already had just one KV head; there were no more KV heads to distribute.
That became a constraint on the whole training layout because we kept the global batch at 32M tokens per optimizer step. Data parallelism assigns different samples to different replicas, while context parallelism lets several GPUs work on the same sample. In the DP × CP layout, with TP and PP both set to one, 512 GPUs at CP4 give us data-parallel replicas.
At 256K sequence length, a 32M-token step contains only 128 packed sequences. Giving each DP replica one pack already consumes the entire batch budget:
There is no smaller microbatch left to choose: each replica is already processing one sequence, with one gradient-accumulation step. Increasing accumulation would add more tokens. At 256K, the 128 sequences in a step can therefore occupy at most GPUs in this layout. Keeping 512 GPUs and increasing context to 512K would instead require at least 64M tokens per step; at 1M, it would require 128M. Both would change the batch size we intended to train with.
This is why the CP4 ceiling mattered even beyond the memory needed by attention. Without introducing pipeline parallelism, we needed more GPUs to cooperate on each sequence. Ring gives us another way to increase CP: divide the token sequence into more blocks, without needing more KV heads.
For example, the following layouts all use 512 GPUs and fit the same 32M-token step budget, with one packed sequence per DP replica:
| Sequence length | Total CP degree | DP replicas | Tokens per optimizer step |
|---|---|---|---|
| 256K | 4 | 128 | 32M |
| 512K | 8 | 64 | 32M |
| 1M | 16 | 32 | 32M |
As a sequence gets longer, the batch contains fewer sequences. Increasing CP lets those fewer sequences still use all 512 GPUs. It removes the head-count limit from this part of the scaling problem; we still have to make the attention computation and its memory usage work at the chosen length.
The most direct way to give local queries access to remote history would be to gather all keys and values. It is straightforward, but every rank ends up holding a global KV representation again. Ring Attention ↗ processes that history block by block. Each rank keeps its queries while KV blocks circulate through the group. It computes against the current block, merges the contribution into its output, and continues with the next one. The next block can be transferred while the GPU is working on the current block. Each block still carries the KV heads needed by that Ring group; it is the token range that changes from one block to the next.
If Ring or Ulysses is new to you, the appendix follows a small sequence through both layouts.
The merge is the important mathematical detail. We cannot average two block outputs, because each block’s softmax used a different denominator. For one query, let the two outputs be and their log-sum-exp values be . Then
This restores the relative probability mass of the two blocks. Repeating it gives attention over their combined keys, without materializing the full score matrix. The local attention kernel therefore needs to return its normalization statistics as well as its output.
Causal attention creates another problem: later queries have more history to read. Giving each rank the same number of consecutive tokens does not give it the same amount of work. The generic Ring path uses a zigzag layout, pairing an early block with a late block:
The two halves compensate for each other. With packed data, we also have to carry document identity and position through this layout: a physical block boundary is not necessarily a document boundary, and being on an earlier rank does not make a key visible across documents.
Backward needs the corresponding communication too. A key can contribute to queries on several ranks, so those gradient contributions must be combined and returned to its owner. The Ring implementation connects received KV blocks to their owners and uses a reduce-scatter for the accumulated gradients.
I also made Ring composable with Ulysses. For the four-KV-head model, Ulysses4 combined with Ring4 gives a total CP degree of 16: Ulysses partitions the heads, and Ring divides the sequence further within each head partition. The local attention computation is shared across these layouts. That makes the implementation reusable as we change the model or parallelism configuration, while leaving room for DeepSeek V4 to exploit its own compressed attention structure.
Packing similar lengths, without making every batch too similar
For a more formal account of this work, see §7.1 of our technical report ↗, which I wrote.
After distributing attention, we still have to distribute the data sensibly. Two packed samples can have identical shapes and very different costs.
Take two 256K-token packs. One contains a single 256K-token document. The other contains 32 documents of 8K tokens each. With document-isolated dense attention, their costs are approximately
The first has about 32 times as much attention work. Both packs keep the GPU busy processing the same number of tokens, but one spends much more time on attention. With varlen attention, we actually skip the cross-document work, so this difference shows up in execution time.
The length-aware dataloader uses the document segments inside each pack to estimate that cost:
It groups packs with similar estimated costs into the same global microbatch, then distributes them across DP ranks. When a rank receives several packs, we assign the most expensive ones first, each time choosing the rank with the lowest accumulated cost that still has room. When microbatch size is one, grouping comparable packs into the same step is already most of the benefit.
There are two practical choices here that turned out to matter more than the sorting algorithm itself.
The first is how far ahead to look. Real corpora contain hundreds of billions or trillions of tokens. Loading tokenized samples into memory and sorting the whole dataset is obviously not going to work. We need a bounded set of candidates: read some samples, compare their lengths or costs, take a batch of reasonably close ones, and replenish the buffer.
In my initial buffering design, I used data.length_aware_num_buckets for that limit, starting with 128 candidate samples. A larger candidate pool gives the scheduler more choice, but it also holds more data in memory. In the real-corpus experiments I was discussing, roughly 2 * world_size candidates already gave a useful balance. There was little reason to keep looking arbitrarily far ahead just to make the lengths match more closely.
The second choice is how much of the training order we allow the scheduler to rearrange. My first attempt set the length-aware window to 128. That was too large.
At first, a bigger sorting window looks attractive: more candidates, closer lengths, less waiting between ranks. But length is not independent of the data itself. Different sources have different length distributions. If we group lengths too aggressively, a step can end up containing very similar examples from similar sources. The dataset may still contain the same samples overall, but the mixture seen by each optimizer step has changed.
In those long-context runs, longer sequences tended to have both lower TGS (tokens per GPU per second) and higher loss.
When a large window groups long samples together, it also groups many of those higher-loss examples into the same steps. Shorter, lower-loss batches appear elsewhere. The loss curve becomes much more uneven, even though the dataloader is doing an excellent job of matching costs within each step. Shuffling the order of the batches does not undo the fact that each batch has already been made more homogeneous.
That changed what I wanted from the scheduler. The aim is to remove severe stragglers while retaining a useful mixture of data. A small lookahead gives us room to balance a batch without arranging a large part of the run by length—and, indirectly, by source and difficulty. The candidate-buffer limit and the sorting window address different costs, so neither is a setting I want to maximize by default.
The interesting part of this optimization is the compromise between GPU utilization, memory, and the batches the model actually learns from. Matching lengths more closely is useful only while that compromise still makes sense.
Rethinking DeepSeek V4 for 1M context
The generic Ring path is useful for dense attention, but DeepSeek V4 gives us more structure to exploit. Its attention schedule combines a raw sliding window with compressed history: ratio-4 compressed sparse attention (CSA), with a learned indexer choosing keys, and ratio-128 compressed attention (HCA). Our N266 implementation shares this path. The V4 appendix explains how the window, compressor, and indexer fit together.
For the 1M target, I wanted to follow each tensor through the layer and ask which part of that history it really needed. We already had context parallelism, but some of the work inside the layer was still global.
The previous implementation kept queries local, then gathered the full uncompressed KV sequence. For packed compressed attention, it also gathered the full hidden-state sequence before running the compressor. In simplified form:
global_raw_kv = all_gather(local_raw_kv)
global_hidden = all_gather(local_hidden)
compressed_kv = compressor(global_hidden, document_plan)
output = attention(local_queries, global_raw_kv, compressed_kv)pythonThis makes boundary handling convenient. A document or compression group can cross ranks, but all the input is present before we process it. The cost is that every rank reconstructs the global tensors we split the sequence to avoid storing.
For example, at 1M context with CP16, each rank owns 64K tokens. At hidden width 4,096, its BF16 hidden-state shard occupies 512 MiB. Gathering the full sequence turns that into an 8 GiB tensor on every rank—16 times the local shard. Adding more CP ranks keeps shrinking the shard while leaving the global allocation the same size. Running the packed compressor on that gathered input also duplicates work across ranks.
The refactor starts from the actual dependencies. Sliding-window attention needs local KV plus a short prefix from the preceding shard. We exchange that boundary region—a halo—instead of gathering the complete raw sequence. With local length and window width , the raw-KV working set is roughly proportional to .
The compressor also gets an explicit ownership plan. A rank computes the completed compressed groups it owns, receiving the small raw-token halo needed for groups that cross its boundary. Ratio-4 compression has overlap, so that overlap is part of the plan too. Once the local compressed entries exist, we share the compressed representation rather than the full hidden-state sequence.
Document boundaries make this more than a matter of exchanging the last few tokens. A document can start near the end of one shard and continue into the next. Its compression groups must follow the document, and a query may only see causally available groups from that same document. Global token position, document-relative RoPE position, local tensor index, and compressed-key index are different coordinates. The CP layout needs to keep them connected.
This is why I ended up substantially rewriting the path rather than swapping one collective for another. Attention, compression, indexing, and the metadata passed between pipeline stages all depend on that layout. Making those dependencies explicit lets us keep raw data local and communicate the smaller representations the model actually needs.
Choosing CP strategies for V4 Flash: doing the math
Once raw hidden states and boundary tokens are handled locally, a more interesting design question shows up. DeepSeek V4 Flash combines three attention mechanisms: SWA (a 128-token sliding window over raw KV), HCA (stride 128), and CSA (stride 4, with a learned indexer selecting top-512 entries per query). We need a context-parallel strategy for each of them—and inside CSA, separate decisions for the indexer and the main sparse attention.
At first glance, several intuitions sound reasonable:
- HCA uses global KV—can that still work at 1M, or should we use Ring to avoid holding global KV?
- The CSA indexer looks like standard single-head (head-reduced) attention—can we run it as a Ring?
- CSA main attention reads a fixed number of compressed KV entries (
topk = 512) per query—whyall_gathereverything whenall_to_allcould fetch only what was selected? - We shard Q and keep global KV; under HCA, so that seems safe, but at CSA
ratio = 4, could keeping global KV OOM?
Rather than relying on intuition, we can settle each choice by doing the arithmetic on two concrete dimensions: memory footprint (both resident tensors and transient peak allocations) and communication volume (forward and backward).
In the calculations below, we use 1M context ( tokens), BF16, 512-d shared KV entries, and 128-d indexer keys, and evaluate concrete numbers at CP8 (). To be clear up front, 1M at CP8 does not actually fit end-to-end—our production layout for 1M is CP32 (). We keep CP8 here as an easy reference point and check CP32 alongside it; none of the conclusions change.
SWA raw KV: halo instead of a 1 GiB all-gather
The sliding window is where raw (vanilla) KV crosses CP rank boundaries, because a 128-token window near the start of a shard reaches into the tail of the previous rank. The earlier implementation handled this by gathering the entire raw KV sequence:
kv_vanilla_global = all_gather_cp(kv_vanilla, dim=1, cp_ctx=cp_ctx)
kv = kv_vanilla_globalpythonAt 1M context, a single 512-d BF16 raw KV tensor occupies
per layer. (Looking at miles’s codebase recently, its implementation still does this global all_gather for raw KV.) Replacing that gather with a 127-token boundary halo brings the exchanged prefix down to —roughly four orders of magnitude smaller. Here, avoiding global KV is clearly worth it.
HCA compressed KV: local Q + global KV, no need for Ring
Now check HCA. At 1M context with compression ratio 128, there are HCA entries across the entire sequence. Each entry is 512-d in BF16, so the global HCA compressed KV tensor is only
Rewriting HCA into Ring Attention just to save 8 MiB would introduce online softmax (LSE merging) and a much more complicated backward pass. That trade is not even close to worth it: keeping Q local and using all_gather for global HCA KV is the right design.
CSA indexer: all-gather K + local Q-chunking beats Ring top-k
At 1M context with compression ratio 4, there are (256K) compressed entries. The indexer’s job is to find the global top-512 entries for each local query.
Materializing the full score matrix is completely out of the question: at 1M / CP8 (), [131072, 262144] in FP32 would take 128 GiB. Even in our production CP32 layout (), the full FP32 score matrix is still 32 GiB—far too large to allocate.
That leaves two natural candidates: circulating K blocks around a ring while maintaining a running top-512, or gathering global indexer K once and chunking along Q locally. Look at the size of the global indexer keys first. Indexer keys are 128-d in BF16, so the entire global K tensor is only
At CP8, each rank receives (at CP32, 62 MiB). Also note the common cost that any strategy pays: the output topk_idxs has shape [131072, 512] in int32, or 256 MiB per layer at CP8 (64 MiB at CP32). That is the indexer’s output, not ring state; every scheme must store it and retain it for attention backward (across 20 C4 layers, that is 5 GiB at CP8, or 1.25 GiB at CP32).
Now compare peak memory for the two schemes at 1M / CP8:
Option 1: Ring Top-K. An 8-step loop rotates K blocks of width , scores each block, and merges it into a running top-512:
| Step / item | Tensor | Size |
|---|---|---|
| Score current K block (per-step transient) | [131072, 32768] FP32 | 16 GiB |
| Per-block top-k | [131072, 512] FP32 + int32 | 512 MiB |
Merge (concat → [131072, 1024], then top-k) | transient | ~1–1.5 GiB |
| Running top-k state (resident) | [131072, 512] FP32 + int32 | 512 MiB |
| Current K block | [32768, 128] BF16 | 8 MiB |
| Peak | ≈ 18 GiB |
Ring Top-K has a structural flaw: its transient score buffer is locked to the CP topology. Each step has block width and row count , so the transient scales as —quadratically with context length. At 4M / CP8, that transient jumps to 256 GiB, which is completely infeasible. The only way to fix it is to also chunk along Q inside each ring step—at which point it degenerates into Option 2 while adding seven ring hops and merge overhead for nothing.
Option 2: All-Gather K + local Q-chunking. Keep the 64 MiB global K resident and chunk local queries with q_chunk = 1024:
| Item | Tensor | Size |
|---|---|---|
| Score transient | [1024, 262144] FP32 | 1 GiB |
| Running state / merge | none (each query sees all keys at once; single top-k writes directly to output) | 0 |
| Resident global K | [262144, 128] BF16 | 64 MiB |
Output topk_idxs | [131072, 512] int32 | 256 MiB |
| Peak | ≈ 1.3 GiB |
Rereading K across chunks moves from HBM—just a few milliseconds at modern HBM bandwidth, completely negligible.
The core lesson is simple: the temporary score allocation dwarfs the resident K tensor by orders of magnitude (GiB vs. 64 MiB). Using Ring here saves 64 MiB of K while creating an 18 GiB peak tied to CP topology. Gathering K once and chunking Q locally wins decisively—and the same conclusion holds at CP32, where global K is still only 64 MiB while an unchunked score matrix is still 32 GiB.
CSA main compressed KV: all_gather vs. all_to_all_fetch vs. sparse_ring
Once the indexer has produced canonical topk_idxs ([131072, 512] int32 = 256 MiB at CP8), main CSA attention needs to read the selected C4 compressed KV entries. Each rank locally holds [32768, 512] BF16 = 32 MiB (padded/aligned).
First check memory: pulling the entire global C4 compressed KV locally takes only
That resident footprint is small—nowhere near OOM. So here, communication volume is what separates the three backends we considered under csa_kv_backend:
all_gather: a variable-lengthall_gatherbrings the full compressed KV onto each rank (256 MiB resident; 224 MiB received at CP8). Indices are offset and concatenated with the sliding-window indices for a single sparse attention call. Backward runs onereduce_scatter(224 MiB).all_to_all_fetch:bucketizelocates the owner rank of each selected group, runs all-to-all (counts → 8 B/request metadata → 1 KiB/entry KV payload), and packs the fetched entries per query into a private[S_local * 512, 512]KV tensor. Requests are sent per(query, slot)without deduplication.sparse_ring: compressed KV blocks circulate along a ring (with prefetch); each owner’s block runs through a TileLang kernel that directly emits(out, lse), and blocks are merged via LSE.
Comparing the three at 1M, CP8, BF16 (per layer, per rank):
| Dimension | all_gather | all_to_all_fetch | sparse_ring |
|---|---|---|---|
| Forward communication | 224 MiB | ~64 GiB (67M entries × 1 KiB, + 8 B req) | 224 MiB (7 hops × 32 MiB) |
| Backward communication | 224 MiB (reduce_scatter) | ~64 GiB (symmetric round) | 224 MiB (reduce_scatter) |
| Resident compressed KV | 256 MiB | Up to 64 GiB packed [S_local·512, 512] | 32–64 MiB (1–2 blocks) |
all_to_all_fetch explodes because its payload scales as , amplified by topk = 512:
| Setup | Requests / rank / layer | Forward bytes / rank / layer |
|---|---|---|
| 1M, CP8 | ~64 GiB | |
| 1M, CP32 | ~16 GiB |
Even at CP32, ~16 GiB per layer in each direction is roughly two orders of magnitude worse than all_gather’s 248 MiB ().
A natural follow-up is: why not deduplicate all_to_all_fetch? If multiple local queries select the same compressed group, only transfer it once. Look at the numbers, though. There are 256K compressed groups globally, and each query picks 512 of them. Any individual query is very sparse (), but a single rank owns tens of thousands of local queries (131K at CP8, 32K at CP32)—making 67M or 16.8M picks in total. On real long-context sequences, it is unlikely that tens of thousands of queries all concentrate on a tiny subset of blocks; far more likely, most causally eligible blocks are hit by at least one local query on that rank. Deduplicated all_to_all_fetch then degenerates right back toward pulling almost the entire global compressed KV, matching all_gather’s communication volume while paying extra deduplication, bucketization, and dynamic all-to-all overhead.
And between all_gather and sparse_ring, both move the exact same 224 MiB forward and 224 MiB backward at CP8 (248 MiB at CP32). sparse_ring only saves ~200 MiB of resident KV while adding multi-hop prefetch orchestration, multiple kernel launches, and LSE merging. With global compressed KV sitting at just 256 MiB, all_gather plus one sparse attention call is the clean winner.
Putting all four pieces side by side at 1M context (BF16):
| Component | Global size at 1M | Chosen CP strategy | Deciding factor |
|---|---|---|---|
| SWA raw KV (512-d) | 1 GiB | Boundary halo (127 tokens ≈ 127 KiB) | Avoids 1 GiB global KV per layer |
| HCA C128 KV (512-d) | 8 MiB | all_gather (local Q + global KV) | Too small to justify Ring + online softmax |
| CSA indexer K (128-d) | 64 MiB | all_gather + local Q-chunking | Transient score tensor dominates K; Ring locks transient to CP topology |
| CSA main C4 KV (512-d) | 256 MiB | all_gather | Small resident KV; all_to_all_fetch is amplified by topk (and dedup degenerates to all_gather); sparse_ring moves the same bytes with more complexity |
Getting KV communication under control is only the beginning, though. The next problems appear when those queries and keys are turned into scores—especially with the head dimension included—and when the results are kept for training.
Long context brings effects that short runs never exposed
At a fixed parallelism degree, going from 256K to 1M multiplies a linear allocation by four and a quadratic allocation by sixteen. Even increasing CP to keep the local token count fixed does not freeze every dimension: global compressed history continues to grow. That is why I cannot look at a long-context implementation and stop at “it is compressed” or “it is sparse.” I need to know what it allocates, what it retains, and how it addresses that memory.
Compressed attention can still produce enormous score tensors
CSA is a good example. Compressing four tokens into one key reduces the key count by four. It does not make a score tensor small if we still multiply a large number of query rows by all the compressed keys, and perhaps by all the attention heads too.
In our CP2 setup, a 64K sequence gives each rank 32K local tokens. C4 compression produces 8K compressed KV entries on that rank, or 16K across the CP group. To see what happens as context grows, let’s keep 32K local tokens per rank by increasing CP, hold the query block at 8K rows, and increase the amount of compressed history it scores against.
Let be the query rows being scored and the available compressed keys. The indexer reduces its heads into one candidate score per pair, so its output has shape . A headwise score tensor before reduction has shape . Their FP32 sizes are
Using one 8K-query block, batch size one, and 64 heads, the allocation sizes would be as follows. Keeping 32K local tokens per rank means using CP2, CP8, and CP32 respectively:
| Global context | CP degree | Local tokens per rank | Query rows in this block | Global C4 keys | FP32 indexer scores | FP32 headwise scores |
|---|---|---|---|---|---|---|
| 64K | 2 | 32K | 8K | 16K | 512 MiB | 32 GiB |
| 256K | 8 | 32K | 8K | 64K | 2 GiB | 128 GiB |
| 1M | 32 | 32K | 8K | 256K | 8 GiB | 512 GiB |
Here K means 1,024 and 1M means 1,048,576 tokens. The table counts a dense rectangular score allocation against the full compressed-key axis. Causal and document ranges can narrow the actual work. The fused kernels avoid materializing the headwise tensor, which is exactly why the distinction matters.
Even after limiting the query side to 8K rows, the full FP32 headwise scores at 1M would require
And that is just one block. At 1M with CP32, materializing FP32 indexer scores for all 32K local token queries against all 256K compressed keys would occupy 32 GiB. If we also materialized a separate score for each of 64 heads, that dense tensor would occupy 2 TiB. These are the intermediates we want to avoid creating. In this example, CP grows with context to keep the local query count fixed, so the per-rank score allocation grows linearly with global context. Keeping local sequences short does not keep their compressed history short.
The same problem can hide inside an innocent-looking reference expression. A headwise einsum followed by a reduction first creates the large tensor, then gets rid of a dimension. Applying a causal mask afterward does not shrink the allocation already made. A top-k applied to a complete candidate-score table does not eliminate the memory needed to produce that table either.
The solution is to control the intermediate where it is created. The indexer scores a bounded set of queries, keeps their top-k indices, and moves on. Headwise reductions happen inside tiles, so the full head dimension is never added to a global score buffer. Teacher-target computation likewise keeps the normalization statistics it needs and accumulates contributions without exposing the entire headwise matrix.
This also explains why a chunk size should follow a memory budget. At 1M, scoring one query against 256K compressed keys requires 1 MiB for the FP32 candidate scores. A 1.5 GiB score-buffer budget therefore permits 1,536 queries at a time. At 256K, the same budget permits 6,144. Keeping an 8K chunk simply because it was comfortable at 64K would miss the growth of the other axis.
Top-k selection introduces a smaller but related issue. If a reference implementation gathers every query’s selected keys into a tensor of shape , keys shared by many queries are copied many times. With 8K queries, 512 selected keys, and width 512, that gather alone occupies 4 GiB in BF16. The sparse kernel can instead follow the indices inside its tiles and accumulate the attention result there. A matrix multiplication also avoids the even larger broadcast-multiply temporary that a literal elementwise implementation could create.
For teacher targets, dividing the computation into tiles still requires the correct denominator. The compressed-key contribution has to account for the relevant sliding-window and attention-sink mass. We cannot independently normalize each tile and average its output. This is the same reason Ring Attention needed log-sum-exp statistics when combining blocks.
Packed documents offer another way to avoid work before allocating it. The indexer used to score keys outside the current document and filter them afterward. The compression plan already knows the valid document-local interval; using that interval directly avoids both the scores and the large same-document mask for irrelevant keys.
HCA had a similar problem in how it represented history. A late document might use compressed keys in [12000, 12128), yet be described by an explicit container starting at zero, mostly filled with invalid entries. Its cost could then depend on where it appeared in the pack. Passing the actual start and extent makes the work depend on the document’s own range. Fixed-width top-k outputs also carry a valid length so the kernel can skip tiles containing only padding.
These changes work together. Chunking limits how much we produce at once. Fusing avoids intermediates that never needed to leave the kernel. Document and causal ranges remove computation we never needed to perform. All three matter when asking whether a design that works today will still make sense at 1M.
The last projection can consume the memory attention saved
Once attention fits, it is tempting to think the hard part is over. Then the model reaches its last projection:
logits = linear(hidden, lm_head_weight)
loss = cross_entropy(logits, labels)pythonThe logits have shape . With 1M tokens, a 128K vocabulary, and BF16, they occupy
With CP16 splitting the tokens, that is still 16 GiB per rank for the logits alone. There is no quadratic sequence dimension here; a sufficiently large vocabulary makes this linear allocation a problem anyway.
The fix is to postpone the LM head and compute projection plus cross entropy in token chunks. Splitting cross entropy after generating the full logits would be too late. In our framework, the training-time output head passes the final hidden states to the loss path, which projects 4,096 tokens at a time. With the example vocabulary above, one BF16 logits chunk is 1 GiB. Cross entropy and any FP32 conversion need additional workspace, but we no longer need all the sequence’s logits together.
There is still a trap in the obvious implementation:
loss = 0
for hidden_chunk, label_chunk in chunks:
logits = linear(hidden_chunk, weight)
loss = loss + cross_entropy(logits, label_chunk)
loss.backward()pythonEach iteration creates a graph, and the final loss depends on all of them. Autograd can therefore keep every chunk’s intermediates alive until backward. The individual allocations got smaller, but their lifetimes still overlap.
I used a custom autograd function to control this. Forward computes the per-token losses without keeping a separate projection-and-CE graph for every chunk. It saves hidden states, weights, and labels. Backward reconstructs one chunk’s logits and loss derivative at a time. If is a chunk’s logits gradient, the remaining matrix multiplications are
We write each hidden-state gradient into its corresponding slice and accumulate all chunks into one weight-gradient buffer. This costs another projection during backward, but gives us control over the large vocabulary-sized intermediate.
The loss reduction still needs to mean the same thing. A short final chunk or a chunk with many ignored labels should not receive the same weight as a full chunk of valid tokens. The chunked operation therefore returns per-token losses; masking and normalization happen afterward. Across CP ranks, the token-normalized objective is
Each rank’s local contribution also has to account for how the training code combines gradients. Changing the chunk size or splitting tokens across more ranks should change how we execute the loss, while preserving the weight each valid token has in the objective.
A scalar can keep an entire graph alive
After spending so much effort shrinking individual allocations, I also had to look at how long they survived. Auxiliary losses made this particularly visible.
It is natural for a layer to compute an auxiliary loss, store it in self.last_aux_loss, and return its hidden states. The trainer can collect those scalars after forward and add them to the main loss. The scalar itself uses almost no memory.
But the scalar has a grad_fn. It is also a reference into a graph, and that graph can retain much larger tensors. Putting the scalar on a module gives it a lifetime determined by a long-lived Python object, rather than by the computation that needs it.
Activation checkpointing makes this more awkward. During backward, it reruns parts of forward to reconstruct discarded activations. If that replay also writes self.last_aux_loss, it can publish a new graph that the trainer never collects. The original loss has already been assembled. The replay-only graph can remain attached to the module even though nothing intends to backpropagate through that published value.
The refactor connects the auxiliary gradient where the loss is produced. An identity-like autograd operation takes an activation and an auxiliary loss:
Forward returns the same activation. Backward passes its incoming gradient through and sends into the auxiliary-loss branch:
Now the auxiliary branch is reached through the activation’s backward path. The trainer does not need to keep a second collection of differentiable module-side scalars until the end of forward. The values published for logging can be detached.
That last distinction matters: detaching a metric is fine; detaching the loss we intend to train with would remove its gradient. The gradient-bearing loss remains connected through AttachAux. Its scale also has to include the intended gradient-accumulation and parallelism normalization, because a custom backward supplies that gradient explicitly.
We also separate computation from bookkeeping during checkpoint replay. Recomputed operations still do the work backward needs, but they should not publish another set of metrics or training state. Together, these changes give the loss graph a lifetime tied to the actual training computation.
This is the part of memory optimization that a table of tensor shapes does not capture. Peak memory depends on which tensors are alive at the same time. A temporary used briefly can be harmless, while a small scalar that keeps a whole layer’s dependencies alive can be expensive.
There is also a useful opposite case. Sometimes a compact saved state is worth retaining because reproducing it is costly. I used that tradeoff for selected-score gradients in the indexer. The point is to make the choice deliberately: how big is the state, how many layers keep it, and how much work does it save? A policy that makes sense at 64K needs another look at 1M.
A tensor can fit while its address arithmetic overflows
Long context also breaks assumptions that are easy to overlook when watching memory usage. One of them is that a 32-bit integer is large enough for tensor indexing.
Signed int32 stops at . The individual indices in our kernels are usually much smaller. But address calculation multiplies them by strides. For example, if a score or target buffer has 262,144 keys per row, row 8,192 starts at
elements from the start. Both operands fit in int32. Their product does not. An FP32 buffer with shape [1, 16384, 262144] is 16 GiB: it can fit on a large GPU, yet an int32 calculation cannot represent the offset to that perfectly valid row.
This is an element offset, not a byte count. A 64-bit pointer does not help if the offset added to it was already computed incorrectly. And widening the result afterward is too late:
# Multiplication happens in int32 before the cast.
wrong = (row_i32 * width_i32).to(tl.int64)
# Widen an operand before the multiplication.
correct = row_i32.to(tl.int64) * width_i32.to(tl.int64)pythonThe fix promotes the relevant indices before multiplying them by strides or leading dimensions. It is a small code change with a large effect on which shapes the kernel can safely handle.
There was a less obvious version of this problem too. A contiguous teacher-query tensor with shape [1, 65536, 64, 512] has these element strides:
shape: (1, 65536, 64, 512)
strides: (2147483648, 32768, 512, 1)textIts batch stride is . Batch size is one, so we never actually move to a second batch. Nevertheless, that huge unused stride can still be passed to the kernel and encounter an int32 assumption.
Slicing out a small query chunk need not remove it. The view can retain its parent’s batch stride, and a size-one dimension can have that stride while the tensor is still considered contiguous. Here is a tiny example:
q = torch.empty_strided(
(1, 4, 64, 512),
(2**31, 64 * 512, 512, 1),
dtype=torch.bfloat16,
)
print(q.is_contiguous()) # True
print(q.stride(0)) # 2147483648pythonThis tensor only needs 256 KiB of element storage. There is no second batch to allocate, but the large stride is still part of its layout. Calling .contiguous() is not a reliable way to eliminate it, because the tensor is already contiguous.
For size-one batches, we normalize that unused batch stride to zero. For offsets that are actually traversed, we use sufficiently wide arithmetic. The two fixes address different parts of the problem.
This was a good example of what preparing for 1M means in practice. We are no longer only asking whether an operation gets slower or consumes more memory. We also have to ask whether assumptions inside its implementation remain valid at all.
What preparing for 1M changed
For me, the useful change in perspective was to stop treating sequence length as just another configuration value. It changes which representations are affordable, how much data we should move, how we should group training examples, and how long we can afford to keep an intermediate alive.
FA3 and Ring Attention give us better ways to execute and distribute attention. Length-aware packing helps the workers arrive at synchronization points together, provided we do not sacrifice the data mixture to get there. The DeepSeek V4 refactor takes the next step: keep raw data local, share the representations the model needs, and avoid turning a compressed or sparse computation back into a giant dense temporary.
The same principle continues through the LM head, auxiliary losses, and kernel indexing. Before choosing a faster implementation, I want to understand what we are asking it to produce. At 1M context, that decision can determine whether there is a feasible implementation in the first place.
Appendix: the attention background
The main article assumes some familiarity with distributed attention and V4’s compressed history. Here is a more concrete walk through both.
Ring Attention: keep the queries, circulate the history
For one attention head, each token produces a query, a key, and a value. A query scores the keys it is allowed to see; softmax turns those scores into weights; the output is a weighted sum of the corresponding values:
Here is the head dimension, and masks future tokens and tokens from other packed documents. The reason attention needs communication is now fairly direct: a local query can depend on keys and values owned by another GPU.
Suppose four GPUs share a sequence. GPU 0 owns token block 0, GPU 1 owns block 1, and so on. Each initially has the Q, K, and V for its own tokens. Ring Attention ↗ keeps each Q block in place and passes the KV blocks around the GPUs. The diagram starts from that initial ownership; the arrows show one transfer step.
Follow GPU 3. First it computes its queries against KV block 3. After one transfer, it has block 2; then block 1; then block 0. It combines each contribution with the running result. It never needs all four KV blocks resident together. The next transfer can overlap the current calculation, provided there is enough computation to cover the communication.
The running result contains more than an output vector. Each block initially normalizes over its own keys, so we also retain the softmax statistics needed to put all blocks on the same denominator. Imagine that one block has total unnormalized weight 9 and produces output 2, while another has weight 1 and produces output 10. The combined output is , rather than the unweighted average 6. The log-sum-exp merge in the main article does this without explicitly storing potentially enormous exponentials.
Causality still applies to every block. In this contiguous example, GPU 0’s queries cannot read blocks 1–3. GPU 3 has much more useful work, which explains the zigzag layout shown earlier: pairing early and late portions of the sequence balances that causal triangle. Packed-document masks must follow the tokens through the rearrangement too.
Ring changes where and when dense attention is evaluated. It does not remove the permitted query-key pairs, and its dense attention work still grows quadratically with sequence length. FlashAttention handles the local tiles; Ring handles the communication between devices. Their memory savings come from doing the work incrementally at those two different scales. During training, KV gradients also have to find their way back to the ranks that own those tensors.
Ulysses: exchange a sequence split for a head split
Ulysses ↗ uses another property of attention: heads can be evaluated independently before their outputs are combined. It temporarily changes which dimension is divided across GPUs.
Consider two GPUs, four tokens, and four attention heads. Initially GPU 0 owns tokens 0–1 for all four heads, while GPU 1 owns tokens 2–3 for all four heads. An all-to-all exchanges pieces of Q, K, and V so that GPU 0 receives all four tokens for heads 0–1, and GPU 1 receives all four tokens for heads 2–3.
Each GPU can now run attention over the full sequence for the heads it owns. Afterward, a second all-to-all restores the original layout: a subset of tokens with all heads, ready for the rest of the layer. For ordinary multi-head attention, the per-rank shape changes as follows, with batch and head width omitted:
The number of elements per rank stays the same ↗ in this example. The sequence axis gets longer while the head axis gets narrower. That is why “each rank sees the full sequence” does not mean each rank holds the full multi-head tensor.
The available heads constrain this split. In the simple layout above, the head count must divide evenly across the Ulysses group. With grouped-query attention, we have to check the KV heads as well as the query heads. In our 30B-A3B example, Ulysses4 gives each rank eight of the 32 query heads and one of the four KV heads. Increasing Ulysses to eight would leave too few KV heads for that partition. Going beyond this limit needs a different treatment of KV distribution, such as replication, or another way to divide the work. Ring divides token blocks, so it can add more ranks without dividing that single KV head again.
Our framework can combine the two: an all-to-all across a Ulysses group creates a head partition, and Ring circulates KV blocks across another group for that partition. For example, a 2-way Ulysses group and a 4-way Ring group give an 8-way context-parallel layout. This lets us choose how much communication uses all-to-all and how much uses block transfers, while the local attention operator remains reusable.
DeepSeek V4: a local window and two ways to read compressed history
V4’s attention design ↗ changes the history a layer reads. It keeps a small window of recent, uncompressed tokens, while representing the longer history with compressed KV entries. Its two compressed attention types are Compressed Sparse Attention (CSA) and Heavily Compressed Attention (HCA). They appear in different layers.
The diagram uses our framework’s Flash configuration: a 128-token sliding window, C4 compression with up to 512 selected entries for CSA, and C128 compression for HCA. The first two layers use only the sliding window; subsequent layers alternate CSA and HCA. Both compressed layer types retain the local window.
Start with the local window. A query can read recent tokens individually, without relying on a compressed representation to preserve every local detail. The window has fixed width, so its raw-KV requirement does not grow with the entire context. Under CP, a rank needs the short boundary halo when its earliest queries look back into the preceding shard.
CSA gives the query a more selective route into the longer history. The compressor emits roughly one KV entry for every four input tokens. This is learned compression: projections and learned weights decide how information is combined. In the C4 path, neighboring groups overlap, so an entry can incorporate information from the preceding group too. “4:1” describes the rate at which entries are produced; it does not mean four disjoint tokens are simply averaged. This overlap is one reason the CP compressor needs an explicit boundary plan.
The indexer then scores eligible compressed entries for each query and chooses up to 512 of them. Main attention reads those selected entries together with the raw local window. Different queries can choose different parts of the history. There is still a query for each original token: the compression discussed here reduces the KV sequence.
HCA ↗ compresses much more aggressively, producing roughly one entry per 128 tokens. It reads all causally available compressed entries from the same document, without the CSA top-k selection. At 1M, C4 produces about 256K candidate entries, while C128 produces about 8K. CSA spends attention on selected entries from a finer representation; HCA reads a coarser representation more broadly. Both entry counts continue growing with context.
Within either layer, the raw-window keys and the chosen compressed keys participate in a common normalization. V4 also has a learned attention sink per head. It contributes to the softmax denominator without contributing a token value to the numerator. Writing for the raw window and for the compressed entries read by query , one head’s output is
Here is that head’s sink logit. This is why computing separate softmaxes for the window and compressed history, then averaging them, would change the result. The teacher targets used to train the indexer also need the appropriate normalization.
This architecture explains the shape of the refactor in the main article. Raw-window attention needs a halo. Compression needs document-aware ownership and boundary inputs. CSA needs selection without a giant score temporary. HCA needs an efficient representation of its valid compressed range. KV entries are shared across attention heads, but queries and attention scores still have a head dimension—so a small shared KV representation can still lead to a huge headwise score tensor if we materialize it. These dependencies give us useful ways to divide the work, provided the implementation follows them all the way through.