Lecture 16 · Large Language Models (guest lecture: Hao Liu)

Deep Unsupervised Learning · Lecture 16。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

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

本篇目录

Maps to: UC Berkeley CS294-158 Deep Unsupervised Learning (Spring 2024), Lecture 8 · Thu 3/7/2024 · Large Language Models (guest lecture, 138 slides): the autoregressive language model and maximum likelihood, why unsupervised, tokens, scaling compute (LSTMs vs Transformers, the sentiment neuron), pre-training objectives and architectures, compute cost C=6ND(1+s/6d)C = 6ND(1 + s/6d), the compute-optimal split between parameters and tokens (Kaplan et al.; Chinchilla), inference-optimal training, “loss predicts performance”; large context (Blockwise Parallel Transformer, Ring Attention, the Large World Model, Gemini 1.5), FlashAttention, retrieval (RETRO); alternatives to attention (sliding windows, state-space models, Based, Griffin); the KV cache, memory bandwidth, KV-cache compression, multi-query and grouped-query attention, mixture of experts (Mixtral); reasoning (scratchpads, chain-of-thought, zero-shot chain-of-thought, process supervision, RLHF), code generation (Codex, AlphaCode), pre-training data (the Pile, LLaMA’s mix, RedPajama, OpenLLaMA); sharding on TPUs / GPUs (developed in Lecture 23). Basis: The slides are a tour of results at a scale no laptop can approach. These notes keep the mechanisms and test them in miniature on a text whose irreducible loss is known exactly — lines of 3-digit additions, 19.93 bits of entropy per line — so that a scaling-law fit can be checked against the truth; they verify that blockwise and ring attention are exact, count the memory and bandwidth that limit long contexts and inference, train multi-query, grouped-query and mixture-of-experts variants, and measure what writing out intermediate steps does for a small model. Code: code/lecture16/ (4 scripts + llm_tools.py; PyTorch (CPU); 30 + 15 small language models, cached; the scaling grid is about an hour of CPU time, the other scripts 5–40 minutes) Reading time: 3.5 hours including running the code


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Write the language-modelling objective and estimate training compute C≈6NDC \approx 6ND; explain what a scaling law L(N,D)L(N, D) is, how the compute-optimal NN and DD follow from it, and why Kaplan et al. and Chinchilla disagreed.
  2. Explain inference-optimal training (smaller models on more tokens) and why “loss predicts performance”.
  3. Explain how blockwise attention (online softmax) and Ring Attention compute exact attention with memory linear in the context, and when communication hides behind computation.
  4. Say what sliding-window attention, state-space / linear attention models and hybrids gain and lose — especially for recall.
  5. Compute KV-cache sizes, explain why decoding is memory-bandwidth bound, and what MQA / GQA and mixture-of-experts layers trade.
  6. Explain why scratchpads / chain-of-thought help small models, and how sampling + verification (AlphaCode, process supervision) converts inference compute into accuracy.

0.2 Prerequisites and scope

AssumedIntroduced hereDeveloped later
Lecture 4 (Transformers, KV caching, tokenizers, linear recurrences)scaling laws, compute accountingmultimodal LLMs (Lecture 22)
Lecture 2 (maximum likelihood = cross-entropy = code length)blockwise / ring attention, memory formulasdata / tensor / FSDP parallelism in detail (Lecture 23)
Lecture 15 (BERT, GPT objectives)MQA, GQA, uptraining, MoE, scratchpads, verifiers

0.3 Map

§1  the language model and its objective
§2  compute and scaling laws                                     ← code 01
§3  data
§4  long context: blockwise attention, Ring Attention             ← code 02, Parts 1-3
§5  alternatives and complements: sliding windows, SSMs, hybrids, retrieval   ← code 02, Part 4
§6  inference: the KV cache, memory bandwidth, MQA and GQA       ← code 03, Parts 1-2
§7  mixture of experts                                           ← code 03, Part 3
§8  reasoning and inference-time compute                         ← code 04
§9  sharding (pointer to Lecture 23)
§10 summary   §11 pitfalls   §12 exercises   §13 further reading   §14 next lecture

0.4 Notation

NN parameters (Kaplan et al.’s convention: non-embedding parameters), DD training tokens, CC training FLOPs; ss context length, dd (or hh) model width, bb batch size, LL layers; L(N,D)L(N, D) the held-out loss; EE the irreducible loss. Our “tokens” are characters.

0.5 How the experiments are run

  • The corpus. Lines “357+468=825”: two operands uniform in 0..999 and their sum. The operands carry log⁡2106\log_2 10^6 = 19.93 bits per line and the sum is determined, so 19.93 bits per line is the exact floor of any model; the rest of a model’s loss is how badly it knows addition. Lines are packed whole into 64-character sequences; every run sees fresh lines (no repetition), as in the compute-optimal studies.
  • Models. Decoder-only Transformers built from primitives (pre-LayerNorm blocks, learned positions, character vocabulary), 3K to 790K non-embedding parameters; AdamW with warm-up and a cosine schedule matched to each run’s token budget (Chinchilla’s point: an unmatched schedule distorts the scaling curve).
  • Everything is seeded and single-threaded; reruns print identical numbers.

1. The language model and its objective

