Maps to: CMU 11-711 Spring 2026, Lecture 7 (02/03), slides
anlp-s2026-07-pretraining2-prompting.pdf; course demo code07_icl_prompting/(icl_prompting.ipynb: completion, zero-shot and few-shot prompts, chat templates and system prompts, chain-of-thought and program-aided prompts with SmolLM2-360M). Readings: T. Brown et al., Language Models are Few-Shot Learners (GPT-3, 2020); J. Hestness et al., Deep Learning Scaling is Predictable, Empirically (2017). Additional: J. Kaplan et al., Scaling Laws for Neural Language Models (2020); J. Hoffmann et al., Training Compute-Optimal Large Language Models (Chinchilla, 2022); DeepSeek-AI, DeepSeek LLM: Scaling Open-Source Language Models with Longtermism (2024). Sources: the public slides, the readings, and the papers cited in each section. Every number labelled “measured” comes fromcode/lecture07/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14, one CPU thread). Code:code/lecture07/— every demo runs in under 75 seconds. Reading time: ~120 minutes for the prose; ~40 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Estimate the training compute of a Transformer with , and explain where the 6 comes from.
- Read and fit power laws on log-log plots; explain why a loss curve must level off at the entropy, and what an exponent means per doubling.
- Describe data, model and compute scaling laws, the compute-optimal frontier, and the Kaplan vs Chinchilla disagreement on how to split compute.
- Explain why such laws are power laws (the long tail of things to learn), and how fragile fitted constants are.
- Use small runs to choose hyperparameters (learning rate, model size, number of tokens) for a large run.
- Distinguish no-prompt, zero-shot and few-shot prompting; describe in-context learning and the evidence on what it does (task retrieval vs task learning; flipped and abstract labels; sensitivity to order, balance and coverage).
- Explain chat templates and system prompts, chain-of-thought, problem decomposition and prompt chains — and when a reasoning trace helps.
0.2 Prerequisites and scope
- Prerequisites: Lecture 6 (pretraining, cross-entropy = entropy + KL, compression), Lecture 5 (Transformers, Adam), Lecture 3 (sampling, perplexity).
- Scope: the first half of the slides is “thinking about pretraining”: compute, scaling laws, using them. The second half is adaptation by prompting.
- Not in scope: decoding algorithms (Lecture 9); fine-tuning and instruction tuning (Lecture 8); test-time scaling and advanced inference (Lecture 23); parallel training at scale (Lecture 20).
0.3 Section → code map
| Section | Idea | Demo in code/lecture07/ |
|---|---|---|
| §3.1–3.2 | exponents, doublings; why the power law must level off; for real models | 01_power_laws.py (+ scaling.py) |
| §3.3–3.7 | a full scaling study on Fact World: learning rate per size, data/model scaling, the long-tail mechanism, the fit, IsoFLOP, extrapolation | 02_scaling_laws.py (+ fact_world.py) |
| §4.3–4.5 | in-context learning: emergence, natural / flipped / symbol labels, random labels, a control, sensitivity | 03_in_context_learning.py (+ prompt_worlds.py) |
| §5.1–5.3 | the chat template; the compositionality gap and chain-of-thought; a control; three hops | 04_chain_of_thought.py |
0.4 Notation
| Symbol | Meaning |
|---|---|
| number of model parameters (non-embedding, unless stated) | |
| number of training tokens | |
| training compute in floating-point operations (FLOPs), | |
| loss: cross-entropy in nats per token on held-out data | |
| irreducible loss (the entropy of the data) | |
| exponents of the parameter and data terms of | |
| a prompt: the input placed in a format that encourages the model to do the task | |
| number of demonstrations (“shots”) in a few-shot prompt |
1. Recap, and the budget question
Lecture 6: pretrain one base model on lots of text, then adapt it. One way to adapt is prompting: “Translate this sentence into English: この映画が嫌い” turns the same model into a translator, a sentiment classifier or a problem solver. That is the second half of today.
The first half starts from the slides’ picture: a bigger model gives lower loss, and so does more data. That raises a planning question:
Given a fixed pretraining budget, how should we allocate it to get the best possible model? Add more training data? Make the model bigger? A combination? (And what about the architecture and the hyperparameters?)
A pretraining run of a frontier model costs millions of dollars and cannot be repeated to try alternatives. The answer must come from small experiments that predict the large one. That is what scaling laws are for.
2. Training = spending compute
We spend compute by performing forward and backward passes on training sequences. For a Transformer language model, the standard approximation (Kaplan et al., 2020) is
with the number of parameters and the number of training tokens. Where the 6 comes from:
- Forward pass, ≈ 2N FLOPs per token. Almost all the work is matrix–vector products. Each parameter in a weight matrix takes part in one multiply and one add per token.
- Backward pass, ≈ 4N FLOPs per token. Gradients with respect to the activations (one more matrix product) and with respect to the weights (another) cost about twice the forward pass.
Attention adds a term proportional to the context length ( per token), which is small next to unless the context is very long (Lecture 5’s crossover at ).
Example (slides): Llama 2 7B on 2 trillion tokens:
With compute measured, the planning questions become precise:
- Data scaling: change , what happens to the loss?
- Model scaling: change , what happens to the loss?
- Compute scaling: for more compute, should we increase or ?
3. Scaling laws
Scaling laws are simple, predictive rules for model performance. They are found empirically: run experiments with many configurations, and identify the trend.
3.1 Power laws and log-log plots
A power law is . Taking logs,
a straight line with slope on a log-log plot. Its defining property is scale-freeness. If we double ,
so every doubling multiplies by the same factor , wherever we start.
Measured (demo 01 Part A, Kaplan et al.’s exponents for language models):
| scaled quantity | exponent | loss factor per doubling | reduction per doubling | doublings to halve the loss |
|---|---|---|---|---|
| data | 0.095 | 0.936 | 6.4% | 10.5 (1,475×) |
| parameters | 0.076 | 0.949 | 5.1% | 13.2 (9,139×) |
| compute | 0.050 | 0.966 | 3.4% | 20 (1,048,576×) |
Doubling data reduces the loss by 6.4% (the slides’ ). Halving the loss through compute alone would take a million times more compute. Progress is steady, predictable — and expensive.
3.2 Data scaling laws, and why they must level off
Language models trained with cross-entropy are widely observed to follow a power law in data size (Hestness et al., 2017; Kaplan et al., 2020):
To build such a plot, train models on datasets of different sizes , and make sure the model is never the bottleneck by using a large model.
It cannot be a pure power law forever. Lecture 6 showed that cross-entropy is bounded below by the entropy of the data: . A pure power law tends to zero, so it must eventually cross the floor. Hestness et al. describe three regions:
- a small-data region, where models barely beat guessing;
- a power-law region;
- an irreducible-error region, where the curve flattens at the floor.
The right form puts the power law on the reducible part, .
Measured (demo 01 Part B, one Transformer on Errand World, entropy 0.754). Both fits use only the checkpoints from 16k to 128k tokens:
| tokens | 16k | 32k | 64k | 128k | 256k | 512k | 880k | 3.5M (extrapolated) |
|---|---|---|---|---|---|---|---|---|
| measured loss | 4.108 | 2.463 | 1.065 | 0.806 | 0.769 | 0.760 | 0.756 | — |
| fit | 4.051 | 2.285 | 1.289 | 0.727 | 0.410 | 0.232 | 0.148 | 0.047 |
| fit | 5.399 | 1.876 | 1.025 | 0.819 | 0.770 | 0.758 | 0.755 | 0.754 |
The pure power law falls below the entropy after ~123,000 tokens, which is impossible. The form with the floor predicts 0.755 at 880k tokens; the model measured 0.756.
Uses of data scaling laws (slides):
- Data composition. Kaplan et al. compared the curves of different data distributions.
- Repeated data. When unique data runs out, how much is a repeated token worth? Muennighoff et al. (2023) fitted a data-constrained scaling law. Up to about 4 epochs, repeated data is almost as good as new data; beyond that, its value decays toward zero. Lecture 6’s mixture constraint (“at most 4 repeats”) comes from this.
3.3 Why power laws? The long tail of things to learn
Why should loss fall as a power of data, and not, say, exponentially? One explanation fits language well (Hutter, 2021; Michaud et al., 2023, the “quantization model”):
- Text contains an enormous number of separate pieces of knowledge — facts, names, idioms, constructions — whose frequencies follow a Zipf-like long tail.
- A model learns a piece once it has seen it often enough. Each doubling of data pushes the learned frontier a fixed factor further down the tail.
- With Zipf-distributed frequencies, the loss mass still unlearned shrinks as a power of .
The same argument with model capacity (how many pieces fit) gives a power law in .
The demos use Fact World (fact_world.py), a language that is exactly this mechanism and nothing else:
- 2,500 people (two-token names) with Zipf popularity ;
- three facts per person, e.g. “kemi dorasu lives in lima .”;
- the true entropy is known exactly: 0.980 nats/token, the irreducible part from who and which relation.
Measured (demo 02 Part C): the loss on the fact token, by the popularity of the person, for the largest model during one pass over fresh text. An unknown fact costs nats (a guess); a memorized one costs ~0.
| tokens | ranks 1–10 (35% of text) | ranks 11–100 (27%) | ranks 101–1000 (27%) | ranks 1001–2500 (11%) |
|---|---|---|---|---|
| 32,000 | 1.33 | 3.21 | 3.37 | 3.36 |
| 64,000 | 0.25 | 2.30 | 3.19 | 3.30 |
| 128,000 | 0.05 | 1.05 | 2.93 | 3.35 |
| 256,000 | 0.02 | 0.32 | 2.38 | 3.41 |
| 512,000 | 0.01 | 0.08 | 1.52 | 3.13 |
| 700,000 | 0.00 | 0.05 | 1.10 | 3.01 |
Each doubling of data finishes one popularity band and starts on the next. Because each band is smaller than the one before, every doubling buys a little less, which is the power law. Lecture 10 returns to this table from the other side: the long tail is where a model’s parametric memory fails and retrieval helps.
3.4 Model size scaling laws
Similar relationships hold for model size (Kaplan et al.): with , when data is not the bottleneck. Larger models are more sample-efficient: they reach a given loss with fewer tokens. Scaling laws in are also used to choose architecture hyperparameters (depth vs width, for example).
Measured (demo 02 Part B, five model sizes, each trained once over the same 700k tokens of fresh Fact World text, each at its own tuned learning rate (§3.7); dev loss in nats/token):
| model | non-emb. params | 8k | 32k | 64k | 128k | 256k | 512k | 700k |
|---|---|---|---|---|---|---|---|---|
| d=8 | 784 | 4.834 | 1.614 | 1.418 | 1.357 | 1.315 | 1.279 | 1.271 |
| d=16 | 6,160 | 4.694 | 1.692 | 1.393 | 1.309 | 1.258 | 1.208 | 1.196 |
| d=32 | 24,672 | 4.505 | 1.592 | 1.345 | 1.269 | 1.206 | 1.154 | 1.136 |
| d=64 | 98,368 | 4.184 | 1.527 | 1.312 | 1.227 | 1.166 | 1.114 | 1.099 |
| d=128 | 393,600 | 3.762 | 1.461 | 1.289 | 1.210 | 1.148 | 1.098 | 1.078 |
| entropy floor | 0.980 | 0.980 | 0.980 | 0.980 | 0.980 | 0.980 | 0.980 |
Every row falls with data, and at every the bigger model is lower: at 64k tokens, d=128 is where d=32 is at 128k. For the largest model, the excess loss over the floor falls like (×0.72 per doubling). Across sizes at 700k tokens it falls like (×0.88 per doubling). These exponents are larger than Kaplan’s because Fact World is a far simpler language than the web. The shape is what transfers.
3.5 Compute scaling and the compute-optimal frontier
Now combine both. The slides’ recipe (following Kaplan et al. and Hoffmann et al.):
- Train models of different sizes, and plot the loss at each step of training against the compute spent so far (light-blue curves).
- At each amount of compute, pick the model with the minimum loss: the compute-optimal frontier (black).
- Run a regression on the resulting (compute, loss) pairs: the scaling law (orange), e.g. .
The frontier also says which model size is best at each budget, and therefore how to split compute between and . Two famous answers disagree:
| study | implication | ||
|---|---|---|---|
| Kaplan et al. (2020) | spend extra compute mostly on parameters | ||
| Hoffmann et al. (2022, Chinchilla) | grow both equally: ~20 tokens per parameter |
Hoffmann et al. traced Kaplan’s answer largely to the training setup. Kaplan used one learning-rate schedule for all run lengths, so a checkpoint at tokens had not been decayed for tokens. That understates what a run planned for tokens achieves, and it penalizes long runs of small models. Chinchilla used three methods:
- the frontier of training curves;
- IsoFLOP curves: for a fixed compute, train several sizes and find the minimum of the U-shaped loss-vs-size curve;
- a parametric fit (§3.6).
All three said: models of the day were too big for their data. The test: Chinchilla (70B parameters, 1.4T tokens) used about the same compute as Gopher (280B, 300B tokens) and beat it, as well as GPT-3 and larger models, on most benchmarks.
Measured (demo 02 Part E): IsoFLOP slices of the Fact World runs. Each row is a fixed compute; the cells are the loss each model reached after tokens (”–” means its run was too short or too long for that compute):
| compute | d=8 | d=16 | d=32 | d=64 | d=128 | best |
|---|---|---|---|---|---|---|
| 1.0e9 | 1.326 | 1.989 | – | – | – | d=8 |
| 3.2e9 | 1.272 | 1.357 | 2.324 | – | – | d=8 |
| 1.0e10 | – | 1.254 | 1.339 | 2.420 | – | d=16 |
| 4.0e10 | – | – | 1.202 | 1.306 | 2.114 | d=32 |
| 1.3e11 | – | – | – | 1.182 | 1.332 | d=64 |
| 4.0e11 | – | – | – | 1.101 | 1.185 | d=64 |
As compute grows, the best model grows. At small budgets the bigger models lose badly, because they have not seen enough tokens. (Our single-pass runs cannot show the left side of each U. That would need small models trained far longer, which is what real IsoFLOP studies do.)
Measured (demo 01 Part C, real models with , and the losses predicted by Chinchilla’s published fit, in that fit’s units):
| model | tokens/param | fit: loss as trained | |||
|---|---|---|---|---|---|
| GPT-3 | 175B | 0.3T | 3.2e23 | 2 | 2.002 |
| Gopher | 280B | 0.3T | 5.0e23 | 1 | 1.993 |
| Chinchilla | 70B | 1.4T | 5.9e23 | 20 | 1.937 |
| LLaMA-65B | 65B | 1.4T | 5.5e23 | 21 | 1.939 |
| Llama 2 7B | 7B | 2T | 8.4e22 | 286 | 2.020 |
| Llama 3 8B | 8B | 15T | 7.2e23 | 1,875 | 1.949 |
The fit reproduces the headline: at similar compute, Chinchilla’s 70B on 1.4T tokens beats Gopher’s 280B on 300B. Notice the last rows. Modern open models are trained far past compute-optimal: Llama 3 8B saw 1,875 tokens per parameter. The fit puts it only 0.026 nats above the optimum for its compute. And a model that is four times smaller is four times cheaper to serve, for every token it ever generates. Compute-optimal is about training cost alone. When inference dominates the lifetime cost, smaller models trained longer win.
3.6 Fitting , and how fragile the constants are
Chinchilla’s third method fits one formula to all runs,
where is the irreducible loss, the second term the penalty for a finite model, and the third the penalty for finite data. Their fit: , , , , . Minimizing subject to gives (exercise 4)
Measured (demo 02 Part D): the same fit on Fact World, 20 points (d=16–128, 64k tokens). The fitting code (scaling.fit_chinchilla) grids the exponents and solves the linear part exactly.
| fit | rel. error | |||||
|---|---|---|---|---|---|---|
| fitted | 0.887 | 2.4 | 0.32 | 19.4 | 0.36 | 0.29% |
| fixed to the true entropy | 0.980 | 4.4 | 0.40 | 101.6 | 0.53 | 0.49% |
Both fit the points to within half a percent, yet they disagree about everything else. The free fit puts the floor at 0.887, below the true entropy 0.980, and its exponents differ from the fixed fit’s. Changing the window or the set of runs moves them again:
- From 128k tokens on: = 0.856, = 0.31.
- Adding the tiny d=8 runs: = 0.704, = 0.09.
The reason: losses that never come close to the floor constrain it only weakly, and trades off against the term. Fact World’s entropy is known; the web’s is not. This is the lesson of a replication by Besiroglu et al. (2024), who found Chinchilla’s published Approach-3 constants inconsistent with the paper’s own data. With those rounded constants, the formula’s optimum at Gopher’s budget is ~30B parameters on 2.8T tokens. The paper’s other two methods said ~63–67B on ~1.4–1.5T (demo 01, observation 4). Use fitted constants for interpolation and rough planning, not as physical constants.
3.7 Using scaling laws to choose hyperparameters
Scaling laws are used to choose hyperparameters for an expensive run. The basic idea:
- Run many experiments at a small scale.
- Fit a trend.
- Use it to estimate the best setting for the large run.
- Model size and number of tokens (Chinchilla). Fit, then predict the optimal and for the budget.
- Batch size and learning rate (DeepSeek LLM, 2024). The optimal batch size grows and the optimal learning rate shrinks with compute, each fitted as a power law from small runs. The fitted laws are then used to set the 7B and 67B runs.
Measured (demo 02 Part A). Before the main sweep, three sizes were trained briefly at four learning rates:
| model | lr 0.001 | lr 0.003 | lr 0.01 | lr 0.03 | best |
|---|---|---|---|---|---|
| d=16 ( = 6,160) | 1.486 | 1.309 | 1.269 | 1.292 | 0.01 |
| d=32 ( = 24,672) | 1.313 | 1.234 | 1.241 | 1.270 | 0.003 |
| d=64 ( = 98,368) | 1.221 | 1.184 | 1.223 | 1.294 | 0.003 |
The best rate shrinks with size. The fitted rule gave each model of the study its own rate, from 0.02 for d=8 down to 0.0013 for d=128. In a first version every size used 0.003. The d=128 model then ended no better than d=64 (1.105 vs 1.103), and a law fitted on smaller models over-predicted its quality. A scaling law describes models that are each trained well.
Measured (demo 02 Part F): extrapolation. Fit on d=16–64 only, then predict d=128, which has 4× the parameters of anything in the fit:
| tokens | 64k | 128k | 256k | 512k | 700k |
|---|---|---|---|---|---|
| predicted | 1.296 | 1.208 | 1.147 | 1.104 | 1.089 |
| measured | 1.289 | 1.210 | 1.148 | 1.098 | 1.078 |
| error / excess loss | 2% | 1% | 1% | 6% | 12% |
The prediction is accurate where it interpolates in . It drifts as both and move beyond the fitted range. That is exactly the situation of a lab planning a 10× larger run. They extrapolate one step at a time and validate at intermediate scales.
Recap of the first half (slides):
- Pretraining can be thought of in terms of compute, which is determined by model size and number of tokens.
- Scaling laws are observed relationships between a variable (e.g. compute) and performance (e.g. loss).
- We can use them to extrapolate, which helps with decisions about an expensive pretraining run.
4. Prompting basics
4.1 Prompting
Prompting puts an input into a format — a prompt — that encourages the model to carry out a task:
Example: = “I love advanced NLP!”; = “Classify this sentence’s sentiment as either Positive or Negative: ‘I love advanced NLP!’”; an output = “The sentence is positive.”
To produce we need an inference algorithm (Lecture 9). The simplest is autoregressive sampling (Lecture 3): repeatedly sample and append it, until an end token.
4.2 Three strategies
Strategy 1: no prompt. A pretrained model completes text. Given “When a dog sees a squirrel, it will usually”, it may continue “bark a lot, especially at close range.” or “start to chase after it.” This is useful when the task is continuation, and it is the starting point of every other strategy.
Strategy 2: instruction prompt (“zero-shot”). Give the task as an instruction, , with no examples, hence “zero-shot”. Considerations:
- Format. The model’s output format can vary and be tricky to parse: “Positive”, “The sentiment is positive.”, or a new paragraph.
- Wording. Performance can change with the wording of the instruction.
- Training. A base model may not have been trained to follow instructions at all, or only in specific formats. Instruction-tuned models (Lecture 8) do this much better.
Lecture 6’s demo 02 was a zero-shot prompt: appending ” rating :” to a review turned a pretrained model into a 78% sentiment classifier, because that format occurred in its pretraining text.
Strategy 3: instruction + examples (“few-shot”). Additionally provide input–output pairs:
The examples show the task format and the expected outputs without any parameter update. This is in-context learning (ICL, 上下文学习), the headline finding of GPT-3 (Brown et al., 2020). Accuracy rose with the number of shots, and the gain from shots grew with model size. Real few-shot prompts can be long: the MATH-dataset prompt used for Llemma contains several fully worked problems.
4.3 In-context learning in a model we can train
To look inside ICL we need a model whose pretraining data we control. Label World (prompt_worlds.py) consists of sequences like
dull -> negative ; witty -> positive ; vapid -> negative ; sublime -> positive ; banal ->
The inputs are Cinema World’s sentiment adjectives. Each sequence picks its own label words:
- a natural pair (positive/negative, yes/no, like/dislike, …), 10% of the time flipped;
- or two random capital letters, symbols with no prior meaning (“dull -> K”).
A 2-layer Transformer trains on 30,000 such sequences in about 30 seconds.
Measured (demo 03 Part A), selected checkpoints. Accuracy means the query’s correct label word scores above the pair’s other word (50% is chance):
| step | natural labels, 0 shots | flipped labels, 4 shots | symbol labels, 4 shots |
|---|---|---|---|
| 234 | 45.0% | 51.0% | 51.5% |
| 468 | 100.0% | 0.0% | 46.0% |
| 936 | 100.0% | 28.5% | 52.5% |
| 1170 | 100.0% | 68.0% | 47.0% |
| 1404 | 100.0% | 100.0% | 82.5% |
| 1638 | 100.0% | 100.0% | 94.5% |
| 2340 | 100.0% | 100.0% | 94.5% |
The abilities arrive in stages:
- Step 468: the model knows the task: given meaningful label words, it labels correctly with zero demonstrations. At that point it ignores demonstrations that contradict the label words (0.0% on flipped).
- Around step 1,400: it starts to read the demonstrations, so flipped labels become 100%.
- Around step 1,600: it can bind arbitrary symbols.
The sudden jumps echo Olsson et al. (2022). In real Transformers, in-context learning appears in a phase change during training, together with induction heads: attention heads that find an earlier occurrence of the current pattern and copy what followed it.
4.4 What is in-context learning doing?
Measured (demo 03 Part B, accuracy vs number of demonstrations ):
| label words | k=0 | k=1 | k=2 | k=4 | k=8 |
|---|---|---|---|---|---|
| natural (“dull -> negative”) | 100.0% | 100.0% | 100.0% | 100.0% | 100.0% |
| flipped (“dull -> positive”) | 0.0% | 100.0% | 100.0% | 100.0% | 100.0% |
| symbols (“dull -> K”) | 48.5% | 61.0% | 79.5% | 94.8% | 99.5% |
Two different things can happen inside “in-context learning”:
- Task retrieval (task recognition). With meaningful labels the model needs no demonstrations. The demonstrations only tell it which task and format; the ability came from pretraining. The slides list “task retrieval” for the observation that inputs alone sometimes work as well as input–output pairs (Agarwal et al., 2024).
- Task learning. With symbols, the mapping exists only in the context. The model must read it off the demonstrations, and accuracy grows with .
Flipped labels sit in between. They contradict what the label words mean, so following them requires overriding a prior. Agarwal et al.’s “unlearning pretraining bias” shows large models need many demonstrations to do this. Our model does it after one, but only because 10% of its pretraining sequences were flipped.
Measured (demo 03 Part C), two experiments:
| 8 demos, correct labels | 8 demos, RANDOM labels | |
|---|---|---|
| natural labels, flip-trained model | 100.0% | 35.5% |
| natural labels, control (pretrained without flips) | — | 100.0% |
| symbols, flip-trained model | 99.5% | 52.2% |
| flipped labels | k=0 | k=1 | k=2 | k=4 | k=8 |
|---|---|---|---|---|---|
| pretrained WITH flipped pairs (10%) | 0.0% | 100.0% | 100.0% | 100.0% | 100.0% |
| pretrained WITHOUT flipped pairs | 0.0% | 0.0% | 0.0% | 0.0% | 0.0% |
The control never follows flipped demonstrations, even with 8. Yet it learned symbol mappings (78.2% with 8), so it reads demonstrations only where the label words leave the mapping open.
Min et al. (2022) found that replacing demonstration labels with random ones barely hurts large models on classification. They concluded that demonstrations work mostly by showing the label space, the input distribution and the format. Here that is true of the control, which relies on the label words (100% with random labels). It is false of the flip-trained model, which learned to trust demonstrations (35.5%). Both behaviours are “in-context learning”. Which one a model shows depends on its pretraining data, which is why studies of ICL on different models disagree.
There are several theoretical accounts of ICL, each with some evidence:
- implicit Bayesian inference over latent tasks (Xie et al., 2022);
- induction-head copying (Olsson et al., 2022);
- Transformers implementing a few steps of gradient descent on the in-context examples (von Oswald et al., 2023; Akyürek et al., 2023).
Our model is small enough that the copying account suffices.
4.5 Sensitivity
LMs are sensitive to small changes in the in-context examples:
- Example ordering (Lu et al., 2022): the same examples in a different order can swing accuracy from near chance to near the state of the art.
- Label balance and label coverage (Zhang et al., 2022): which labels the examples show, and how often.
- Majority-label and recency biases (Zhao et al., 2021): models favor labels that are frequent in the prompt, or that appear last.
Measured (demo 03 Part D, symbol labels, 4 demonstrations):
| the 4 demonstrations | accuracy |
|---|---|
| 2 + 2, shuffled | 100.0% |
| 3 vs 1, query has the majority label | 100.0% |
| 3 vs 1, query has the minority label | 100.0% |
| 2 + 2, query’s label in the last two | 100.0% |
| 2 + 2, query’s label in the first two | 100.0% |
| query’s label never shown | 24.2% |
Our small model shows no imbalance or order bias once it has seen both labels. Those biases come largely from the priors of big pretrained models, which ours lacks. But label coverage is decisive. If the query’s label never appears among the demonstrations, the model picks a label it has seen and is right only 24% of the time. This also explains the 61% at in §4.4: half of the queries share the single demonstration’s label (≈100%), half need the unseen one (≈24%).
Practical consequence: include every label in a few-shot prompt, and check a prompt’s accuracy across several orderings before trusting a number.
5. Prompt engineering
5.1 Chat prompts and system prompts
Many models are fine-tuned to be chatbots (Lecture 8). Their inputs are given as messages, each with a role:
- system: provided by the developer to influence behavior (“Please classify movie reviews as ‘positive’ or ‘negative’.”);
- user: the user’s input (“This movie is a banger.”);
- assistant: the model’s previous outputs.
A chat model is still a language model over one token sequence. A chat template turns the messages into a string with special tokens.
Measured (demo 04 Part A, prompt_worlds.chat_template, the Llama 3 format):
<|begin_of_text|><|start_header_id|>system<|end_header_id|>
Please classify movie reviews as 'positive' or 'negative'.<|eot_id|><|start_header_id|>user<|end_header_id|>
This movie is a banger.<|eot_id|><|start_header_id|>assistant<|end_header_id|>
The string ends with an open assistant header, so the model’s continuation is the reply. The model saw these special tokens throughout its chat fine-tuning. Using a different template than the one a model was trained with is a common silent bug.
System prompts can be long. Anthropic publishes Claude’s system prompts. The slides’ November 2024 example covers:
- step-by-step reasoning for math and logic;
- the knowledge cutoff;
- how to respond to harmful requests;
- Markdown use;
- how to count words, letters and characters;
- and more.
Developers use system prompts to set behavior, tone and output format for every conversation.
The course notebook demonstrates two ways to fix a model’s inconsistent output format with SmolLM2-360M-Instruct: a detailed format instruction in the system prompt, or example conversations (user/assistant pairs) placed before the real question, the chat form of few-shot prompting.
5.2 Chain-of-thought
Chain-of-thought (CoT) prompting (Wei et al., 2022) gets the model to explain its reasoning before giving an answer. The approach provides hand-written few-shot examples whose answers include the reasoning steps. Wei et al. found large gains on arithmetic and commonsense reasoning, but only for large models.
Why does it help? It provides the model with adaptive computation time. A model’s forward pass has a fixed depth; each generated token is another full forward pass. A problem that needs several dependent steps may not fit into one pass, but each step may.
Chain-of-thought without examples. Models may produce reasoning chains without examples:
- Zero-shot CoT (Kojima et al., 2022): append “Let’s think step by step.” to the question.
- CoT-style training data: chains-of-thought in pretraining or fine-tuning data, which makes reasoning the default.
- System prompts that request it.
Measured (demo 04 Part B). Friend World: 200 people, each with one friend. Every one-hop fact (“the friend of n7 is n52 .”) is in the pretraining data. Two-hop questions, answered either directly or step by step after the trigger ”? think :”, appear only for the train half of the people. For the held-out half, a direct answer requires composing two facts inside the network. A step-by-step answer only chains lookups.
| people | one-hop fact | two-hop, direct | two-hop, step by step |
|---|---|---|---|
| train half (two-hop documents seen) | 100.0% | 100.0% | 100.0% |
| held-out half (never in a two-hop document) | 100.0% | 2.0% | 95.0% |
Held-out example: “the friend of the friend of n0 ? think :” → “the friend of n0 is n99 , the friend of n99 is n47 . so n47”.
The model knows every fact it needs, yet it answers two-hop questions about held-out people at near chance (2.0%; chance is 0.5%). For the train half it had simply memorized the two-hop answers. Writing the steps out, it answers 95%. Press et al. (2022) named this the compositionality gap: models often know both facts but fail to compose them in one step, and the gap does not close with scale.
Why it worked — a control (demo 04 Part C). The pretraining data also contained one-hop worked examples (“the friend of n7 ? think : the friend of n7 is n52 . so n52 .”) for everyone. Without them, step-by-step accuracy on held-out people fell to 7.0%. The model had never copied a held-out name into a reasoning trace, and it wrote the wrong name in the very first step. A reasoning format helps only as far as the training data taught it broadly. That is one reason the slides list “chain-of-thought-style data in pretraining/fine-tuning data” as a cause of CoT.
Its limit (demo 04 Part D): with three hops, a length never trained, step by step reaches only 5.0%. The model writes two steps and stops, imitating the length it saw. Real models generalize better because their training data contains reasoning of every length — and they still degrade on chains longer than they have seen.
5.3 Problem decomposition, programs and prompt chains
- Problem decomposition (self-ask; Press et al., 2022): prompt the model, with few-shot examples, to ask itself a sub-question, answer it (possibly by querying a search engine), and repeat. This is the two-hop experiment with an external lookup in place of the model’s memory. It closes the compositionality gap for facts the model does not know (Lecture 10’s retrieval).
- Program-aided reasoning (PAL; Gao et al., 2022). The course notebook asks SmolLM2 to “solve the problem by writing a Python program”. The model writes the steps as code, and an interpreter does the arithmetic exactly, a computation the model is bad at.
- Prompt chains: more generally, chain together several calls to prompted models and/or external functions. One call’s output becomes part of the next call’s prompt (MiniChain is a minimal library for this). This is the step from prompting to LM-based agents (Lecture 18).
Recap of the second half (slides):
- Prompting and in-context learning basics: no prompt, zero-shot, few-shot.
- Prompt engineering: chat and system prompts, chain-of-thought, prompt chaining.
6. Summary
- Compute: (2N FLOPs forward + 4N backward per token); Llama 2 7B: .
- Power laws are straight lines on log-log plots; each doubling multiplies the loss by . Kaplan: data −6.4% per doubling; halving the loss takes ~× compute.
- Loss is bounded by the entropy: use . A pure power law fitted to early Errand World checkpoints predicted losses below the entropy after ~123k tokens.
- Why power laws: a long tail of things to learn. On Fact World, each doubling of data finished one popularity band and started the next.
- Model and compute scaling: bigger models are more sample-efficient; the compute-optimal model grows with compute (IsoFLOP best size d=8 → d=64 over 400×). Kaplan said spend extra compute mostly on parameters; Chinchilla said grow both equally (~20 tokens per parameter). Chinchilla beat Gopher at equal compute. Today’s small open models are deliberately trained far past the optimum, because inference is cheaper.
- Fitted constants are fragile: two fits within 0.5% error disagreed on the floor (0.887 vs 0.980) and exponents. Window and run choice moved them further. Fix what you know; extrapolate cautiously (12% of excess loss at 4× size).
- Hyperparameters from small runs: the best learning rate shrank with size (); without per-size tuning the scaling study gave a wrong answer.
- Prompting: no prompt / zero-shot / few-shot. ICL can be task retrieval (meaningful labels: 100% with 0 shots) or task learning (symbols: 49% → 99.5% with 8 shots). It emerged in stages during training.
- Whether demonstrations override the prior, and whether random labels hurt, depends on pretraining (control: 0% on flipped labels, 100% with random labels). Label coverage matters (24% when the query’s label is never shown).
- Chat templates are text with special tokens. Chain-of-thought closes the compositionality gap (held-out two-hop: 2% direct vs 95% step by step), if the reasoning format was learned broadly (7% without).
Common pitfalls
- Fitting a pure power law to a loss curve. It eventually predicts a loss below the entropy; include the irreducible term.
- Treating fitted exponents as constants of nature. They moved with the fitting window and with which runs were included; compare fits, report uncertainty.
- Comparing model sizes at one learning rate. The best rate shrinks with size; an untuned large model makes the law look worse than it is.
- Reading compute-optimal as “best model to deploy”. Inference cost favors smaller models trained longer.
- Using checkpoints of a long run as if they were short runs. Without decaying the learning rate at each length, short budgets look worse (Chinchilla’s correction of Kaplan).
- Assuming few-shot accuracy measures “learning from examples”. With meaningful labels it may be task retrieval: test with symbols or flipped labels.
- Leaving a label out of the demonstrations, or trusting one ordering of them.
- Using the wrong chat template for a model: the special tokens must match its fine-tuning.
- Expecting chain-of-thought to help with anything. It helps when the steps are individually easy and the format is known; it did not extend to a longer chain than trained.
Exercises
-
Compute. Estimate the training compute of GPT-3 (175B parameters, 300B tokens). How many A100-days at an effective 150 TFLOP/s?
Answer
$C = 6 \times 1.75\times10^{11} \times 3\times10^{11} = 3.15\times10^{23}$ FLOPs. $3.15\times10^{23} / 1.5\times10^{14} = 2.1\times10^9$ s ≈ 24,300 GPU-days (e.g. ~24 days on 1,000 GPUs). -
Where does the 6 come from? For one linear layer with , count the FLOPs per token of the forward pass, of , and of .
Answer
Forward: $mn$ multiplies + $mn$ adds = $2mn$. $\partial L/\partial x = W^\top \partial L/\partial y$: $2mn$. $\partial L/\partial W = (\partial L/\partial y)\, x^\top$ accumulated over tokens: $2mn$. Total $6mn = 6 \times$ (number of parameters) per token. -
Doublings. A data exponent of 0.095: how much data do you need to cut the loss by 25%? If the loss has an irreducible part and the current loss is 2.2, how does that change the answer for cutting the reducible loss by 25%?
Answer
$2^{-0.095 n} = 0.75 \Rightarrow n = \log_2(1/0.75)/0.095 \approx 4.37$ doublings ≈ 21× the data. With a floor, the power law applies to $L - E = 0.51$; cutting it by 25% (to 0.38, total 2.07) also takes 21× — but cutting the *total* loss by 25% (to 1.65) is impossible, since it is below $E$. -
Compute-optimal allocation. Derive for with . What happens when ?
Answer
Substitute $D = C/(6N)$: $L(N) = E + AN^{-\alpha} + B (C/6)^{-\beta} N^{\beta}$. Setting $dL/dN = 0$: $\alpha A N^{-\alpha-1} = \beta B (C/6)^{-\beta} N^{\beta-1}$, so $N^{\alpha+\beta} = \frac{\alpha A}{\beta B}(C/6)^{\beta}$, i.e. $N_{\text{opt}} = G (C/6)^{\beta/(\alpha+\beta)}$. With $\alpha = \beta$, $N_{\text{opt}} \propto C^{1/2}$ and $D_{\text{opt}} \propto C^{1/2}$: the Chinchilla "grow both equally" rule. -
Inference-aware training. A model will generate tokens over its lifetime (inference ≈ FLOPs per token). Compare the total compute of (a) a 70B model on 1.4T tokens and (b) an 8B model on 15T tokens. Which is cheaper over its lifetime?
Answer
(a) training $6 \times 7\times10^{10} \times 1.4\times10^{12} = 5.9\times10^{23}$; inference $2 \times 7\times10^{10}\times10^{13} = 1.4\times10^{24}$; total $2.0\times10^{24}$. (b) training $7.2\times10^{23}$; inference $1.6\times10^{23}$; total $8.8\times10^{23}$ — less than half, at a predicted loss only slightly higher (demo 01: 1.949 vs 1.937). -
Why do the exponents move? In demo 02, fitting with free gave = 0.887 although the true entropy is 0.980. Explain why the data cannot pin down, and propose an experiment that would.
Answer
All measured losses are ≥ 1.08, so $E$ is extrapolated across a gap; a lower $E$ with a larger, flatter $B D^{-\beta}$ term fits the same points almost as well (the parameters are correlated). Pinning $E$ requires points close to the floor: much longer runs (or bigger models) where the reducible loss is small — or independent knowledge of the entropy, as here. -
Task retrieval or task learning? You see a model reach 90% on a sentiment task with 4 demonstrations. Describe two prompt variants that tell you which it is doing.
Answer
(1) Replace the label words with arbitrary symbols (A/B) consistently: task learning keeps accuracy high with enough shots, pure retrieval falls to chance. (2) Flip the labels in the demonstrations: a model that follows the demonstrations flips its predictions; one that retrieves the task ignores them. Also (3) random labels: retrieval barely suffers (demo 03's control: 100%). -
The one-shot number. In demo 03, symbol labels give 61% with one demonstration. Explain this number from the label-coverage result (24.2%).
Answer
With one demonstration the query has the same polarity half the time (the model copies the shown label: ≈100%) and the opposite half the time (its label was never shown: ≈24%). Average ≈ (100% + 24%) / 2 ≈ 62%. -
When will chain-of-thought not help? Give two kinds of problem where writing out steps should not improve a model’s accuracy, with a reason for each.
Answer
(1) Problems that are a single lookup or pattern match (one-hop facts: demo 04 shows 100% directly) — there is no composition to unfold. (2) Problems whose individual steps the model cannot do either (e.g. a fact it never learned, or arithmetic it gets wrong at every step) — the chain just propagates errors; retrieval or a program (PAL) is needed instead. Also: chains longer than any the model learned to produce (demo 04 Part D).
Related assignment (concepts only)
- Assignment 1 — Build your own LLaMa (due 02/12): the model you implement is the object that scaling laws describe and that prompting adapts; the course notebook’s prompting experiments use the same architecture at 360M parameters. These notes do not provide assignment code.
Further reading
- T. Brown et al., “Language Models are Few-Shot Learners”, NeurIPS 2020 (course reading).
- J. Hestness et al., “Deep Learning Scaling is Predictable, Empirically”, 2017 (course reading).
- J. Kaplan et al., “Scaling Laws for Neural Language Models”, 2020; J. Hoffmann et al., “Training Compute-Optimal Large Language Models”, NeurIPS 2022; T. Besiroglu et al., “Chinchilla Scaling: A Replication Attempt”, 2024.
- DeepSeek-AI, “DeepSeek LLM: Scaling Open-Source Language Models with Longtermism”, 2024 (batch size and learning rate laws); N. Muennighoff et al., “Scaling Data-Constrained Language Models”, NeurIPS 2023.
- M. Hutter, “Learning Curve Theory”, 2021; E. Michaud et al., “The Quantization Model of Neural Scaling”, NeurIPS 2023.
- R. Agarwal et al., “Many-Shot In-Context Learning”, 2024; S. Min et al., “Rethinking the Role of Demonstrations”, EMNLP 2022; Y. Lu et al., “Fantastically Ordered Prompts”, ACL 2022; Z. Zhao et al., “Calibrate Before Use”, ICML 2021.
- C. Olsson et al., “In-context Learning and Induction Heads”, 2022; S. M. Xie et al., “An Explanation of In-context Learning as Implicit Bayesian Inference”, ICLR 2022.
- J. Wei et al., “Chain-of-Thought Prompting Elicits Reasoning in Large Language Models”, NeurIPS 2022; T. Kojima et al., “Large Language Models are Zero-Shot Reasoners”, NeurIPS 2022; O. Press et al., “Measuring and Narrowing the Compositionality Gap in Language Models”, 2022; L. Gao et al., “PAL: Program-aided Language Models”, ICML 2023.
Preview of Lecture 8 — Fine-tuning and distillation
Prompting adapts a model without changing a single weight; its limits showed up today (formats, sensitivity, reasoning the model was never taught). Lecture 8 adapts by training: full fine-tuning and its cost, parameter-efficient methods (LoRA: why a low-rank update suffices), instruction tuning (FLAN, Super-NaturalInstructions, Self-Instruct) that turns a base model into one that follows zero-shot instructions, and knowledge distillation — word-level vs sequence-level (Kim & Rush, 2016) and distillation from synthetic data generated by a stronger model.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| scaling law | 缩放定律 |
| power law / exponent | 幂律 / 指数 |
| log-log plot | 双对数图 |
| compute (FLOPs) / compute budget | 计算量(浮点运算次数)/ 计算预算 |
| forward / backward pass | 前向 / 反向传播 |
| data scaling / model scaling / compute scaling | 数据缩放 / 模型缩放 / 计算量缩放 |
| irreducible loss / reducible loss | 不可约损失 / 可约损失 |
| small-data region / power-law region | 小数据区 / 幂律区 |
| compute-optimal / compute-optimal frontier | 计算最优 / 计算最优前沿 |
| IsoFLOP curve | 等计算量曲线 |
| tokens per parameter | 每参数词元数 |
| undertrained / overtrained | 训练不足 / 过度训练(相对计算最优) |
| sample efficiency | 样本效率 |
| extrapolation / interpolation | 外推 / 内插 |
| long tail / Zipf’s law | 长尾 / 齐普夫定律 |
| repeated data / epoch | 重复数据 / 轮次 |
| prompt / prompting | 提示 / 提示方法 |
| completion | 续写 |
| zero-shot / few-shot / k-shot | 零样本 / 少样本 / k 样本 |
| in-context learning (ICL) | 上下文学习 |
| demonstration (example) | 示范(示例) |
| label words / label space | 标签词 / 标签空间 |
| task retrieval (recognition) / task learning | 任务检索(识别)/ 任务学习 |
| flipped labels / abstract (symbol) labels | 翻转标签 / 抽象(符号)标签 |
| induction head | 归纳头 |
| majority-label bias / recency bias | 多数标签偏置 / 近因偏置 |
| label coverage / label balance | 标签覆盖 / 标签均衡 |
| chat template / special token | 对话模板 / 特殊词元 |
| system prompt / user / assistant | 系统提示 / 用户 / 助手 |
| chain-of-thought (CoT) / zero-shot CoT | 思维链 / 零样本思维链 |
| compositionality gap / multi-hop | 组合性差距 / 多跳 |
| problem decomposition / self-ask | 问题分解 / 自问 |
| program-aided reasoning | 程序辅助推理 |
| prompt chain | 提示链 |