The Cost Ledger of Long-Context Pretraining: Attention Share, Sequence Parallelism and Staged Window Extension
A 128K context window is not "bump seq_len and train a few more days". Llama 3 states it plainly: long sequences are not used earlier in training because the compute in self-attention layers grows quadratically in sequence length. Behind that sentence sit three separate ledgers — compute share, memory and communication, data and positional encoding. This article turns all three into reproducible numbers, and connects to pretraining compute and cost planning and the distributed parallelism landscape.
1. Three questions to answer first
- Which layer is expensive? Is attention itself getting expensive, or is memory running out, or is communication rising, or is effective throughput collapsing? Each maps to a completely different action.
- How do you wire sequence parallelism? Where is the boundary between CP and TP, what are the hard constraints, and why could teams from 2024 onward simply set CP to 8 or 16?
- How many tokens does the extension stage need, how should data and positional encoding be configured, and what counts as passing acceptance?
The conclusion up front: the extension stage's absolute compute is usually small — 4.3% of total training in DeepSeek-V3's published accounting — but the unit cost per token is more than 5x that of main pretraining. So this budget cannot be read as "a percentage of the total"; it has to be read as "price per token".
2. Ledger one: how much of per-token compute is attention
Forward compute per layer per token splits into two parts. The linear part (QKV/O projections plus FFN) does not depend on sequence length:
The attention part (QK^T and AV) grows linearly with sequence length. With a causal mask that only computes the lower triangle, the average query sees s/2 keys:
Dividing the two gives a ratio that needs only hidden size and sequence length:
Convert it into an attention share (attn / total) with an FFN expansion ratio of 4, a common configuration:
| Hidden size d | 4K | 8K | 32K | 128K | Per-token compute at 128K vs 8K |
|---|---|---|---|---|---|
| 4096 (7B class) | 5.9% | 11.1% | 33.3% | 66.7% | 2.67x |
| 8192 (70B class) | 3.0% | 5.9% | 20.0% | 50.0% | 1.88x |
| 16384 (405B class) | 1.5% | 3.0% | 11.1% | 33.3% | 1.45x |
Two counter-intuitive but important corollaries:
- At 128K, attention is no longer the small term: for d=8192 the attention part equals all linear layers combined; for d=4096 it is two-thirds of the total.
- Small models pay relatively more for long context: linear compute scales with d², attention with s·d, so a smaller d means a higher attention share. Going from 8K to 128K multiplies per-token compute by 2.67 for a 7B-class model but only 1.45 for a 405B-class one. Validating a long-context recipe on a small model is therefore conservative in compute structure but looser in memory and communication — neither extrapolates cleanly.
Caliber notes: the lower triangle is counted as FlashAttention-style kernels actually compute it; vocab projection and backward (about 2x forward, a constant factor that does not change the share) are excluded; r=4 is an assumption, and a larger r lowers the attention share.
3. Ledger two: the unit price of the extension stage
Two published recipes provide good anchors.
DeepSeek-V3: 14.8T tokens of main pretraining, then YaRN-based extension in two stages of 1,000 steps each — first 4K→32K, then 32K→128K. The key configuration:
| Stage | Sequence length | Batch (sequences) | Tokens per step |
|---|---|---|---|
| Stage 1 | 32K | 1920 | 62,914,560 |
| Stage 2 | 128K | 480 | 62,914,560 |
The two products are exactly equal — the extension stage keeps tokens per step constant and only trades batch size for longer sequences. That is a very practical discipline: when you change seq_len, pin tokens/step first and back out the sequence count, otherwise gradient noise and learning rate drift together.
From the published cost table: 2,664K H800 GPU-hours for main pretraining and 119K for extension (2,788K total). Converting into unit prices:
- Main pretraining: 2,664,000 / 14,800 ≈ 180 GPU-hours per billion tokens
- Extension stage: 119,000 / 125.8 ≈ 946 GPU-hours per billion tokens
In other words, each token in the extension stage costs about 5.3x more than in main pretraining, while the stage consumes only 4.3% of the budget. That "expensive but small share" combination is exactly why teams underestimate the difficulty: the budget looks fine, but engineering has to re-solve parallelism, memory, data and stability.
Llama 3 405B shows a different shape: six stages stepping from 8K up to 128K, roughly 800B tokens in total, with a global batch of 16M tokens per step during long-context training. That works out to 800B / 16M = 50,000 steps, and at 128K a step holds only about 122 sequences (16M / 131072). The paper also publishes the MFU cost: 43% BF16 MFU at 8K with CP=1, 38% at 131072 with CP=16 — the extension shaves off about 5 percentage points of hardware efficiency, a loss that never appears in the FLOPs formula but always appears in the GPU-hour ledger.
A directly usable estimator (6ND plus the attention correction):
Take a 70B model, 100B tokens, 35% MFU and 989 TFLOPS of dense BF16 per GPU (the 1,979 on the H100 SXM spec sheet is the sparsity figure): about 36K GPU-hours at 8K versus about 67K at 128K. Same token count, only a longer sequence, and the bill grows 1.88x — matching the 1.88 from section 2 exactly. That is why the ledger has to be computed twice: the formula gives direction, the public recipes give calibration.
4. Memory: why you split the sequence instead of leaning on recompute
Long sequences stress memory because activations grow linearly with sequence length (the intermediate results of every layer and every token). The three usual workarounds have very different prices:
| Means | What it fixes | Price |
|---|---|---|
| Full activation recompute | Activation memory | About 30% extra overhead (Megatron-Core documentation) |
| Larger TP | Per-GPU parameters and activations | Compute per GPU gets too thin, communication is hard to overlap |
| CP (context parallelism) | Each GPU handles s/CP tokens | KV exchange at attention; sequence must be divisible |
Megatron-Core describes it directly: CP partitions network inputs and all activations along the sequence dimension; every module except attention (Linear, LayerNorm) works unchanged because it has no inter-token operations; attention must see the full sequence's KV, hence an all-gather, with reduce-scatter in backward. To save memory, the forward pass keeps only the local chunk of KV and gathers again in backward. Communication happens only between corresponding ranks of the same TP group.
So the right order is: split the sequence with CP first (activation memory, compute and communication all shrink by CP), and keep recompute as the fallback — not the main weapon.
5. Three sequence-parallel routes and their hard constraints
| Route | Splitting | How attention works | Hard constraint | Where it fits |
|---|---|---|---|---|
| Megatron CP (ring style) | Sequence into CP chunks | all-gather full-sequence KV, lowered to ring P2P | Sequence length must be divisible by CP (pad otherwise); Megatron-Core >= 0.5.0, Transformer Engine >= 1.1 | Mainstream LLM pretraining |
| Ulysses | Sequence into CP chunks | two all-to-alls swap the split axis from "sequence" to "attention heads" | Head count must be divisible by CP (commonly stated as TP x CP); early implementations could not mix with TP/PP | Plenty of heads, want to avoid full KV gather |
| Larger TP | Hidden dimension | Each GPU computes a subset of heads | Frequent communication, fragmented per-GPU compute | When the model itself does not fit |
World size multiplies out: total GPUs = TP x CP x PP x DP. Enabling CP necessarily squeezes DP, so the number of sequences in the global batch drops — that is precisely why the "pin tokens/step" discipline in section 3 exists.
One implementation detail from Megatron is worth remembering: it says CP follows the same idea as Ring Attention but performs better by (1) using the latest open-source and cuDNN FlashAttention kernels, and (2) eliminating unnecessary computation caused by low-triangle causal masking, achieving better load balance. In other words, "CP is just reimplementing Ring Attention" is wrong — the kernels and how the mask triangle is exploited decide actual efficiency.
Ulysses's advantage is the nature of its communication: the paper's result is that when sequence length and device count scale proportionally, its communication volume stays constant, whereas other methods grow with the sequence. The price is the divisibility constraint — a 40-head model cannot be split evenly across 8 or more GPUs and must fall back to dummy heads or to ring.
6. Ledger three: CP traffic is set by the KV head count
Much of the fear around CP comes from the MHA era, when KV had to be gathered in full. A quick calculation shows the magnitude and why GQA changed it.
Per layer, per rank, per forward pass, the KV bytes to gather are:
Using Llama 3 405B's published structure (128 attention heads, 8 KV heads, head_dim 128), a 128K sequence and bf16: 131072 x 2 x 8 x 128 x 2 B = 512 MiB per layer, about 63 GiB across 126 layers. At 400 GB/s of per-GPU IB bandwidth that is roughly 0.17 seconds — a small slice of a 128K step's compute time, and under a ring topology it can overlap with compute.
Switch to a same-scale model with MHA (128 KV heads) and the volume multiplies by 16, reaching the 1 TiB range — no longer negligible communication at all. This is why models designed from 2024 onward could set CP to 8 or 16 directly: GQA/MQA/MLA cut the KV head count, and CP's main communication bottleneck disappears with it. Megatron's documentation likewise lists MQA/GQA as a way to reduce CP communication volume.
Engineering implication: to judge whether CP pays off, look at n_kv and d_head, not the total head count. Older structures with many KV heads should prefer Ulysses or a smaller CP degree; newer structures with few KV heads get CP as nearly free memory expansion.
7. Data: where long documents come from, and the mask you must add
The most overlooked point in the extension stage: length is fed by real data, not produced by positional encoding.
Llama 3 made one small architectural change and stated the reason: an attention mask that prevents self-attention between different documents within the same sequence, noting that "this change had limited impact during standard pre-training, but find it to be important in continued pre-training on very long sequences". The reason is plain: long-sequence training must rely on packing several short documents into one 128K sequence, otherwise the effective token rate collapses; and without a document-level mask after packing, the model learns spurious cross-document associations — averaged away at short lengths, but systematically destructive to the attention distribution at long lengths.
Three things to do:
- Turn on packing and document-level masking together, never one without the other.
- Bucket by length: count the token share of 4K–8K, 8K–32K and 32K+ documents separately before deciding what the extension stage eats. Long documents are scarce by nature; forcing them drives the effective token rate down.
- Measure the effective token rate:
effective tokens / padded tokens. Below 70% means the packing or bucketing strategy is broken — fix the data side before adding GPUs.
8. Positional encoding: retrain with a new theta, or extrapolate with YaRN
Two routes, and picking the wrong one costs a whole training stage.
Changing the RoPE base (retrain route): Llama 3 raised the RoPE base from 10,000 to 500,000, citing Xiong et al. that this value is effective for contexts up to 32,768, then pushed to 128K with staged extension. This route requires carrying the new base from pretraining onward — it changes the model's native window.
YaRN extrapolation (post-training route): DeepSeek-V3 applied YaRN after main pretraining, with scale s=40, alpha=1, beta=32 and scaling factor sqrt(t) = 0.1 ln s + 1, applied only to the decoupled shared key; hyperparameters were identical across both stages, and the learning rate was 7.3e-6, matching the final pretraining rate.
Decision rules:
- If the model will keep pretraining at scale: change the base and build the window into the model once.
- If the base model is fixed and you only need long-context capability: YaRN post-training, at the price of a small stage (2,000 steps for DeepSeek-V3).
- Never change it dynamically mid-training: compute
inv_freqonce. Recomputing every step is numerically unstable and irreproducible.
9. Acceptance: three criteria, all required
Llama 3's criteria can be copied straight into a checklist:
- Short-context capability fully recovers: after extension, the original short-task evaluations return to pre-extension levels (noise allowed, systematic regression not).
- NIAH fully covered: the needle is retrieved at every depth and every position of the target length. DeepSeek-V3's published results are stable across all lengths up to 128K.
- Downstream long-document tasks: summarization, long-document QA, repository-level code understanding — real tasks, not just NIAH.
One engineering criterion to add: no loss spike at packing boundaries. If the loss curve jitters at a fixed position within each batch, suspect the mask or position ids not being reset per document before touching the learning rate.
10. One-page planning table
| Decision | Basis | Typical value |
|---|---|---|
| Enable CP? | s exceeds what one GPU's activations can hold | Consider from 32K; basically mandatory at 128K |
| CP degree | Sequence divisibility, KV heads, bandwidth | 8 or 16 |
| Tokens per step | Aligned with main pretraining | ~60M |
| Extension token budget | 1%–6% of main pretraining | 100B–800B |
| Learning rate | Final pretraining rate, no re-warmup | ~7e-6 |
| Number of stages | Double or 4x per stage, until adapted | 2–6 |
| Masking | Packing + document-level | Mandatory |
| Positional encoding | Retrain with new base / YaRN post-training | Pick one |
11. Five pitfalls and a one-line summary
- Treating extension as "change a parameter": a single-digit percentage of the budget, but 5x the unit GPU-hours and a full-stack engineering redo.
- Enabling CP and forgetting tokens/step: longer sequences with the same sequence count is a 16x batch, and learning rate plus stability collapse together.
- Packing without document-level masking: invisible at short lengths, attention gets contaminated across documents at long lengths.
- Judging CP feasibility by total head count: look at KV heads; only Ulysses cares about head divisibility.
- Declaring success after NIAH alone: short-context regressions usually surface only on real tasks.
In one line: long context is not "a longer input", it is "a more expensive token plus a parallelism stack that must be rewired". Compute the attention share and the extension unit price first, then decide the CP degree, the token budget and the number of stages — get that order wrong and every later tuning knob is work done against the wrong ledger.
Further reading
- Pretraining compute and cost planning: the upstream ledger of GPU-hour budgets and MFU corrections
- The distributed parallelism landscape: how TP/PP/DP/CP combine
- Mixed precision training and resilient checkpointing: memory and stability management in long-sequence stages
- Long-context inference: how the training-side window becomes the serving-side KV ledger
- The pretraining data pipeline in practice: long-document filtering and mixing, upstream