A language model is a probability distribution over token sequences, almost always autoregressive: pθ(x1,…,xT)=∏tpθ(xt∣x<t)p_\theta(x_1, \ldots, x_T) = \prod_t p_\theta(x_t \mid x_{<t}), trained by maximum likelihood — minimizing the cross-entropy, i.e. the code length of the data (Lecture 2). The slides’ arguments for next-token prediction: it predicts the future; every token is a supervision signal; it is natural for conversation. The lifecycle: pre-training (large-scale unsupervised learning: LLaMA used 1.5 trillion tokens for 7–70 billion parameters), fine-tuning for tasks, and learning from feedback (human preferences, execution results). Why unsupervised: there is far more unlabeled text, and it generalizes better.

Tokens: bytes are general but long; characters make words long; words cannot share meaning between “dog” and “dogs”; sub-words by byte-pair encoding (merge the most frequent pair until the vocabulary has the desired size; Lecture 4) are the standard.

Why Transformers. Radford et al. (2017) trained an LSTM on Amazon reviews and found a single “sentiment neuron” — unsupervised next-character prediction had discovered sentiment. But LSTMs scale poorly with context: Kaplan et al. (2020) show Transformers using long contexts better and pulling ahead as compute grows; attention reaches any past token without forgetting, and the large feed-forward layers parallelize well. Comparisons of objectives (Wang et al., 2022: causal decoder, prefix LM, masked / encoder–decoder) and of architectures (Tay et al., 2022) on the slides find the plain causal-decoder Transformer competitive or best at scale — and it is what GPT and LLaMA use.


2. Compute and scaling laws

2.1 Compute

A forward and backward pass costs about 6 FLOPs per parameter per token (2 for the forward multiply-adds, 4 for the backward), plus attention’s share: C=6ND(1+s/6d)C = 6ND(1 + s/6d), so for s≪6ds \ll 6d, C≈6NDC \approx 6ND. The slides’ example: LLaMA-7B on 2 trillion tokens is 6×7×109×2×1012=8.4×10226 \times 7\times10^9 \times 2\times10^{12} = 8.4 \times 10^{22} FLOPs. Shall I spend more compute on data or on the model?

2.2 Scaling laws and the compute-optimal split

Empirically, loss follows power laws in each factor when the other is not limiting. Chinchilla (Hoffmann et al., 2022) fits

L(N,D)=E+ANα+BDβ,L(N, D) = E + \frac{A}{N^\alpha} + \frac{B}{D^\beta},

where EE is the irreducible loss (the entropy of the text) and the two other terms are what a finite model and finite data cost. Minimizing LL under 6ND=C6ND = C gives Nopt∝CaN_{\text{opt}} \propto C^{a}, Dopt∝CbD_{\text{opt}} \propto C^{b} with a=β/(α+β)a = \beta/(\alpha + \beta), b=α/(α+β)b = \alpha/(\alpha + \beta) (Exercise 1). Kaplan et al. (2020) found a≈0.73a \approx 0.73 — spend compute mostly on parameters; Chinchilla found a≈0.49a \approx 0.49, b≈0.51b \approx 0.51 — scale both equally, about 20 tokens per parameter (the slides: “best to double the estimate”, 40×). The difference came largely from Kaplan’s fixed learning-rate schedule (not matched to each run’s length) and smaller models. Chinchilla (70B parameters, 1.4T tokens) beat Gopher (280B, 300B tokens) at the same compute. The slides’ practical advice: train different small models on different data sizes and fit the constants yourself — the coefficients depend on the data (DeepSeek’s fits differ again).

Inference-optimal training. Compute-optimal is optimal for training. A deployed model’s cost is per generated token, ∝N\propto N; LLaMA-7B was trained on about 7× its Chinchilla-optimal tokens — more training compute for a smaller, cheaper model. Loss predicts performance: LLaMA’s slides show downstream accuracy depending on the training loss, whatever the model size; DeepSeek predicted its large models’ loss from small runs.

2.3 Experiment: a scaling grid on a text with known entropy (script 01)

Six model sizes × five budgets, each run with its own schedule. Held-out bits per line (floor 19.93):

model (width, layers)ND = 1M2M4M8M16M characters
s1 (16, 1)3,28034.7132.6031.3230.5129.59
s2 (32, 2)25,40831.1330.4229.3227.8724.20
s3 (48, 2)56,54430.5729.3327.7923.5422.72
s4 (64, 3)149,95229.7328.0327.2120.6820.13
s5 (96, 3)335,52028.5926.9221.3820.6420.02
s6 (128, 4)793,08827.7424.9720.9320.0420.01

and the fraction of held-out lines whose answer is fully right:

model1M2M4M8M16M
s10.0%0.0%0.1%0.1%0.2%
s20.1%0.1%0.2%0.5%28.7%
s30.1%0.3%0.8%32.9%44.8%
s40.2%0.9%0.8%84.4%95.9%
s50.6%2.4%76.3%87.5%98.2%
s60.8%25.0%85.3%97.6%98.4%

Scaling runs and fits; loss predicts performance

The loss falls with both NN and DD — but not smoothly: each model learns addition at some point, with a drop of 5–7 bits and an accuracy jump from ~1% to 76–98%. Bigger models get there with fewer tokens (s5 at 4M, s4 at 8M, s2 only partly at 16M); the smallest never does.

Loss predicts performance. Sorting all 30 runs by held-out loss, the answer accuracy is monotone regardless of size and budget: above ~26 bits per line almost no answer is right (≤ 2.4%), below ~21 bits more than 75% are. The slides’ LLaMA plot, in miniature.

Fitting the law.

fitEE (bits / line)AAα\alphaBBβ\betarms error of log⁡L\log L
all five constants free5.9359.70.1491.63e30.3420.055
EE fixed to the true entropy19.933850.4641.06e60.8550.072

