Maps to: CMU 11-711 Spring 2026, Lecture 22 (04/07), “Scaling Sequence Length”, Sean Welleck (some slides by Graham Neubig, Fall 2024); slides
anlp-s2026-22-longcontext.pdf; no course code. Readings: M. Rabe, C. Staats, Self-attention Does Not Need O(n²) Memory (2021); A. Gu, T. Dao, Mamba: Linear-Time Sequence Modeling with Selective State Spaces (2023). Additional: T. Dao et al., FlashAttention (NeurIPS 2022); H. Liu et al., Ring Attention with Blockwise Transformers for Near-Infinite Context (2023). Sources: the public slides, the readings, and the papers cited in each section. Numbers quoted from papers or slides are attributed to them. Every number labelled “measured” comes fromcode/lecture22/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14, one CPU thread). Code:code/lecture22/— five demos, each under 15 seconds once the models are cached. Reading time: ~85 minutes for the prose; ~15 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Say where attention’s cost grows as in compute and in memory, and why memory traffic (HBM ↔ SRAM) is the real bottleneck.
- Derive the online softmax, and explain how chunked attention, FlashAttention and ring attention compute exact attention without the matrix.
- Explain why trained models fail to extrapolate beyond their training length, for learned, fixed and relative position encodings.
- Explain RoPE scaling: position interpolation and an adjusted base frequency. Say why continued training on long documents is the reliable fix.
- Write down a state-space model, compute it as a recurrence and as a convolution, and explain what Mamba’s selectivity adds and why it needs a parallel scan.
- Read long-context benchmarks critically: needle-in-a-haystack, lost in the middle, RULER, aggregation tasks.
0.2 Prerequisites and scope
- Prerequisites:
- Lecture 5: attention, positional encodings, RoPE.
- Lecture 4: RNNs.
- Lecture 9: the KV cache.
- Lecture 20: activation memory and ring collectives.
- Scope: the slides’ outline. Long-context use cases and evaluation; improving Transformers (memory-efficient computation, extrapolation, modifications); Transformer alternatives (state-space models).
- Not in scope:
- Retrieval as an alternative to long context (Lecture 10).
- KV-cache compression and eviction.
- Linear attention and RWKV-style recurrences, beyond a mention.
- The GPU kernel code of FlashAttention.
0.3 Section → code map
| Section | Idea | Demo in code/lecture22/ |
|---|---|---|
| §3.1–3.5 | the terms; online softmax; chunked attention; FlashAttention’s IO; KV cache | 01_attention_cost.py (+ attention_impl.py) |
| §3.6 | ring attention / context parallelism | 02_ring_attention.py |
| §4 | extrapolation failures, by length and distance | 03_extrapolation.py (+ long_lm.py) |
| §5 | RoPE scaling and continued training | 04_rope_scaling.py |
| §7 | S4, Mamba, the scan, selective copying | 05_state_space.py (+ ssm.py) |
0.4 Notation
| Symbol | Meaning |
|---|---|
| (or , ) | sequence length |
| batch size, number of heads, model (or head) dimension | |
| running max, running sum, running output of the online softmax | |
| size of on-chip SRAM (elements) | |
| number of devices in context parallelism | |
| RoPE frequency of dimension pair with base | |
| state-space matrices and step size; their discretized versions |
1. How long are sequences, and why is that hard?
The slides’ scale of things (in tokens):
| content | length |
|---|---|
| one sentence | ~20 |
| one document | 100–10k |
| one book | 50k–300k |
| one video | 1.5k–1M (~300 per second) |
| one codebase | 20k–1B |
| one genome | 3B nucleotides |
Modeling such sequences is hard for three reasons (slides):
- Memory: Transformer attention needs memory quadratic in sequence length, if done naively.
- Compute: attention’s computation is quadratic in sequence length.
- Training: long data is scarce, the training signal from far-away context is weak, and training on long sequences is costly.
The lecture attacks them in turn:
- compute exact attention without quadratic memory (§3);
- understand and fix models that break beyond their training length (§4–5);
- replace attention by a recurrence that is linear in length (§7).
2. Long-context use cases and evaluation
How do we know a model uses a long context, rather than merely accepting it?
- Composite benchmarks: Long Range Arena (Tay et al., 2020; mostly non-NLP tasks); SCROLLS (Shaham et al., 2022; long-document summarization, QA, …).
- Targeted analyses:
- Lost in the middle (Liu et al., 2023): models use information at the beginning and end of the context much better than in the middle.
- Needle in a haystack (Kamradt, 2023): hide one fact at a chosen depth of a long filler text and ask for it; plot accuracy over (length, depth).
- RULER (Hsieh et al., 2024): many needle-style tasks (multiple needles, multi-hop tracing, aggregation) at controlled lengths.
- Aggregation: Oolong (Bertsch et al., 2025) asks questions that need many pieces of a long context combined. An example: how many times did a character cast a spell in a transcript of a Dungeons & Dragons show? Retrieving one needle is not enough.
- Long-context in-context learning (Bertsch et al., 2024): with many demonstrations in the context, in-context learning can rival or beat fine-tuning.
Our demos use the simplest of these: a needle in a haystack. The haystack is Errand World sentences (Lecture 3), the needle “the code is 4 1 7 .”, and the question at the end “what is the code ? 4 1 7”. It is enough to expose extrapolation failures. It cannot test aggregation or reasoning over the context, which are harder and closer to real use.
3. Where the goes, and how to avoid materializing it
3.1 Attention’s complexity
For one layer with (slides):
- Compute: costs , and so does multiplying the attention weights by .
- Memory: the score and weight matrices take per head, for heads, while the output is only . Splitting into heads does not change the compute, but multiplies the score memory by .
Computed (demo 01 Part A, one layer of Llama 3 8B’s size, batch 1):
| sequence length | projection FLOPs | FLOPs | attention share | score matrices (bf16) |
|---|---|---|---|---|
| 1,024 | 8.6e10 | 1.7e10 | 17% | 0.1 GB |
| 16,384 | 1.4e12 | 4.4e12 | 76% | 17.2 GB |
| 131,072 | 1.1e13 | 2.8e14 | 96% | 1,100 GB |
From about 16k tokens on, attention outweighs all the layer’s projections. At 128k tokens one layer’s score matrices would take 1.1 TB.
3.2 The memory hierarchy
GPUs have a little fast memory and a lot of slow memory. An A100 has ~20 MB of on-chip SRAM at ~19 TB/s, and 40–80 GB of HBM at ~1.5–2 TB/s (FlashAttention’s figure, on the slides). Standard attention writes the matrix to HBM, reads it back for the softmax, writes the result, and reads it again. The implications (slides):
- long-context training and inference become slow: bandwidth, not FLOPs, limits them;
- or infeasible: memory simply runs out.
3.3 The online softmax
The way out (Milakov & Gimelshein, 2018; Jang, 2019; Rabe & Staats, 2021): compute the softmax online, one chunk at a time. For any constant ,
and keeps every exponential . Read in chunks, keeping a running max and a running sum . When a new chunk raises the max to , rescale what you have:
For attention, also keep the running weighted sum of values and rescale it the same way: . At the end is exactly the attention output.
Measured by hand (demo 01 Part B), for :
| chunk | running max | running sum |
|---|---|---|
| 1 3 | 3 | 1.1353 |
| 2 5 | 5 | 1.2034 |
| 0.5 | 5 | 1.2145 |
The final probabilities equal torch.softmax to four decimals. The memory needed: the numerator is and the denominator is (slides); the matrix never exists. The slides show Rabe & Staats’ benchmark: memory falls by orders of magnitude, with analogous savings for training.
3.4 Measured: chunked attention
Demo 01 Part C computes causal attention twice, naively and in 128 × 128 blocks with the online softmax, and measures the peak memory of all live tensors:
| sequence length | naive | chunked | ratio | max difference |
|---|---|---|---|---|
| 256 | 2.7 MB | 1.6 MB | 2× | 3.9e-07 |
| 1,024 | 36.7 MB | 3.2 MB | 11× | 4.8e-07 |
| 4,096 | 574.6 MB | 11.1 MB | 52× | 4.2e-07 |
Each doubling of the length multiplies the naive peak by ~3.6 (quadratic, plus linear parts) and the chunked one by ~1.9 (linear). The outputs agree to float rounding: this is exact attention, computed in a different order.
3.5 FlashAttention
FlashAttention (Dao et al., 2022) writes the chunked computation as one GPU kernel:
- load blocks of , , into SRAM, compute the block’s scores and online-softmax update there, write only the output back;
- in the backward pass, recompute the scores from instead of storing them: a few more FLOPs, far less memory traffic.
Dao et al. prove that standard attention needs HBM accesses, and FlashAttention for SRAM size . Computed with their model (demo 01 Part D, elements):
| sequence | head dim | fewer HBM accesses |
|---|---|---|
| 4,096 | 64 | 5.6× |
| 65,536 | 64 | 6.0× |
| 65,536 | 128 | 1.5× |
FlashAttention’s speedup comes from memory traffic, not fewer FLOPs. Its memory is linear in , which is what made long-context training practical. Since then it has become the default attention implementation in every major framework.
3.6 Ring attention: context parallelism
When one sequence does not fit on one device, split it across devices (Liu et al., 2023; the Playbook’s “context parallelism”):
- each of devices holds one block of queries and the matching block of keys and values;
- in each of steps, a device computes its queries against the K/V block it currently holds, merges the result with the online softmax, and passes the block to its neighbour on a ring (Lecture 20’s ring);
- after steps every query has seen every key.
Sending the next block overlaps with computing on the current one.
Measured (demo 02):
- Exact: ring attention equals ordinary causal attention to 4e-07 for 2, 4 and 8 devices.
- Causal masks unbalance the work. With contiguous blocks, device 0 needs only its own block while the last device needs all of them. Per-device score entries over the whole ring: 2,080 / 6,176 / 10,272 / 14,368, a 6.9× spread, and every step waits for the slowest device.
- The zigzag layout (the slides’ “clever interleaving”) gives each device one early and one late chunk: 8,224 entries each, and the ring finishes in 57% of the time.
- Overlap needs long blocks. Per step, compute grows with the block length squared and communication only linearly. Communication hides once each device holds at least (peak FLOPS)/(bandwidth) tokens: computed, ~1,300 tokens over NVLink and ~11,900 over InfiniBand. Ring attention is a tool for very long sequences, which is where it is needed.
3.7 What remains: the KV cache
At generation time, attention needs the keys and values of all previous tokens: the KV cache (Lecture 9). For Llama 3 8B that is 128 KB per token, or 17.2 GB for one 128k-token sequence, more than the weights (16 GB). Online softmax and FlashAttention do not shrink it. Grouped-query attention (Lecture 5), cache quantization and eviction do, and state-space models (§7) avoid it altogether.
4. Trained models fail to extrapolate
4.1 The problem
Most models are trained on shorter sequences (e.g. 4k tokens), and longer documents are truncated or chunked. What happens when a test sequence is longer than any training sequence? It depends on the position encoding (slides; Lecture 5):
- Learned absolute embeddings: impossible. Positions beyond the table were never trained.
- Fixed absolute (sinusoidal): the vectors exist, but they are out of distribution: “very bad”.
- Relative (RoPE, ALiBi): should extrapolate better in theory, “but not really in practice”.
The slides’ example (Fu et al., 2024): Llama 2 with a 32k context (RoPE) answers questions about sequences up to about 40k, and fails beyond.
4.2 Measured: four position schemes
Demo 03 trains Lecture 5’s Transformer (2 layers, d = 64) on 64-token needle documents with each position scheme. All four reach 100% at the training length:
| position scheme | 64 tokens | 128 | 256 | 512 |
|---|---|---|---|---|
| learned absolute | 100% | 0.0% | 0.0% | 0.0% |
| sinusoidal (fixed absolute) | 100% | 3.0% | 4.5% | 2.5% |
| RoPE (relative) | 100% | 73.5% | 51.5% | 9.0% |
| none (NoPE) | 100% | 2.0% | 0.0% | 0.0% |
The absolute schemes collapse immediately, as the slides predict. RoPE extrapolates furthest, but far from perfectly. “No positions at all” is no free pass. A causal model without position vectors must infer positions from the mask (Haviv et al., 2022), and what it infers changes with length.
4.3 Measured: what RoPE generalizes over
RoPE’s attention scores depend only on relative positions. Does the document’s length matter, or only the distance between the needle and the question? Demo 03 Part C splits RoPE’s results by both (training documents put the needle at most 57 tokens before the question):
| length | distance ≤ 60 | 61–120 | 121–250 | 251+ |
|---|---|---|---|---|
| 128 | 92.7% | 85.9% | 10.0% | — |
| 256 | 85.0% | 67.5% | 35.0% | — |
| 512 | 40.0% | — | 4.4% | 0.0% |
Both matter.
- Accuracy falls with distance: at 256 tokens, 85% when the needle is within the trained distance, 35% at 121–250.
- It also falls with length at a short distance: 93% at 128 tokens, 40% at 512. Plausibly, with more tokens to attend over, the softmax spreads its mass more thinly.
- New absolute positions are harmless under RoPE; new distances and longer contexts are not.
By depth, a needle that opens a long document is usually missed (0–28%), and one right before the question is usually found. This is not quite “lost in the middle”: our tiny model is lost at the start. The phenomenon to watch is position-dependent retrieval, whatever its shape.
5. Extending the context: training and RoPE scaling
5.1 Training with long context
The dependable fix is to train on long documents (Fu et al., 2024; slides):
- continue pretraining at the target length;
- upsample long documents, while keeping the domain mixture (upsample long documents within each domain, rather than over-representing domains that happen to have long documents, like books).
They extend Llama 2 to 128k context with a few billion tokens of such data.
5.2 RoPE scaling
RoPE rotates each pair of query/key dimensions by the angle , with and base . The structure is periodic:
- fast pairs (small ) complete many turns within the training length, so longer inputs bring no new angles;
- slow pairs (large ) never complete a turn in training, so longer inputs produce angles they have never seen.
Two ways to bring long inputs back into the trained range (slides):
- Adjusted base frequency (ABF; Xiong et al., 2023): increase the base , which slows every rotation, most of all the slow pairs. Llama 2 Long raised it to 500,000, and Llama 3 trains with 500,000 from the start.
- Position interpolation (PI; Chen et al., 2023): multiply every position by a constant (train length / target length), so the longest new position maps onto a trained one.
Computed (demo 04 Part A; head dimension 16, training distances 1–63):
| pair | trained angles | angle at distance 255 | PI: distance 1 | ABF (base 50,000): at 255 | |
|---|---|---|---|---|---|
| 0 | 1.0000 | 1.00 – 63.0 (wraps) | 255.0 (seen) | 0.25 | 255.0 |
| 3 | 0.0316 | 0.03 – 1.99 | 8.06 (new) | 0.008 | 4.41 |
| 7 | 0.0003 | 0.0003 – 0.020 | 0.081 (new) | 0.0001 | 0.020 |
Plain RoPE’s problem sits in the slow pairs. The two remedies behave differently:
- PI fixes the slow pairs but disturbs the fast ones. Neighbouring tokens now look “0.25 positions apart”, a combination of angles training never produced.
- ABF leaves pair 0 untouched and slows the slow pairs back into range. This is the idea behind “NTK-aware” scaling and YaRN (Peng et al., 2023), which change low frequencies and keep high ones.
Measured (demo 04 Parts B–C, needle accuracy):
| model | 64 | 128 | 256 | 512 |
|---|---|---|---|---|
| RoPE as trained | 100% | 73.5% | 51.5% | 9.0% |
| PI at test time | 2.0% | 0.5% | 1.0% | 0.5% |
| ABF at test time | 99.0% | 96.5% | 68.0% | 36.0% |
| + 300 steps on 256-token documents, RoPE as is | 100% | 89.5% | 94.0% | 40.5% |
| + 300 steps, PI | 8.5% | 7.5% | 4.0% | 3.0% |
| + 300 steps, ABF | 96.5% | 98.0% | 97.0% | 77.5% |
- A little long-document training does most of the work: 51.5% → 94.0% at 256 tokens after 2,400 documents.
- ABF helps without any training, and most with it. It reaches 77.5% at 512 tokens, twice the length it was fine-tuned on.
- PI broke this small model. It fails at its own training length, and 300 steps do not repair it (1,000 steps at a higher learning rate reached ~40–60% in a side test). Chen et al. report PI working well on 7B–65B models after ~1,000 steps. A 2-layer model with 16-dimensional heads depends heavily on its few fast dimensions, which is the weakness the angle table shows.
6. Transformer modifications
The slides list four families and skipped them in lecture for time. In brief:
- Sparse attention (Child et al., 2019): each position attends to a strided subset of earlier positions (every -th), plus a local window. The cost is instead of .
- Segment recurrence and sliding windows (Transformer-XL, Dai et al., 2019): attend to cached hidden states of the previous segment without backpropagating into them, like truncated BPTT for RNNs. Mistral’s sliding-window attention (Jiang et al., 2023) attends to a fixed window per layer; stacked layers reach further.
- Compressing past states (Compressive Transformer, Rae et al., 2019): compress older memories with a strided function and keep attending to them.
- Low-rank approximation: project keys and values to a fixed length (Linformer, Wang et al., 2020), or approximate the attention matrix from sampled landmarks (Nyströmformer, Xiong et al., 2021).
All trade exactness for cost. FlashAttention’s success, exact attention made memory-efficient, reduced their appeal for moderate lengths. The next section’s alternative gives up attention altogether.
7. Transformer alternatives: state-space models
7.1 Recurrence and convolution, revisited
- RNNs (Lecture 4) have an unbounded context and memory-efficient inference (a single hidden state), but are hard to parallelize in training: step needs step .
- Convolutions compute every position from a local window at once, which is parallel, but the context is bounded by the kernel width.
Structured state-space models (Gu et al., 2021) combine both: computed like an RNN at inference (fast), like a convolution in training (parallel).
7.2 The state-space model
A continuous-time linear system with state :
Discretize with step size (zero-order hold: hold the input constant over each step):
That is an RNN: the recurrent view, with constant memory per generated token. Unroll it:
That is a convolution: the convolution view. With FFTs it computes every position at once, in parallel, with an unbounded context.
Measured (demo 05 Part A): an S4D layer computed both ways agrees to 2.4e-07.
S4 (Gu et al., 2021) gives a special structure (from HiPPO, Gu et al., 2020) that retains a compressed memory of the whole past, and computes the kernel efficiently. The diagonal version S4D (Gu et al., 2022) uses complex . A complex matters:
- its modes oscillate, so their sum can form a sharp delay;
- in a first version of our code, a real-valued (smooth decays only) could not even learn to copy.
7.3 Mamba: selective state spaces
S4 is time-invariant: the same at every step, whatever the input. It cannot decide, based on content, what to remember and what to ignore. Mamba (Gu & Dao, 2023) makes the SSM selective (“S6”):
How the input-dependent quantities act:
- A large writes into the state and forgets the old state (“remember this”).
- A small keeps the state and ignores (“skip this”).
- and choose what is written and what is read.
Input-dependent parameters break the convolution view: there is no single kernel. Training is parallelized instead with a scan:
- composing two steps of gives another step of the same form, ;
- so the whole sequence can be computed in rounds of a parallel prefix computation (Blelloch, 1990).
Measured (Part B): a 4,096-step recurrence in 12 rounds, equal to the loop to 7e-07. Mamba fuses this into one hardware-aware GPU kernel that keeps the expanded state in SRAM, the same idea as FlashAttention.
The Mamba block combines:
- an input projection to two streams;
- a short causal convolution;
- the selective SSM;
- a SiLU gate from the second stream;
- an output projection.
It replaces both the attention and the MLP of a Transformer block. Mamba reports strong results on text, the human genome and audio. Mamba-3B matches Transformers twice its size, and generation throughput is about 5× higher.
7.4 Measured: what selectivity buys
The Mamba paper’s selective copying task (demo 05): the input has 32 positions, 4 of which hold symbols at random places; the model must output the 4 symbols in order. Plain copying puts the symbols at fixed positions.
| model | copying (fixed spacing) | selective copying |
|---|---|---|
| S4 (time-invariant) | 100% | 27.2% (73.9% of symbols) |
| Mamba (selective) | — | 98.6% |
| attention (Transformer) | — | 99.6% |
(Share of 500 test sequences with all 4 symbols right; chance 1 in 4,096.)
A convolution can learn “output what came 32 steps ago”, but not “output the non-blank tokens, wherever they were”. That needs content-based selection, which Mamba has and S4 lacks.
Does the trained Mamba actually use it? Part D freezes its input-dependent quantities to their averages:
| frozen | all 4 right |
|---|---|
| nothing | 98.6% |
| Δ | 0.0% |
| B | 42.2% |
| C | 0.2% |
| Δ, B and C | 0.0% (12.7% of symbols = chance) |
Selection is essential, yet invisible in averages: Mamba’s mean is about the same at symbols and blanks (0.97×, 0.91×). The selection is spread over channels and directions. An analysis that only looked at averages would have concluded the opposite.
7.5 Recap: what SSMs trade
- For: linear time in sequence length; constant memory per generated token. Computed (Part E): a Mamba-2.8B-like model carries 12.5 MB of state at any length, against a 32.8 GB KV cache for a similar Transformer at 100k tokens.
- Against: everything the model will need must fit into a fixed-size state; attention can look back at any token exactly. Exact recall from long contexts remains harder for pure SSMs. Hybrids that interleave attention and SSM layers (e.g. Jamba, 2024) aim for both.
8. Summary
- The costs. Attention’s compute and memory grow quadratically; memory traffic between HBM and SRAM is the practical bottleneck.
- Computed: a Llama 3 8B-sized layer’s score matrices take 1.1 TB at 128k tokens.
- Online softmax. A running max and sum , rescaled by , give the exact softmax chunk by chunk.
- Measured: chunked attention equals naive attention to 6e-07, with linear instead of quadratic memory (11 MB vs 575 MB at 4,096 tokens).
- FlashAttention and ring attention. FlashAttention tiles the computation into SRAM; Dao et al.’s model gives 5.6–6× fewer HBM accesses at . Ring attention passes K/V blocks around devices.
- Measured: exact; the zigzag layout balances causal work (57% of contiguous time).
- Computed: communication hides above ~1,300 tokens per device (NVLink).
- Extrapolation. Absolute positions fail immediately beyond the training length; RoPE degrades with distance and with length.
- Measured: learned 0%, sinusoidal 3%, RoPE 73.5% at 2×.
- Extension. Continued training on long documents is the dependable fix; ABF (a larger base) works best here; PI disturbs the fast dimensions.
- Measured, after 300 steps: ABF 97% at 4×, 77.5% at 8×; PI 4%.
- State-space models. One linear SSM is an RNN and a convolution. Mamba makes it selective and trains it with a parallel scan.
- Measured: S4 copies (100%) but cannot copy selectively (27%); Mamba can (98.6%), and freezing its Δ breaks it (0%).
- Constant inference state vs a growing KV cache.
Common pitfalls
- Measuring FLOPs instead of memory traffic. FlashAttention does more FLOPs and runs faster.
- Assuming RoPE extrapolates. It degrades with unseen distances and longer contexts; test at the lengths and depths you need.
- Testing long context with one needle only. Retrieval of one fact says little about aggregation or reasoning over the context (RULER, Oolong).
- Applying position interpolation without training. It moves even neighbouring tokens to unseen angles; budget a fine-tuning phase (or prefer a base-frequency change).
- Upsampling “long-document domains”. It shifts the data mixture; upsample long documents within each domain.
- Contiguous blocks with causal context parallelism. The last device does all the work; interleave.
- Reading a selective model from averages. Ablate instead.
- Forgetting the KV cache. Long-context inference is often limited by cache memory, not by attention’s compute.
Exercises
-
Online softmax. Compute the softmax of in two chunks and with a running max and sum. Show the rescaling step.
Answer
Chunk 1: m = 2, ℓ = e⁰ + e⁻¹ = 1.3679. Chunk 2: m' = 4; ℓ ← 1.3679 · e^{2−4} + e⁰ + e⁻¹ = 0.1851 + 1 + 0.3679 = 1.5530. Probabilities: e^{x−4}/1.5530 = [0.0871, 0.0321, 0.6439, 0.2369]. They sum to 1 and equal softmax([2, 1, 4, 3]). -
Memory. For , heads, , bf16: how big are one layer’s attention scores? What does chunked attention with 1,024 × 1,024 blocks need instead (per head, ignoring )?
Answer
32 × 32,768² × 2 bytes = 68.7 GB. One block of scores is 1,024² × 2 bytes = 2 MB (per head being processed), plus the running statistics (m, ℓ: 32,768 × 2 numbers) and the output accumulator (32,768 × d) — megabytes instead of tens of gigabytes. -
Ring attention balance. With 8 devices and causal attention over contiguous blocks, how many of the 8 blocks does device (0-indexed) need? With the zigzag layout over 16 chunks, show each device needs the same amount of work.
Answer
Contiguous: device i needs blocks 0..i, so i + 1 blocks (the diagonal one half-masked): 1, 2, …, 8; the last device works ~8× as long as the first, and each ring step waits for it. Zigzag: device i holds chunks i and 15 − i. Chunk i needs chunks 0..i (i + 1 of them), chunk 15 − i needs 16 − i: together 17 chunk-pairs' worth of work for every i. -
RoPE angles. With and base 10,000, the slowest pair has . A model trained on 4,096 tokens sees angles up to what for this pair? At 32,768 tokens? What base keeps the 32k angle within the trained range?
Answer
4,096 × 1.15e-4 ≈ 0.47 rad; 32,768 × 1.15e-4 ≈ 3.8 rad (never seen, and it has not wrapped). We need 32,768 · θ' ≤ 4,096 · θ, i.e. θ' ≤ θ / 8. With θ' = b'^(−126/128): b' ≥ 10,000 · 8^(128/126) ≈ 83,000 — an 8× longer context needs a base roughly 8× larger for this pair (Llama 2 Long went to 500,000 for 32k from 4k, with margin). -
Why ABF over PI? Explain in two sentences why multiplying positions by 1/8 (PI) can hurt short-range modeling while raising the base barely does.
Answer
PI scales every angle, including those of the fastest pairs that tell adjacent tokens apart, so neighbours now look 1/8 of a position apart — an input pattern never seen in training. Raising the base changes θ_j = b^(−2j/d) by a factor that grows with j: the fastest pair (j = 0) is untouched and only slow pairs are slowed, which is exactly where unseen angles came from. -
Two views of an SSM. For a scalar SSM with , , , compute for input by the recurrence, then give the convolution kernel and check.
Answer
Recurrence: h₀ = 1, y₀ = 2; h₁ = 0.5, y₁ = 1; h₂ = 0.25 + 3 = 3.25, y₂ = 6.5. Kernel K = (C B̄, C Ā B̄, C ² B̄) = (2, 1, 0.5). Convolution: y₀ = 2·1 = 2; y₁ = 2·0 + 1·1 = 1; y₂ = 2·3 + 1·0 + 0.5·1 = 6.5. Same. -
Selectivity. Why can a time-invariant SSM solve copying with fixed spacing but not selective copying? What does Mamba change, and what does it lose?
Answer
With fixed spacing the output at position L + k depends on the input at position k: a fixed lag, which one convolution kernel can represent (a delay). With random spacing, which input to output depends on the content (where the non-blank tokens are), and a time-invariant system treats every position identically. Mamba makes Δ, B, C functions of the input, so the state can skip blanks and store symbols; it loses the convolution view (no single kernel), and so needs a scan for parallel training. -
Memory at inference. A Transformer with 32 layers, 8 KV heads of dimension 128, generates in bf16. How long can the context get before its KV cache exceeds 8 GB? A Mamba model with 64 layers, , : how big is its state?
Answer
KV per token: 2 × 32 × 8 × 128 × 2 bytes = 131,072 bytes = 128 KB; 8 GB / 128 KB ≈ 61,000 tokens. Mamba state: 64 × 4,096 × 16 numbers ≈ 4.2M numbers ≈ 8.4 MB in bf16 (plus a small convolution buffer), independent of context length.
Related assignment (concepts only)
- Assignments 3–4: if your project needs long inputs:
- measure memory and speed with FlashAttention (
scaled_dot_product_attention) before redesigning anything; - evaluate with needles at many depths and with aggregation questions;
- if you extend a model’s context, plan a continued-training phase on long, in-domain documents, and compare RoPE base changes.
- measure memory and speed with FlashAttention (
- These notes do not provide assignment code.
Further reading
- M. Rabe, C. Staats, “Self-attention Does Not Need O(n²) Memory”, 2021 (course reading); A. Gu, T. Dao, “Mamba: Linear-Time Sequence Modeling with Selective State Spaces”, 2023 (course reading).
- T. Dao et al., “FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness”, NeurIPS 2022; T. Dao, “FlashAttention-2”, 2023; M. Milakov, N. Gimelshein, “Online normalizer calculation for softmax”, 2018.
- H. Liu, M. Zaharia, P. Abbeel, “Ring Attention with Blockwise Transformers for Near-Infinite Context”, 2023; N. Tazi et al., The Ultra-Scale Playbook (context parallelism), 2025.
- Y. Fu et al., “Data Engineering for Scaling Language Models to 128K Context”, ICML 2024; S. Chen et al., “Extending Context Window of Large Language Models via Positional Interpolation”, 2023; W. Xiong et al., “Effective Long-Context Scaling of Foundation Models”, 2023; B. Peng et al., “YaRN”, 2023.
- N. Liu et al., “Lost in the Middle”, TACL 2024; C. Hsieh et al., “RULER”, 2024; A. Bertsch et al., “In-Context Learning with Long-Context Models”, 2024; A. Bertsch et al., “Oolong”, 2025; Y. Tay et al., “Long Range Arena”, 2020; U. Shaham et al., “SCROLLS”, 2022.
- A. Gu et al., “Efficiently Modeling Long Sequences with Structured State Spaces” (S4), ICLR 2022; A. Gu et al., “HiPPO”, NeurIPS 2020; A. Gu et al., “On the Parameterization and Initialization of Diagonal State Space Models” (S4D), NeurIPS 2022; M. Grootendorst, “A Visual Guide to Mamba”, 2024.
- R. Child et al., “Generating Long Sequences with Sparse Transformers”, 2019; Z. Dai et al., “Transformer-XL”, ACL 2019; J. Rae et al., “Compressive Transformers”, ICLR 2020; S. Wang et al., “Linformer”, 2020; Y. Xiong et al., “Nyströmformer”, AAAI 2021.
Preview of Lecture 23 — Test-time scaling
This block has been about making models cheaper: fewer bits, more devices, sparse experts, linear-time sequence models. The last lecture spends compute deliberately at inference to get better answers:
- generating many candidates and choosing with verifiers or votes;
- refining answers with feedback;
- long chains of thought, and how to control their length.
Which of these pays off, when, and how far does it scale?
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| long context / sequence length | 长上下文 / 序列长度 |
| quadratic complexity | 二次复杂度 |
| HBM / SRAM / memory bandwidth | 高带宽显存 / 片上缓存 / 内存带宽 |
| IO-aware algorithm / memory traffic | 感知读写的算法 / 访存量 |
| online softmax / running max / running sum | 在线 softmax / 运行最大值 / 运行和 |
| memory-efficient (chunked) attention / tiling / recomputation | 内存高效(分块)注意力 / 分块 / 重计算 |
| FlashAttention | FlashAttention(闪电注意力) |
| ring attention / context parallelism / zigzag layout | 环形注意力 / 上下文并行 / 之字形布局 |
| KV cache | 键值缓存 |
| needle in a haystack / lost in the middle / aggregation | 大海捞针 / 中间迷失 / 信息聚合 |
| length extrapolation / out of distribution | 长度外推 / 分布外 |
| learned / sinusoidal / rotary position embedding (RoPE) / no positional encoding (NoPE) | 可学习 / 正弦 / 旋转位置编码 / 无位置编码 |
| position interpolation (PI) / adjusted base frequency (ABF) / NTK-aware scaling | 位置插值 / 调整基频 / NTK 感知缩放 |
| continued pretraining / upsampling long documents | 继续预训练 / 上采样长文档 |
| sparse attention / sliding-window attention | 稀疏注意力 / 滑动窗口注意力 |
| segment recurrence (Transformer-XL) / compressive memory | 段级循环 / 压缩记忆 |
| low-rank approximation (Linformer, Nyströmformer) | 低秩近似 |
| state-space model (SSM) / S4 / HiPPO / S4D | 状态空间模型 / S4 / HiPPO / 对角 SSM |
| discretization / zero-order hold / step size Δ | 离散化 / 零阶保持 / 步长 Δ |
| recurrent view / convolution view / kernel | 循环视角 / 卷积视角 / 卷积核 |
| selective SSM (Mamba, S6) / selectivity | 选择性状态空间模型 / 选择性 |
| parallel scan / prefix sum | 并行扫描 / 前缀和 |
| selective copying | 选择性复制 |
| ablation | 消融 |
| hybrid architecture | 混合架构 |