Lecture 22 · Scaling Sequence Length

Advanced Natural Language Processing · Lecture 22。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

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 from code/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:

  1. Say where attention’s cost grows as O(s2)O(s^2) in compute and in memory, and why memory traffic (HBM ↔ SRAM) is the real bottleneck.
  2. Derive the online softmax, and explain how chunked attention, FlashAttention and ring attention compute exact attention without the s×ss \times s matrix.
  3. Explain why trained models fail to extrapolate beyond their training length, for learned, fixed and relative position encodings.
  4. Explain RoPE scaling: position interpolation and an adjusted base frequency. Say why continued training on long documents is the reliable fix.
  5. 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.
  6. 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

SectionIdeaDemo in code/lecture22/
§3.1–3.5the s2s^2 terms; online softmax; chunked attention; FlashAttention’s IO; KV cache01_attention_cost.py (+ attention_impl.py)
§3.6ring attention / context parallelism02_ring_attention.py
§4extrapolation failures, by length and distance03_extrapolation.py (+ long_lm.py)
§5RoPE scaling and continued training04_rope_scaling.py
§7S4, Mamba, the scan, selective copying05_state_space.py (+ ssm.py)

0.4 Notation

SymbolMeaning
ss (or NN, LL)sequence length
b,h,db, h, dbatch size, number of heads, model (or head) dimension
m,ℓ,om, \ell, orunning max, running sum, running output of the online softmax
MMsize of on-chip SRAM (elements)
PPnumber of devices in context parallelism
θj=b−2j/dk\theta_j = b^{-2j/d_k}RoPE frequency of dimension pair jj with base bb
A,B,C,ΔA, B, C, \Deltastate-space matrices and step size; Aˉ,Bˉ\bar A, \bar B their discretized versions

1. How long are sequences, and why is that hard?

The slides’ scale of things (in tokens):

contentlength
one sentence~20
one document100–10k
one book50k–300k
one video1.5k–1M (~300 per second)
one codebase20k–1B
one genome3B 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:

  1. compute exact attention without quadratic memory (§3);
  2. understand and fix models that break beyond their training length (§4–5);
  3. 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 O(s2)O(s^2) goes, and how to avoid materializing it

3.1 Attention’s complexity

For one layer with Q,K,V∈Rb×s×dQ, K, V \in \mathbb{R}^{b \times s \times d} (slides):

  • Compute: QK⊤QK^\top costs O(bs2d)O(b s^2 d), and so does multiplying the attention weights by VV.
  • Memory: the score and weight matrices take O(bs2)O(b s^2) per head, O(bs2h)O(b s^2 h) for hh heads, while the output is only O(bsd)O(b s d). Splitting into heads does not change the compute, but multiplies the score memory by hh.

Computed (demo 01 Part A, one layer of Llama 3 8B’s size, batch 1):

sequence lengthprojection FLOPsQK⊤+AVQK^\top + AV FLOPsattention sharescore matrices (bf16)
1,0248.6e101.7e1017%0.1 GB
16,3841.4e124.4e1276%17.2 GB
131,0721.1e132.8e1496%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 s×ss \times s 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 mm,

softmax(x)i=exi−m∑jexj−m,\mathrm{softmax}(x)_i = \frac{e^{x_i - m}}{\sum_j e^{x_j - m}},

and m=max⁡jxjm = \max_j x_j keeps every exponential ≤1\le 1. Read xx in chunks, keeping a running max mm and a running sum ℓ=∑exj−m\ell = \sum e^{x_j - m}. When a new chunk raises the max to m′m', rescale what you have:

ℓ←ℓ em−m′+∑j∈chunkexj−m′.\ell \leftarrow \ell\, e^{m - m'} + \sum_{j \in \text{chunk}} e^{x_j - m'}.

For attention, also keep the running weighted sum of values oo and rescale it the same way: o←o em−m′+∑jexj−m′vjo \leftarrow o\, e^{m - m'} + \sum_j e^{x_j - m'} v_j. At the end o/ℓo / \ell is exactly the attention output.