The unconstrained fit is good on the grid (rms 0.055 in log⁡L\log L) and wrong about the floor: it puts the irreducible loss at 5.93 bits per line, a third of the truth, and so predicts losses below the entropy just outside the grid — impossible for any model. A smooth power law with a free floor cannot represent “slowly, then suddenly”. Fixing EE at the known value fits almost as well with very different exponents.

The compute-optimal frontier (from the fit with EE fixed):

compute CC (FLOPs)NoptN_{\text{opt}}DoptD_{\text{opt}} (characters)tokens per parameterpredicted bits / line
101110^{11}6,5612,540,356387.229.96
101210^{12}29,1485,717,848196.224.95
101310^{13}130,02512,817,99998.622.44
101410^{14}577,68428,850,83149.921.19
101510^{15}2,566,56564,937,62725.320.56

Nopt∝C0.65N_{\text{opt}} \propto C^{0.65} (the free fit: C0.70C^{0.70}): on our task, a growing budget should go mostly into parameters — Kaplan-like, not Chinchilla’s 50/50 — and the tokens-per-parameter ratio is not a constant but falls from ~390 to ~25 over four orders of magnitude of compute. Our grid spans 2×10102\times10^{10} to 7.6×10137.6\times10^{13} FLOPs; beyond it all of this is extrapolation from fits that disagree. The general lesson is the slides’: the constants depend on the data and the training recipe, and must be fitted on your setting — and a fitted irreducible loss should be checked against any knowledge you have of the data’s entropy.

Inference-optimal (from the same fit): to reach 21.71 bits per line (the 25th percentile of our runs), the compute-optimal model has 270,775 parameters and needs 19.1M characters; a model 75% that size needs 27.3M characters — only 7% more training compute for 25% cheaper inference; half the size needs 77.9M (2.04× the compute); at 35% the target is out of reach (the model term alone exceeds it). Over-training a smaller model is cheap up to a point, then very expensive.


3. Data

Most pre-training text comes from Common Crawl (the Pile’s breakdown on the slides), filtered for quality and deduplicated; LLaMA’s mix up-weights curated sources such as Wikipedia, books, code and papers. RedPajama reproduced LLaMA’s data recipe openly, and OpenLLaMA, trained on it, matched LLaMA. The slides’ theme: data quality and mixture are as much a part of the recipe as the architecture. (Our corpus is the opposite extreme — perfectly clean and fully known — which is what lets §2.3 check a fitted EE.)


4. Long context: blockwise attention and Ring Attention

4.1 Why context is the bottleneck

Agents, world models, code bases, hyperlinked web pages and genomes need contexts far beyond 4K tokens. Standard attention materializes an s×ss \times s score matrix per head: memory O(s2)O(s^2). Memory-efficient attention / FlashAttention (Rabe & Staats; Dao et al., 2022) compute attention block by block with an online softmax, keeping per query only a running maximum, a running normalizer and a running weighted sum — exact, with memory linear in ss, and fast because it minimizes traffic between HBM and on-chip SRAM (FlashAttention-2: better work partitioning, query blocks in the outer loop). The Blockwise Parallel Transformer (Liu & Abbeel, 2023) also computes the feed-forward layer block by block, fused with attention: the slides’ accounting of the peak activation memory per layer — standard attention O(s2)O(s^2); memory-efficient attention max(4bch, 2bsh) plus the FFN’s 8bsh; BPT 2bsh, 4× smaller.

4.2 Ring Attention

Even linear memory runs out on one device. Ring Attention (Liu, Zaharia & Abbeel, 2024) splits the sequence into blocks across devices arranged in a ring: each device keeps its query block; key/value blocks travel around the ring, each device updating its online softmax with the block it currently holds while sending it on and receiving the next. After PP steps every query block has seen every key block — exact attention, with the context length scaling with the number of devices (the slides: 512× longer than BPT alone). The transfer of the next block is hidden behind the computation on the current one if

4c2d/F⏟compute per step≥4cd/B⏟send K and V (bf16)  ⟺  c≥F/B,\underbrace{4c^2d/F}_{\text{compute per step}} \ge \underbrace{4cd/B}_{\text{send K and V (bf16)}} \iff c \ge F/B,

with FF the device’s FLOP/s and BB the link bandwidth in bytes/s: the block must hold at least F/BF/B tokens. The Large World Model trained with it on million-token video and text, with near-perfect “needle in a haystack” retrieval at 1M tokens; Gemini 1.5 shows what such contexts enable (whole code repositories, long documents, translating Kalamang from a grammar book given in context).

4.3 Experiment (script 02, Parts 1–3)

Exactness (L = 1,024, d = 64, causal, float64): blockwise attention with blocks of 16, 64 and 256 differs from standard attention by at most 8.3×10−168.3\times10^{-16}, while holding 256, 4,096 or 65,536 score entries at once instead of 1,048,576.

Peak activation memory of one layer (hidden 4,096, 32 heads, batch 1, bf16):

context ssstandard attention + FFNmemory-efficient attention + FFNBPT (blockwise FFN too, cc = 2,048)
4,0961.00 GB0.25 GB0.12 GB
32,76864.00 GB2.00 GB0.50 GB
131,0721,024.00 GB8.00 GB2.00 GB
1,048,57665,536.00 GB64.00 GB16.00 GB
8,388,6084,194,304.00 GB512.00 GB128.00 GB

At a million tokens, scores would need 64 TB per layer; blocking brings it to 64 GB (the feed-forward layer now dominates), BPT to 16 GB — still too much for one 80 GB accelerator once all layers and weights are counted, which is where Ring Attention comes in.

Ring Attention, simulated on 2, 4, 8 and 16 devices: exact (≤ 8.3×10−168.3\times10^{-16}); with PP devices each holds a block of L/PL/P tokens (buffers for its queries, its output and three K/V blocks: 512 KiB at PP = 2 down to 64 KiB at PP = 16 in our tiny setting) and sends one K/V block per step. The overlap condition with approximate public numbers:

device and linkminimum block size c=F/Bc = F/B
A100: 312 TFLOP/s bf16, NVLink 300 GB/s1,040 tokens
A100: 312 TFLOP/s bf16, InfiniBand 25 GB/s12,480 tokens
TPU v4: 275 TFLOP/s bf16, ICI 100 GB/s per link2,750 tokens

Ring Attention is exact and free of communication cost only when each device’s share of the context is large — thousands of tokens per device — which is the regime it was built for.


5. Alternatives and complements to full attention

  • Retrieval (RETRO, Borgeaud et al., 2022): split the input into 64-token chunks, retrieve nearest neighbours (by frozen BERT embeddings) from a database of trillions of tokens, and attend to them through cross-attention; facts live in the database rather than in the weights, with the largest gains on code (GitHub) and books.
  • Sliding-window attention (Sparse Transformer; Longformer; Mistral 7B): each layer attends to the last ww tokens; information travels ww tokens further per layer.
  • State-space models (S4, Mamba): a recurrence with a fixed-size state — linear-time training, constant-memory inference (Lecture 4 §6); the slides: “unclear how it would scale compared with the transformer”.
  • Hybrids (Based: linear attention + small sliding windows; Griffin: gated linear recurrences + local attention): “fixed hidden size SSM underperforms Transformer; SSM plus attention can match Transformer on some tasks”, with a much smaller KV cache.

The weak point of fixed-size states is recall — retrieving a specific item from far back — which the “needle” tests measure.

5.1 Experiment: associative recall (script 02, Part 4)

A sequence of 2–16 (key, value) pairs, then a query key; predict its value (16 keys, 16 values; chance 6.25%). Two-layer models of width 64, 3,000 steps of 64 sequences:

model2 pairs4 pairs8 pairs16 pairs16 pairs: pair ≤ 8 tokens back16 pairs: > 8 back
full softmax attention100.0%100.0%100.0%100.0%99.9%100.0%
sliding window of 8 tokens99.3%83.4%27.0%16.6%35.4%10.1%
linear attention (fixed-size state)52.7%33.3%26.6%17.9%18.9%19.8%
hybrid: linear layer + sliding-window layer59.6%33.8%24.7%19.9%17.7%18.8%

Associative recall

Full attention retrieves from anywhere (an induction-head circuit, two layers). The sliding window works while the pair is within reach of its two layers and fails beyond. Linear attention with the elu + 1 feature map struggles even with 2 pairs: its state superimposes all key–value associations and retrieval by a soft dot product is too blurry. Plan vs reality: our hybrid did not recover recall (19.9% at 16 pairs) — Based and Griffin keep better feature maps (Taylor approximations of the exponential) or full-attention layers in the mix; ours has neither, which is the point of the slides’ warning.


6. Inference: the KV cache, memory bandwidth, MQA and GQA

6.1 Why decoding is slow

Generating token tt needs the keys and values of all previous tokens; recomputing them would cost O(t)O(t) per token, so they are kept in the KV cache (Lecture 4 §5): per token, 2×layers×KV heads×head dim2 \times \text{layers} \times \text{KV heads} \times \text{head dim} numbers. The slides’ point: the gap between compute and memory bandwidth keeps widening, and at small batch sizes decoding is dominated by loading — every step reads all the weights and the whole cache to produce one token, about 2 FLOPs per parameter for 2 bytes per parameter: an arithmetic intensity of ~1 FLOP/byte, while an A100 needs ~150 to be compute-bound. Remedies: compress the cache (KVQuant quantizes it to a few bits), share key/value heads — multi-query attention (MQA, Shazeer 2019: one K/V head for all query heads) and grouped-query attention (GQA, Ainslie et al., 2023: GG groups) — trading quality for speed; existing multi-head checkpoints can be uptrained to GQA/MQA by mean-pooling their K/V heads and training briefly (the paper: ~5% of the pre-training compute). Hardware helps too: HBM stacked on the processor raises bandwidth with die area.

6.2 The numbers for real models (script 03, Part 1)

model (bf16)KV cache / token4K context32K128K1Mtokens/s at 4K (batch 1)at 128K
LLaMA-2 7B (MHA)0.500 MB2.0 GB16.0 GB64.0 GB512.0 GB12924
LLaMA-2 70B (GQA, 8 KV heads)0.312 MB1.2 GB10.0 GB40.0 GB320.0 GB1411
Mistral 7B (GQA, 8 KV heads)0.125 MB0.5 GB4.0 GB16.0 GB128.0 GB13463
LLaMA-2 7B shape with MQA0.016 MB0.1 GB0.5 GB2.0 GB16.0 GB151130

(Tokens/s: the memory-bandwidth bound of an A100, 2.0 TB/s, reading the weights and the whole cache once per token.) At 128K tokens, LLaMA-2 7B’s cache (64 GB) is 4.8× its weights and cuts its bound from 129 to 24 tokens/s; GQA (Mistral) keeps 63, MQA 130. Long contexts are a memory-bandwidth problem as much as a memory-size problem.