Measured by hand (demo 01 Part B), for x=[1,3∣2,5∣0.5]x = [1, 3 \mid 2, 5 \mid 0.5]:

chunkrunning maxrunning sum
1 331.1353
2 551.2034
0.551.2145

The final probabilities equal torch.softmax to four decimals. The memory needed: the numerator oo is O(bsd)O(bsd) and the denominator ℓ\ell is O(bsh)O(bsh) (slides); the s×ss \times s 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 lengthnaivechunkedratiomax difference
2562.7 MB1.6 MB2×3.9e-07
1,02436.7 MB3.2 MB11×4.8e-07
4,096574.6 MB11.1 MB52×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 QQ, KK, VV 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 Q,KQ, K instead of storing them: a few more FLOPs, far less memory traffic.

Dao et al. prove that standard attention needs Θ(Nd+N2)\Theta(Nd + N^2) HBM accesses, and FlashAttention Θ(N2d2/M)\Theta(N^2 d^2 / M) for SRAM size MM. Computed with their model (demo 01 Part D, M=100,000M = 100{,}000 elements):

sequence NNhead dimfewer HBM accesses
4,096645.6×
65,536646.0×
65,5361281.5×

FlashAttention’s speedup comes from memory traffic, not fewer FLOPs. Its memory is linear in ss, 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 PP devices holds one block of queries and the matching block of keys and values;
  • in each of PP 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 PP 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 scheme64 tokens128256512
learned absolute100%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):

lengthdistance ≤ 6061–120121–250251+
12892.7%85.9%10.0%—
25685.0%67.5%35.0%—
51240.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 jj of query/key dimensions by the angle (position)×θj(\text{position}) \times \theta_j, with θj=b−2j/dk\theta_j = b^{-2j/d_k} and base b=10,000b = 10{,}000. The structure is periodic:

  • fast pairs (small jj) complete many turns within the training length, so longer inputs bring no new angles;
  • slow pairs (large jj) 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 bb, 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 jjθj\theta_jtrained anglesangle at distance 255PI: distance 1ABF (base 50,000): at 255
01.00001.00 – 63.0 (wraps)255.0 (seen)0.25255.0
30.03160.03 – 1.998.06 (new)0.0084.41
70.00030.0003 – 0.0200.081 (new)0.00010.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):

model64128256512
RoPE as trained100%73.5%51.5%9.0%
PI at test time2.0%0.5%1.0%0.5%
ABF at test time99.0%96.5%68.0%36.0%
+ 300 steps on 256-token documents, RoPE as is100%89.5%94.0%40.5%
+ 300 steps, PI8.5%7.5%4.0%3.0%
+ 300 steps, ABF96.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 nn-th), plus a local window. The cost is O(ss)O(s\sqrt{s}) instead of O(s2)O(s^2).
  • 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 tt needs step t−1t-1.
  • 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 h(t)∈RNh(t) \in \mathbb{R}^N:

h′(t)=A h(t)+B x(t),y(t)=C h(t).h'(t) = A\, h(t) + B\, x(t), \qquad y(t) = C\, h(t).

Discretize with step size Δ\Delta (zero-order hold: hold the input constant over each step):

Aˉ=eΔA,Bˉ=(ΔA)−1(eΔA−I) ΔB,ht=Aˉht−1+Bˉxt,yt=Cht.\bar A = e^{\Delta A}, \qquad \bar B = (\Delta A)^{-1}(e^{\Delta A} - I)\, \Delta B, \qquad h_t = \bar A h_{t-1} + \bar B x_t, \qquad y_t = C h_t.

That is an RNN: the recurrent view, with constant memory per generated token. Unroll it:

yt=∑ℓ≥0CAˉℓBˉ xt−ℓ=(Kˉ∗x)t,Kˉ=(CBˉ,  CAˉBˉ,  CAˉ2Bˉ,… ).y_t = \sum_{\ell \ge 0} C \bar A^{\ell} \bar B\, x_{t-\ell} = (\bar K * x)_t, \qquad \bar K = (C\bar B,\; C\bar A\bar B,\; C\bar A^2 \bar B, \dots).

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 AA 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 An=−12+iπnA_n = -\tfrac12 + i\pi n. A complex AA matters:

  • its modes oscillate, so their sum can form a sharp delay;
  • in a first version of our code, a real-valued AA (smooth decays only) could not even learn to copy.

7.3 Mamba: selective state spaces

S4 is time-invariant: the same Aˉ,Bˉ,C\bar A, \bar B, C 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”):

Δt=softplus(WΔxt+b),Bt=WBxt,Ct=WCxt.\Delta_t = \mathrm{softplus}(W_\Delta x_t + b), \qquad B_t = W_B x_t, \qquad C_t = W_C x_t.

How the input-dependent quantities act:

  • A large Δt\Delta_t writes xtx_t into the state and forgets the old state (“remember this”).
  • A small Δt\Delta_t keeps the state and ignores xtx_t (“skip this”).
  • BtB_t and CtC_t 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 ht=atht−1+bth_t = a_t h_{t-1} + b_t gives another step of the same form, (a2a1,  a2b1+b2)(a_2 a_1,\; a_2 b_1 + b_2);
  • so the whole sequence can be computed in log⁡2L\log_2 L 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.

modelcopying (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:

frozenall 4 right
nothing98.6%
Δ0.0%
B42.2%
C0.2%
Δ, B and C0.0% (12.7% of symbols = chance)

Selection is essential, yet invisible in averages: Mamba’s mean Δ\Delta 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

  1. The s2s^2 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.
  2. Online softmax. A running max mm and sum ℓ\ell, rescaled by em−m′e^{m - m'}, 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).
  3. FlashAttention and ring attention. FlashAttention tiles the computation into SRAM; Dao et al.’s model gives 5.6–6× fewer HBM accesses at d=64d = 64. 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).
  4. 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×.
  5. 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%.
  6. 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

  1. Online softmax. Compute the softmax of [2,1,4,3][2, 1, 4, 3] in two chunks [2,1][2, 1] and [4,3][4, 3] with a running max and sum. Show the rescaling step.

    AnswerChunk 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]).
  2. Memory. For b=1b = 1, h=32h = 32 heads, s=32,768s = 32{,}768, bf16: how big are one layer’s attention scores? What does chunked attention with 1,024 × 1,024 blocks need instead (per head, ignoring Q,K,VQ, K, V)?

    Answer32 × 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.
  3. Ring attention balance. With 8 devices and causal attention over contiguous blocks, how many of the 8 blocks does device ii (0-indexed) need? With the zigzag layout over 16 chunks, show each device needs the same amount of work.

    AnswerContiguous: 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.
  4. RoPE angles. With dk=128d_k = 128 and base 10,000, the slowest pair has θ=10,000−126/128≈1.15×10−4\theta = 10{,}000^{-126/128} \approx 1.15 \times 10^{-4}. 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?

    Answer4,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).
  5. 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.

    AnswerPI 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.
  6. Two views of an SSM. For a scalar SSM with Aˉ=0.5\bar A = 0.5, Bˉ=1\bar B = 1, C=2C = 2, compute y0,y1,y2y_0, y_1, y_2 for input x=(1,0,3)x = (1, 0, 3) by the recurrence, then give the convolution kernel and check.

    AnswerRecurrence: 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.
  7. 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?

    AnswerWith 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.
  8. 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, E=4,096E = 4{,}096, N=16N = 16: how big is its state?

    AnswerKV 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.
  • 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.
  • 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内存高效(分块)注意力 / 分块 / 重计算
FlashAttentionFlashAttention(闪电注意力)
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混合架构
← 返回课程目录