6.3 MHA vs GQA vs MQA in miniature (script 03, Part 2)

Width 64, 4 layers, 8 query heads (head dimension 8), 8M characters of additions each:

attentionparameters (blocks)KV cache / tokenbits / lineanswer accuracy
MHA (8 KV heads)199,9361,024 B22.3655.3%
GQA (2 KV heads)174,976256 B21.9862.0%
MQA (1 KV head)170,816128 B21.3675.4%
MHA → MQA by mean-pooling the K/V heads (no training)199,936128 B93.040.0%
… + uptraining on 5% of the budget199,936128 B28.870.6%

Plan vs reality. (1) Sharing K/V heads cost nothing here — MQA even came out best. With 8M characters these models sit in the middle of their “learning addition” transition (§2.3: a model of this size crosses it between 4M and 16M), so the differences mostly reflect when each run crossed it; the honest conclusion is “no measurable cost of MQA at this scale”, not “MQA is better”. (2) Uptraining failed: averaging 8 heads into one destroyed the trained model (93 bits per line, worse than a 3K-parameter model) and 400K characters of further training recovered only to 28.87. The GQA paper pools 64 heads into 8 groups of a large model and trains for 5% of a far longer run; collapsing all heads of a small model into one is a much bigger jump.


7. Mixture of experts

7.1 The idea

A mixture-of-experts layer (Shazeer et al., 2017) replaces the feed-forward block by EE expert MLPs and a router that sends each token to its top-kk; parameters grow with EE, compute per token with kk — “decouple compute from parameters”. Mixtral 8×7B (2024): 8 experts, 2 active per token, matching or beating LLaMA-2 70B with far fewer active parameters; the slides note that expert selection may not be interpretable (experts do not specialize by topic). A load-balancing loss keeps routers from sending everything to a few experts (Switch Transformer: E∑efepeE\sum_e f_e p_e).

7.2 Experiment: two domains, four experts (script 03, Part 3)

A mixed corpus — half ShapeWorld captions (floor 11.97 bits per line), half additions (19.93) — 6M characters; width 64, 4 layers; MoE layers with 4 experts of the dense model’s size:

modelparametersactive per tokenbits / captionbits / additionexpert usage (bits)II(expert; domain)
dense FFN (hidden 256)199,936199,93612.2229.49——
dense FFN, 4× wider (hidden 1,024)596,224596,22412.1730.34——
MoE, top-1 of 4, balancing loss 0.01598,016200,96012.2730.571.950.06
MoE, top-1 of 4, no balancing loss598,016200,96012.2130.221.950.02
MoE, top-2 of 4, balancing loss 0.01598,016333,31212.1929.961.980.11

Expert choice vs domain

(Expert usage: entropy of the distribution of tokens over the 4 experts of the first layer — 2 bits when all are used equally; II(expert; domain): mutual information between a token’s expert and whether it belongs to a caption or an addition — 1 bit for a perfect split.)

All five models learned the captions almost perfectly (12.2 vs 11.97 bits) and none had learned addition yet (29.5–30.6 vs 19.93): with half of 6M characters, every model is before its transition, and neither 4× more parameters (dense or experts) nor a second active expert helped. The routers used all four experts evenly (1.95–1.98 of 2 bits) even without the balancing loss, and the experts did not specialize by domain (II ≤ 0.11 bits) — as the slides say of Mixtral, routing is not organized by topic. Plan vs reality: we expected collapse without balancing and a domain split; neither happened at this scale. What an MoE is for — more capacity at the same per-token compute — only pays when capacity is the bottleneck, which it was not here.


8. Reasoning and inference-time compute

8.1 The slides’ story

  • Fine-tuning on answers needs a lot of data: on grade-school math (GSM8K), Cobbe et al. (2021) estimate a 175B model would need ~100× more fine-tuning data to reach 80% by fine-tuning alone — and they train verifiers to rank sampled solutions.
  • Scratchpads (Nye et al., 2021): train the model to write intermediate computations before the answer. Chain-of-thought prompting (Wei et al., 2022): show worked examples in the prompt; zero-shot chain-of-thought (Kojima et al., 2022): just add “Let’s think step by step”.
  • Process supervision (Lightman et al., 2023, Let’s Verify Step by Step): a reward model trained on step-level human labels selects solutions better than one trained on final answers only, and does not saturate early — but step labels are expensive.
  • RLHF (Ouyang et al., 2022): supervised fine-tuning on demonstrations, a reward model from human comparisons, reinforcement learning against it; preferred over SFT alone and scaling well.
  • Code (Chen et al., 2021, Codex): test loss follows power laws in model size, and pass@k grows with size; AlphaCode samples up to millions of programs and filters them by running them on the example tests, then clusters; AlphaCode 2 does the same with a Gemini-based model: a good pre-trained model plus large-scale inference-time sampling.

8.2 Experiment: a scratchpad for addition (script 04, Part 1)

A 3-layer, width-64 Transformer, 4,000 steps, trained on 1,000 / 5,000 / 30,000 three-digit additions, either to write the answer directly (“357+468=825”) or first the digit sums with carries, right to left (“357+468=7+8=15,5+6+1=12,3+4+1=8,825”):

training problemsdirect answerscratchpad
1,00015.2%92.4%
5,00098.0%100.0%
30,00099.9%100.0%

With few examples, showing the work multiplies accuracy six-fold (15.2% → 92.4%). The direct answer asks the network to compute every carry internally before writing the first digit — a computation of fixed depth per token; the scratchpad turns it into a sequence of one-digit additions, each conditioned on the carry already written down, and spends more tokens (26 characters instead of 4–5) — more computation per problem. With enough data the small network learns the direct mapping too.

8.3 Experiment: sampling, voting and verifying (script 04, Part 2)

Sample kk completions at temperature 1 from a weaker model and pick one answer, on 500 test problems:

modelsamples kkmajority votestep checkeroracle verifier (pass@k)
direct answers, 5,000 problems196.8%—96.8%
597.6%—99.4%
2598.0%—99.8%
scratchpad, 1,000 problems190.2%90.2%90.2%
590.8%95.4%95.4%
2590.8%97.0%97.0%
  • Inference compute buys accuracy when something can tell good samples from bad: with an oracle (AlphaCode’s “run the tests”), 25 samples lift the scratchpad model from 90.2% to 97.0%.
  • Majority vote barely helps the scratchpad model (90.8%): its mistakes repeat across samples, so the most common answer is often a wrong one.
  • A step checker that only verifies what is written — each digit sum and carry, and that the answer is assembled from the steps, without knowing the true sum — is as good as the oracle here. Every wrong answer the model produced came with a visibly wrong step. That is the promise of process supervision: verify the reasoning, not just the result.

9. Sharding (pointer)

The last part of the slides — TPU / GPU basics, sharding a matmul by rows or columns, sharding the MLP and attention (Megatron’s conjugate “f” and “g” operators: identity forward / all-reduce backward and vice versa), data parallelism, fully-sharded data parallelism (gather the next layer’s weights while computing this one), tensor parallelism, their arithmetic-intensity conditions, and the practical guideline “use FSDP as much as possible; blockwise transformers to cut memory, Ring Attention to extend context” — is developed with simulated devices in Lecture 23.


10. Summary

  1. A language model is trained by maximum likelihood on next tokens; compute is C≈6NDC \approx 6ND. Scaling laws L=E+A/Nα+B/DβL = E + A/N^\alpha + B/D^\beta give the compute-optimal split N∝Cβ/(α+β)N \propto C^{\beta/(\alpha+\beta)} — Kaplan ~0.73, Chinchilla ~0.5 (20 tokens per parameter). On our text of known entropy, models learn addition abruptly; a free fit put the irreducible loss at 5.93 bits per line instead of the true 19.93; with EE fixed, Nopt∝C0.65N_{\text{opt}} \propto C^{0.65}. Fit the constants yourself — and check them against what you know.
  2. Loss predicts performance: across all 30 runs, answer accuracy was a monotone function of loss. Inference-optimal training (smaller model, more tokens) cost +7% compute for a model 25% smaller, 2.04× for half the size.
  3. Blockwise attention (online softmax) and Ring Attention compute exact attention (to 10−1610^{-16}) with activation memory linear in the context and spread over devices; at 1M tokens one layer still needs 16 GB with BPT, and Ring Attention hides communication only for blocks of thousands of tokens (c≥F/Bc \ge F/B).
  4. Cheaper alternatives lose recall: full attention retrieved every key–value pair, a sliding window failed beyond its reach, linear attention and our naive hybrid were weak even for short contexts.
  5. Decoding is memory-bound: at 128K tokens LLaMA-2 7B’s KV cache (64 GB) dwarfs its weights; GQA / MQA shrink it 4–32× — at no measurable cost in our small models; mean-pooling all heads into one destroyed a trained model, and brief uptraining did not repair it.
  6. A mixture of experts gave no gain where capacity was not the bottleneck, used its experts evenly even without a balancing loss, and did not split them by domain.
  7. Writing out intermediate steps made a small model data-efficient (15.2% → 92.4% with 1,000 problems). Sampling plus verification turned inference compute into accuracy (90.2% → 97.0% with 25 samples), majority vote did not (90.8%), and a step checker without access to the answer was as good as an oracle.

11. Common pitfalls

  1. Trusting a fitted irreducible loss. Our free fit put EE at 5.93 bits per line when the truth is 19.93, and predicted impossible losses just beyond the grid.
  2. Extrapolating exponents from a small grid. Two fits that describe the grid equally well disagree about the compute-optimal split; loss curves with sudden transitions are not power laws.
  3. A learning-rate schedule not matched to the token budget — Kaplan’s fixed schedule is one reason their exponents differ from Chinchilla’s.
  4. Confusing compute-optimal with inference-optimal. A model that is cheaper to train may be more expensive to serve; over-training smaller models is cheap up to a point (+7% compute for −25% size here) and then very expensive.
  5. Assuming linear memory solves long context. Blocking removes the s2s^2 term; activations still grow linearly (16 GB per layer at 1M tokens), and Ring Attention only hides communication when per-device blocks are large.
  6. Judging recurrent / linear-attention models only by perplexity. They can match perplexity and fail at recall.
  7. Counting FLOPs for decoding. At batch 1 decoding reads every weight and the whole KV cache per token; bandwidth, not FLOPs, sets the speed.
  8. Majority voting a model whose errors are systematic. Verification (outcome or process) is what turns samples into accuracy.

12. Exercises

Exercise 1 (the compute-optimal split — derivation). Minimize L(N,D)=E+AN−α+BD−βL(N, D) = E + A N^{-\alpha} + B D^{-\beta} subject to 6ND=C6ND = C, and show Nopt∝Cβ/(α+β)N_{\text{opt}} \propto C^{\beta/(\alpha + \beta)}.

Answer

Substitute D=C/(6N)D = C/(6N): L(N)=E+AN−α+B(6N/C)βL(N) = E + AN^{-\alpha} + B(6N/C)^{\beta}. Setting dL/dN=−αAN−α−1+βB(6/C)βNβ−1=0dL/dN = -\alpha A N^{-\alpha - 1} + \beta B (6/C)^\beta N^{\beta - 1} = 0 gives Nα+β=αAβB(C/6)βN^{\alpha + \beta} = \frac{\alpha A}{\beta B}(C/6)^\beta, so Nopt=G (C/6)β/(α+β)N_{\text{opt}} = G\,(C/6)^{\beta/(\alpha + \beta)} with G=(αA/βB)1/(α+β)G = (\alpha A/\beta B)^{1/(\alpha + \beta)}, and Dopt=C/(6Nopt)∝Cα/(α+β)D_{\text{opt}} = C/(6N_{\text{opt}}) \propto C^{\alpha/(\alpha + \beta)}. Equal exponents α=β\alpha = \beta give Chinchilla’s equal split; our fit (α\alpha = 0.464, β\beta = 0.855) gives N∝C0.65N \propto C^{0.65}.

Exercise 2 (6ND). Derive the “6” in C=6NDC = 6ND for a network of matrix multiplications, and the attention correction s/6ds/6d.

Answer

A weight matrix with nn parameters applied to one token costs nn multiply-adds = 2n2n FLOPs forward. Backward needs the gradient with respect to the input (2n2n) and to the weights (2n2n): 6n6n per token in total, 6N6N for the network. Attention adds, per token and layer, the score and weighted-sum products with all ss positions: 2⋅2sd2 \cdot 2sd FLOPs forward, ×3\times 3 with backward =12sd= 12sd per layer, versus 6⋅12d2=72d26 \cdot 12d^2 = 72d^2 for the layer’s parameters (12d212d^2 per layer): ratio 12sd/72d2=s/6d12sd/72d^2 = s/6d.

Exercise 3 (the online softmax — derivation). Show that the update m′=max⁡(m,max⁡jsj)m' = \max(m, \max_j s_j), ℓ′=em−m′ℓ+∑jesj−m′\ell' = e^{m - m'}\ell + \sum_j e^{s_j - m'}, o′=em−m′o+∑jesj−m′vjo' = e^{m - m'}o + \sum_j e^{s_j - m'}v_j processed over blocks ends with o/ℓ=∑jsoftmax(s)jvjo/\ell = \sum_j \mathrm{softmax}(s)_j v_j.

Answer

Invariant: after any prefix of blocks, ℓ=∑j seenesj−m\ell = \sum_{j \text{ seen}} e^{s_j - m} and o=∑j seenesj−mvjo = \sum_{j \text{ seen}} e^{s_j - m}v_j with mm the maximum seen. The update rescales the old sums from reference mm to m′m' (multiplying by em−m′e^{m - m'}) and adds the new terms at reference m′m', so the invariant holds. At the end, o/ℓ=∑jesj−mvj/∑jesj−mo/\ell = \sum_j e^{s_j - m}v_j / \sum_j e^{s_j - m} = the softmax average (the common factor e−me^{-m} cancels). Script 02: differences ≤8.3×10−16\le 8.3\times10^{-16}.

Exercise 4 (Ring Attention’s overlap condition). Derive c≥F/Bc \ge F/B for a block of cc tokens of width dd with bf16 keys and values, and evaluate it for an A100 over InfiniBand.

Answer

Per step a device computes QK⊤QK^\top and PVPV for a c×cc \times c tile: 2⋅2c2d=4c2d2 \cdot 2c^2d = 4c^2d FLOPs, time 4c2d/F4c^2d/F. It sends one K and one V block: 2⋅c⋅d⋅22 \cdot c \cdot d \cdot 2 bytes =4cd= 4cd, time 4cd/B4cd/B. Overlap requires 4c2d/F≥4cd/B4c^2d/F \ge 4cd/B, i.e. c≥F/Bc \ge F/B (independent of dd). A100 with 312 TFLOP/s and 25 GB/s: c≥12,480c \ge 12{,}480 tokens per device.

Exercise 5 (the KV cache). Compute the KV cache of LLaMA-2-70B (80 layers, 8 KV heads of dimension 128, bf16) for a 128K-token context, and compare with an MHA version with 64 KV heads.

Answer

Per token: 2⋅80⋅8⋅128⋅22 \cdot 80 \cdot 8 \cdot 128 \cdot 2 bytes = 327,680 bytes ≈ 0.31 MB; at 131,072 tokens ≈ 40 GB. With 64 KV heads (MHA): 8× more, ≈ 320 GB — more than four 80 GB GPUs for the cache of one sequence. GQA with 8 groups is what makes long contexts servable (§6).

Exercise 6 (MoE arithmetic). An MoE layer has EE experts of PP parameters each and routes each token to kk. How many parameters does it store and how many does it use per token? Why is the load-balancing loss minimized when tokens are spread evenly?

Answer

It stores EPEP and uses kPkP per token: capacity grows with EE at constant per-token compute (Mixtral 8×7B: 8 experts, 2 active). The Switch loss E∑efepeE\sum_e f_e p_e (fef_e = fraction of tokens whose top choice is ee, pep_e = mean router probability of ee) is, for fixed totals ∑fe=∑pe=1\sum f_e = \sum p_e = 1, smallest (= 1) when both are uniform; concentration on a few experts raises it. Without it, a router that slightly prefers one expert sends it more tokens, which trains it more, which makes it preferred — collapse (§7).

Exercise 7 (why scratchpads help — a counting argument). A kk-layer Transformer writes the first digit of a+ba + b in one forward pass. Why might it need depth growing with the number of digits, and how does a scratchpad remove that requirement?

Answer

The first digit of the sum depends on the carry chain through all lower digits; computing a chain of nn dependent carries in one pass needs a circuit whose depth grows with nn (or a clever parallel-prefix construction a small network may not find from little data). With a scratchpad each written step needs one digit addition plus the previously written carry, a constant-depth computation; the sequence of tokens provides the depth. Script 04: 15.2% → 92.4% with 1,000 training problems.

Exercise 8 (majority vote vs verification). In script 04, majority vote over 25 samples gave 90.8% and a verifier 97.0% for the same samples. Construct a per-problem answer distribution in which majority vote is wrong while pass@25 ≈ 1.

Answer

If the model puts probability 0.6 on one wrong answer and 0.4 on the right one, majority vote over 25 samples returns the wrong answer almost always, while the probability that at least one of 25 samples is right is 1−0.625≈11 - 0.6^{25} \approx 1. Systematic errors (e.g. a consistently dropped carry) look exactly like this; a verifier exploits the right answer’s presence, voting only its frequency.

Exercise 9 (coding). Re-run script 01’s grid on 2-digit additions (entropy 13.29 bits per line). Predict whether the transitions happen earlier and how the fitted exponents change.

Answer

(Run it.) With 10,000 possible lines, models can memorize the table; transitions should come earlier and the curves be smoother (memorization improves gradually), likely giving a fit with a less extreme EE. The comparison shows how much the “law” depends on the task’s structure.


13. Further reading

From the slides

  • A. Radford, R. Jozefowicz, I. Sutskever. Learning to Generate Reviews and Discovering Sentiment, 2017; J. Kaplan et al. Scaling Laws for Neural Language Models, 2020; J. Hoffmann et al. Training Compute-Optimal Large Language Models (Chinchilla), 2022; H. Touvron et al. LLaMA, 2023; DeepSeek-AI. DeepSeek LLM: Scaling Open-Source Language Models with Longtermism, 2024.
  • T. Wang et al. What Language Model Architecture and Pretraining Objective Works Best for Zero-Shot Generalization?, ICML 2022; Y. Tay et al. Scaling Laws vs Model Architectures, 2022.
  • H. Liu, P. Abbeel. Blockwise Parallel Transformer for Large Context Models, NeurIPS 2023; H. Liu, M. Zaharia, P. Abbeel. Ring Attention with Blockwise Transformers for Near-Infinite Context, ICLR 2024; H. Liu et al. World Model on Million-Length Video and Language with RingAttention (LWM), 2024; Gemini Team. Gemini 1.5, 2024; T. Dao et al. FlashAttention, NeurIPS 2022; T. Dao. FlashAttention-2, 2023.
  • S. Borgeaud et al. Improving Language Models by Retrieving from Trillions of Tokens (RETRO), ICML 2022; R. Child et al. Generating Long Sequences with Sparse Transformers, 2019; I. Beltagy et al. Longformer, 2020; A. Jiang et al. Mistral 7B, 2023; A. Gu et al. S4, ICLR 2022; A. Gu, T. Dao. Mamba, 2023; S. Arora et al. Simple Linear Attention Language Models Balance the Recall-Throughput Tradeoff (Based), 2024; S. De et al. Griffin, 2024.
  • C. Hooper et al. KVQuant, 2024; N. Shazeer. Fast Transformer Decoding: One Write-Head is All You Need (MQA), 2019; J. Ainslie et al. GQA, EMNLP 2023; N. Shazeer et al. Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer, ICLR 2017; Mistral AI. Mixtral of Experts, 2024.
  • K. Cobbe et al. Training Verifiers to Solve Math Word Problems, 2021; M. Nye et al. Show Your Work: Scratchpads for Intermediate Computation with Language Models, 2021; J. Wei et al. Chain-of-Thought Prompting, NeurIPS 2022; T. Kojima et al. Large Language Models are Zero-Shot Reasoners, NeurIPS 2022; H. Lightman et al. Let’s Verify Step by Step, 2023; L. Ouyang et al. Training Language Models to Follow Instructions with Human Feedback, NeurIPS 2022.
  • M. Chen et al. Evaluating Large Language Models Trained on Code (Codex), 2021; Y. Li et al. Competition-Level Code Generation with AlphaCode, Science 2022; AlphaCode Team. AlphaCode 2 Technical Report, 2023.
  • L. Gao et al. The Pile, 2020; Together AI. RedPajama, 2023; X. Geng, H. Liu. OpenLLaMA, 2023; M. Shoeybi et al. Megatron-LM, 2019.

Added by these notes

  • W. Fedus, B. Zoph, N. Shazeer. Switch Transformers, JMLR 2022 — the load-balancing loss used in script 03.
  • M. Rabe, C. Staats. Self-attention Does Not Need O(n²) Memory, 2021.
  • R. Schaeffer, B. Miranda, S. Koyejo. Are Emergent Abilities of Large Language Models a Mirage?, NeurIPS 2023 — sharp jumps in accuracy vs smooth loss (our Part 4).

14. Next lecture

Lecture 17 (Wilson Yan) turns to video generation: video as a modality and why temporal compression is the key to tractable models, cascades and per-frame latents, spatio-temporal tokenizers, and video models as action-conditioned simulators. We will build a moving ShapeWorld, compare frame-by-frame with spatio-temporal tokenizers, and watch the errors of an autoregressive “simulator” accumulate.

← 返回课程目录