import gc
import hashlib
import itertools
import json
import os
import re
import string
import textwrap
import time
import pandas as pd
import transformers
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from transformers import AutoTokenizer18.3 Prompting and In-Context Learning
Anyone who has used a chat assistant knows the routine: we type a question and read the answer. A model of the kind that we loaded in Section 18.1 and rebuilt in Section 18.2 offers less. It takes tokens and returns probabilities for the next one. Suppose that we want it to name the topic of a news headline. What does the model see when we ask, and how much of its answer is decided by the text that we put around the question?
We work with two checkpoints of one architecture. Qwen3-1.7B-Base is a base model, trained only to predict the next token. Qwen3-1.7B is its post-trained sibling, trained further to hold conversations and to follow instructions, and we call it the instruct model. The task comes from AG News (Zhang et al. 2015), news items in four classes: World, Sports, Business and Sci/Tech. The dataset is released for non-commercial use only, so every headline printed in this section is invented. Of the names in the setup cell only four matter now: a headline QUERY, four solved headlines DEMOS, their format FMT and a plain question ASK.
SMALL = not torch.cuda.is_available() # no GPU: the 0.6B pair in fp32
RERUN = os.environ.get('D2L_RERUN', '0') == '1' and not SMALL
BASE, INST = (('Qwen/Qwen3-0.6B-Base', 'Qwen/Qwen3-0.6B') if SMALL
else ('Qwen/Qwen3-1.7B-Base', 'Qwen/Qwen3-1.7B'))
NATURAL = ['World', 'Sports', 'Business', 'Tech'] # AG News's 4 classes
ABSTRACT = ['foo', 'bar', 'baz', 'zip']
FMT = 'Headline: {x}\nTopic: {y}'
ASK = 'What is the topic of this news headline?\n{x}\n'
INSTRUCTION = 'Name the topic of each news headline: {}, {}, {} or {}.'
SYSTEM = INSTRUCTION.format(*NATURAL) # World, Sports, Business or Tech
SYSTEMS = [None, SYSTEM, INSTRUCTION.format(*NATURAL[::-1])] # by 'instr'
QUERY = 'Local team wins cup final' # invented, as are all examples below
DEMOS = [('Leaders meet to settle a border dispute', 'World'),
('Striker signs a new three-year contract', 'Sports'),
('Chip maker shares climb after strong earnings', 'Business'),
('New phone battery lasts a whole week', 'Tech')]
HEADLINES = [QUERY, 'Parliament votes on a new trade treaty',
'Oil prices fall as supply grows',
'Researchers build a faster quantum chip']
transformers.logging.set_verbosity_error() # no notices or progress bars
transformers.logging.disable_progress_bar()
def print_table(rows, digits=3): # a list of dicts, or a DataFrame
print(pd.DataFrame(rows).to_string(
index=False, na_rep='', float_format=f'{{:.{digits}f}}'.format))d2l.load_hf (Section 18.1) loads each model at its pinned revision.
dtype = torch.float32 if SMALL else torch.bfloat16
base, tok = d2l.load_hf(BASE, dtype=dtype)
inst, tok_i = d2l.load_hf(INST, dtype=dtype)
for name, model in ((BASE, base), (INST, inst)):
print(f'{name}: {model.num_parameters():,} parameters in {model.dtype}')
if SMALL:
print('No GPU: the 0.6B pair in fp32 stands in for the 1.7B models,\n'
'so the outputs below differ from those quoted in the text.')Qwen/Qwen3-1.7B-Base@ea980cb0a6c2: Qwen3ForCausalLM, stop tokens [151643]
0 missing keys; unexpected keys: none
kernels: attention sdpa
Qwen/Qwen3-1.7B@70d244cc86cc: Qwen3ForCausalLM, stop tokens [151645, 151643]
0 missing keys; unexpected keys: none
kernels: attention sdpa
Qwen/Qwen3-1.7B-Base: 1,720,574,976 parameters in torch.bfloat16
Qwen/Qwen3-1.7B: 1,720,574,976 parameters in torch.bfloat16
Both models have 1.72 billion parameters. We ask the base model twice with the greedy d2l.generate of Section 18.2: with the question as one would type it, and with the four solved headlines in front of ours, arranged by d2l.fewshot_prompt (Section 18.3.2.1).
for prompt in (ASK.format(x=QUERY),
d2l.fewshot_prompt(DEMOS, QUERY, fmt=FMT)):
reply = d2l.generate(base, tok, [prompt], max_new_tokens=12)[0]
print(f'{prompt}<continuation>{reply.text!r}\n')What is the topic of this news headline?
Local team wins cup final
<continuation>'The topic of this news headline is a local team winning a'
Headline: Leaders meet to settle a border dispute
Topic: World
Headline: Striker signs a new three-year contract
Topic: Sports
Headline: Chip maker shares climb after strong earnings
Topic: Business
Headline: New phone battery lasts a whole week
Topic: Tech
Headline: Local team wins cup final
Topic:<continuation>' Sports\n\nHeadline: New car model launched\nTopic:'
Asked plainly, the base model does not answer. It continues the text, with a sentence that restates the headline. With four solved examples in front, its continuation begins with the word Sports, and then, having no reason to stop, it writes another headline of its own and the next Topic:. The model did the same thing both times: it continued a pattern of tokens. The solved examples changed the pattern.
This observation became a new way of using language models. Brown et al. (2020) showed with GPT-3 that a model pretrained on enough text performs a task it was never trained for when a few solved examples, called demonstrations, precede the query. No weight changes. Acquiring a task from the context is called in-context learning (ICL). A prompt with \(k\) demonstrations is a \(k\)-shot prompt, and one with none is zero-shot.
Every score in the rest of this part is measured through a prompt, so the 5-shot accuracy on a model card belongs to a model and a prompt together. If one line of instruction moves it by several points, a comparison of two models must hold the prompt fixed, or it compares prompts. This section measures how much the prompt decides. It is more than one would like.
The section is long, because one experiment has to answer many questions. Six of them are worth keeping in mind. What does the model receive, and how do we read a label from it? What do demonstrations teach first? What can one line of instruction do to a score, or four tokens at the end of a prompt? Do the order and the labels of the demonstrations matter? When the examples and the meaning of the label words disagree, which wins? And when does a prompt beat a classifier that was fit to the same labeled examples? The cells that build the experiment are reference material, and we say where they can be skimmed.
18.3.1 Prompts as Token Sequences
18.3.1.1 Chat Templates
The base model continued whatever text it was given. An assistant has to know more: who said what, and where its own reply begins. The instruct model was therefore trained on conversations, lists of messages that each have a text and a role: system for framing instructions, user, or assistant. Yet the model still reads one sequence of tokens. The translation is done by the chat template, a short program in the Jinja template language that ships with the tokenizer files (Section 18.1) and turns a list of messages into one string. We render a conversation with an instruction, one solved headline and our query, and print the string again token by token. Tokens in brackets are added tokens: strings that the tokenizer keeps whole, each with an id of its own, and that mark structure.
conversation = [
{'role': 'system', 'content': 'Name the topic of the headline.'},
{'role': 'user', 'content': 'Headline: ' + DEMOS[1][0]},
{'role': 'assistant', 'content': DEMOS[1][1]},
{'role': 'user', 'content': 'Headline: ' + QUERY}]
chat_text = tok_i.apply_chat_template(
conversation, tokenize=False, add_generation_prompt=True,
enable_thinking=False)
print(chat_text)
start = tok_i.convert_tokens_to_ids('<|im_start|>')
special = set(tok_i.added_tokens_decoder) # <|im_start|>, <think>, ...
line = []
for i in tok_i(chat_text, add_special_tokens=False)['input_ids']:
if i == start and line: # one paragraph per message
print(textwrap.fill(' '.join(line), 79))
line = []
t = tok_i.decode([i]).replace('\n', '\\n')
line.append(f'[{i}:{t}]' if i in special else f'{i}:{t}')
print(textwrap.fill(' '.join(line), 79))<|im_start|>system
Name the topic of the headline.<|im_end|>
<|im_start|>user
Headline: Striker signs a new three-year contract<|im_end|>
<|im_start|>assistant
Sports<|im_end|>
<|im_start|>user
Headline: Local team wins cup final<|im_end|>
<|im_start|>assistant
<think>
</think>
[151644:<|im_start|>] 8948:system 198:\n 675:Name 279: the 8544: topic 315: of
279: the 31163: headline 13:. [151645:<|im_end|>] 198:\n
[151644:<|im_start|>] 872:user 198:\n 12346:Head 1056:line 25:: 4509: Str
24803:iker 11929: signs 264: a 501: new 2326: three 4666:-year 5116: contract
[151645:<|im_end|>] 198:\n
[151644:<|im_start|>] 77091:assistant 198:\n 40979:Sports [151645:<|im_end|>]
198:\n
[151644:<|im_start|>] 872:user 198:\n 12346:Head 1056:line 25:: 8774: Local
2083: team 14816: wins 10525: cup 1590: final [151645:<|im_end|>] 198:\n
[151644:<|im_start|>] 77091:assistant 198:\n [151667:<think>] 271:\n\n
[151668:</think>] 271:\n\n
Each message is wrapped in <|im_start|> and <|im_end|>, and its role is spelled in ordinary tokens: system is token 8948, user 872 and assistant 77091. The ids can be forgotten. What should stay is that a role is an ordinary word after a marker, and that the string does not end with the last message.
The argument add_generation_prompt=True appends <|im_start|>assistant and a newline, the generation prefix: the beginning of the reply, written for the model so that its next token starts an answer. Qwen3’s post-trained models may precede an answer with reasoning enclosed in <think> and </think>, called thinking. The argument enable_thinking=False appends an empty block of that kind after the prefix, four more tokens that tell the model that its thinking is already over (Figure 18.3.1). Of the added tokens printed here, only the two markers of a message are special tokens in the sense of skip_special_tokens=True. The think tokens stay in a decoded reply.
enable_thinking=False adds an empty think block of four. The answer begins at the next position, which is where we will read a label. In a rendered conversation it follows the line break after the think block (top). In plain text it follows a colon (bottom), and the same word is another token.
When enable_thinking is not given, the template decides. The next cell renders one user message with the templates of our two checkpoints and of two models of the Qwen3.5 family, and prints what follows <|im_start|>assistant and its newline.
PREFIX = '<|im_start|>assistant\n' # every template's tail starts so
rows = []
for name in ('Qwen/Qwen3-1.7B', 'Qwen/Qwen3-1.7B-Base', 'Qwen/Qwen3.5-2B',
'Qwen/Qwen3.5-4B'):
t = AutoTokenizer.from_pretrained(name, revision=d2l.HF_REVISIONS[name])
render = lambda **kw: t.apply_chat_template(
[{'role': 'user', 'content': QUERY}], tokenize=False, **kw)
body = render(add_generation_prompt=False)
unset, off = (render(add_generation_prompt=True, **kw)[len(body):]
for kw in ({}, {'enable_thinking': False}))
assert unset.startswith(PREFIX) and off.startswith(PREFIX)
rows.append({'model': name, 'unset': repr(unset[len(PREFIX):]),
'enable_thinking=False': repr(off[len(PREFIX):]),
'thinks by default': 'no' if '</think>' in unset else 'yes'})
print(f'tail after the user turn: {PREFIX!r}, then')
print_table(rows)tail after the user turn: '<|im_start|>assistant\n', then
model unset enable_thinking=False thinks by default
Qwen/Qwen3-1.7B '' '<think>\n\n</think>\n\n' yes
Qwen/Qwen3-1.7B-Base '' '<think>\n\n</think>\n\n' yes
Qwen/Qwen3.5-2B '<think>\n\n</think>\n\n' '<think>\n\n</think>\n\n' no
Qwen/Qwen3.5-4B '<think>\n' '<think>\n\n</think>\n\n' yes
With the argument unset, the template of Qwen3-1.7B stops after the newline and leaves it to the model to open a think block. The template of Qwen3.5-4B opens the block, and that of Qwen3.5-2B closes it, so that model answers at once. Two models of one family differ in their default, which is why Section 18.1 made it a rule to pass enable_thinking explicitly.
Note the second row. Qwen3-1.7B-Base ships a version of its post-trained sibling’s template, with the same thinking switch, so rendering a conversation for the base model raises no error, and the last column says that it thinks by default. That column describes the file, not the model. A base model was never taught to think, and we will measure in Section 18.3.2.4 what a think block does to it.
18.3.1.2 Reading a Label from the Next Token
For a classification task we do not need the model to write anything. Its forward pass already assigns a probability to every possible next token, and we can ask how that probability is divided among the label words. One forward pass then yields a number for every label, where a generated reply yields one word, and perhaps not one of ours. Let \(x\) be the input to classify, a headline placed in some prompt, and let \(t_y\) be the first token of the word for label \(y\) as it would follow that prompt. With \(z_t\) the logit of token \(t\) at the position after the prompt, we define
\[ p(y \mid x) = \frac{\exp(z_{t_y})}{\sum_{y'} \exp(z_{t_{y'}})}, \tag{18.3.1}\]
where the sum runs over the labels only. This is the softmax of Section 3.1, restricted to as many tokens as there are labels, and the predicted label is its largest entry. We call \(p(\cdot \mid x)\) the read-out of the prompt. The language model has become a classifier whose output layer consists of four rows of its own.
One read-out we know without computing it. For the 4-shot prompt of the opening, greedy decoding wrote Sports, so the token for Sports had the largest logit of the whole vocabulary, and with it the largest of the four.
d2l.label_logprobs computes \(\log p(y \mid x)\) for a batch of prompts. Three of its lines carry the idea: the last hidden state h of each prompt, the rows W.weight[lab] of the output layer that belong to the label tokens, and the log_softmax of their products. The rest is batching, with prompts padded on the left so that every row ends where its prompt ends. Which token stands for a label is decided by d2l.label_token_ids, to which we come below. Note that the function computes the label logits itself, in fp32, where it could have asked the model for them. The check after the cell shows why.
def label_logprobs(model, tokenizer, prompts, label_words, *, batch_size=8,
chat=False, enable_thinking=False, sep=None):
"""Log-probabilities (len(prompts), len(label_words)), float32 on the
CPU, of each label word's first token as the next token, normalized
over the label tokens only. A word follows its prompt after sep, by
default a space, but none after whitespace or next to Chinese text.
With chat=True a prompt is a message list (a string is one user
message), rendered with the generation prefix. The label logits are
computed in float32 from the last hidden state and the label words'
rows of the output layer (bf16 logits of size 20 to 40 are 1/8 to 1/4
apart and tie)."""
if chat:
opts = {} if enable_thinking is None else {
'enable_thinking': enable_thinking}
prompts = [tokenizer.apply_chat_template(
[{'role': 'user', 'content': m}] if isinstance(m, str) else m,
tokenize=False, add_generation_prompt=True, **opts)
for m in prompts]
ids, labels = d2l.label_token_ids(tokenizer, prompts, label_words, sep)
if not chat: # as d2l.generate: a plain prompt gets the BOS, if any
ids = [d2l._lm_bos_ids(tokenizer) + r for r in ids]
if not all(ids):
raise ValueError('an empty prompt has no position to predict from')
W = d2l._label_output_layer(model)
if W is None: # a d2l GPT, or a soft-capped output layer
return d2l._label_logprobs_logits(model, tokenizer, ids, labels,
batch_size)
decoder = d2l._lm_unwrap(model).get_decoder()
pad = getattr(tokenizer, 'pad_token_id', None) or 0
device = next(model.parameters()).device
out = torch.empty(len(ids), len(label_words))
for j in range(0, len(ids), batch_size): # left-padded, in input order
rows, lab = ids[j:j + batch_size], labels[j:j + batch_size]
T = max(len(r) for r in rows)
X = torch.tensor([[pad] * (T - len(r)) + r for r in rows],
device=device)
mask = torch.tensor([[0] * (T - len(r)) + [1] * len(r)
for r in rows], device=device)
pos = (mask.cumsum(-1) - 1).masked_fill(mask == 0, 1)
with torch.inference_mode():
h = decoder(input_ids=X, attention_mask=mask, position_ids=pos,
use_cache=False).last_hidden_state[:, -1]
lab = torch.tensor(lab, device=device) # (batch, labels)
z = torch.einsum('bd,bld->bl', h.float(), W.weight[lab].float())
if W.bias is not None:
z = z + W.bias[lab].float()
lp = z.log_softmax(-1).cpu()
out[j:j + batch_size] = lp # out is an ordinary tensor
return outEvery later number passes through this function, so we check it on four 4-shot prompts. The cell compares it with the full softmax over the whole vocabulary, computed in fp32 from the same hidden state and renormalized over the labels, and then with the same quantity from the model’s own bf16 logits. It goes on to compare one padded batch with scoring the prompts one at a time, and ends by printing the read-out that we have just predicted.
def renorm(z, ids): # the full softmax, renormalized over the labels
lp = z.float().log_softmax(-1)[ids]
return (lp - lp.logsumexp(-1)).cpu()
prompts = [d2l.fewshot_prompt(DEMOS, h, fmt=FMT) for h in HEADLINES]
_, label_ids = d2l.label_token_ids(tok, prompts, NATURAL)
one = d2l.label_logprobs(base, tok, prompts, NATURAL, batch_size=1)
W = base.lm_head.weight.float() # the whole output layer, in fp32
for prompt, ids, lp in zip(prompts, label_ids, one):
x = tok(prompt, return_tensors='pt').input_ids.to(base.device)
with torch.inference_mode(): # every logit at the last position
h = base.model(input_ids=x, use_cache=False).last_hidden_state[0, -1]
ref = renorm(h.float() @ W.T, ids)
ref16 = renorm(base.lm_head(h), ids) # the model's own logits
err, err16 = ((lp - r).abs().max().item() for r in (ref, ref16))
print(f'read-out vs full softmax: {err:.1e} nats (from its own logits: '
f'{err16:.1e})')
assert err <= 1e-4
del W
batched = d2l.label_logprobs(base, tok, prompts, NATURAL, batch_size=4)
tol = 1e-4 if SMALL else 0.25 # a mask or position bug costs whole nats
for e in (batched - one).abs().max(-1).values.tolist():
print(f'batched vs one at a time: {e:.1e} nats (tolerance {tol:.1e})')
assert e <= tol
assert torch.equal(batched.argmax(-1), one.argmax(-1)) # same predictions
print(f'4-shot read-out for {QUERY!r}:\n ' + ', '.join(
f'{w} {p:.3f}' for w, p in zip(NATURAL, one[0].exp().tolist())))read-out vs full softmax: 6.7e-06 nats (from its own logits: 8.9e-02)
read-out vs full softmax: 1.9e-06 nats (from its own logits: 1.5e-01)
read-out vs full softmax: 5.7e-06 nats (from its own logits: 7.7e-02)
read-out vs full softmax: 3.3e-06 nats (from its own logits: 1.1e-01)
batched vs one at a time: 1.4e-01 nats (tolerance 2.5e-01)
batched vs one at a time: 1.0e-01 nats (tolerance 2.5e-01)
batched vs one at a time: 1.0e-01 nats (tolerance 2.5e-01)
batched vs one at a time: 5.8e-02 nats (tolerance 2.5e-01)
4-shot read-out for 'Local team wins cup final':
World 0.001, Sports 0.999, Business 0.000, Tech 0.000
The first comparison agrees to within \(10^{-5}\) nats. On paper the two are one computation, so this confirms only that the function picks the right rows at the right position. The second comparison is the interesting one. The model’s own logits are off by about a tenth of a nat. They are bf16 numbers with eight significant bits, so logits between 16 and 64 lie on a grid with a spacing of 1/8 to 1/4. On such a grid two close labels tie, and a tie goes to whichever label we happened to list first. Four products in fp32 remove the grid.
Batching moves the result by as much, up to 0.14 nats here, and changes no prediction. That part we cannot remove: the hidden state itself is computed in bf16, and the shape of a batch changes how a matrix product is rounded, as Section 18.2 found. It is also the lesser evil, since this noise favors no label, whereas every tie on the grid goes to the label listed first. A tenth of a nat is the noise floor of every log-probability in this section.
The last line holds no surprise, which is the point of it. Behind four solved headlines the read-out gives Sports all but a thousandth of the probability.
The definition Equation 18.3.1 hides one quantity. The full softmax gives the four label tokens together some share of the probability, and we call that share the label mass. The read-out divides by it and so no longer shows it. If the label mass is 0.9, the read-out is close to what the model would write. If it is 0.001, the model is about to write something else, and the read-out tells us only which of the four words it prefers to the other three. Such a preference can be well informed, and we will meet one that is right two times in three. It is still no answer. A renormalized distribution sums to one however little probability it started from, so the label mass belongs beside every read-out whose meaning depends on it. We print it for single prompts here, and Section 18.3.2.5 collects it for the tables of accuracy.
def label_mass(model, tokenizer, texts, ids):
"""Full-softmax probability of the label tokens ids[i] as the next
token after texts[i], one text at a time."""
mass = []
for text, i in zip(texts, ids):
x = tokenizer(text, return_tensors='pt').input_ids.to(model.device)
with torch.inference_mode():
z = model(input_ids=x, use_cache=False,
logits_to_keep=1).logits[0, -1]
mass.append(z.float().softmax(-1)[i].sum().item())
return np.array(mass)Which token is \(t_y\)? Tokens of this vocabulary carry their leading space: in Topic: Sports the word is one token, and the space is part of it. A newline is a token of its own, and the word after it has no space. So the answer depends on what precedes the label, and this is the difference between the two halves of Figure 18.3.1. d2l.label_token_ids appends each label word to the prompt, after a space, or directly if the prompt already ends in whitespace, and returns the first new token. It raises an error where a silent score would be wrong: when the last token of the prompt merges with the label, when two labels share a first token, and when a label has several tokens.
_, (after_colon,) = d2l.label_token_ids(tok, ['Topic:'], NATURAL)
_, (after_newline,) = d2l.label_token_ids(tok_i, [chat_text], NATURAL)
d2l.label_token_ids(tok, ['Topic:'], ABSTRACT) # raises unless 1 token
print(pd.DataFrame({
'word': NATURAL,
'after "Topic:"': [f'{i} {tok.decode([i])!r}' for i in after_colon],
'after a newline': [f'{i} {tok.decode([i])!r}' for i in after_newline]
}).to_string(index=False))
assert not set(after_colon) & set(after_newline)
spaced = [p + ' ' for p in prompts] # the space typed into the prompt
mass = [label_mass(base, tok, texts, [ids] * len(texts))
for texts, ids in ((prompts, after_colon), (spaced, after_newline))]
print('label mass after "Topic:", per prompt: '
+ ', '.join(f'{m:.3f}' for m in mass[0])
+ f'; mean {mass[0].mean():.3f}')
print(f'after "Topic: ", read at the bare words: mean {mass[1].mean():.3f}')
for texts, words in ((spaced, NATURAL),
(prompts, ['World', 'Sports', 'Business', 'Sci/Tech'])):
try:
d2l.label_logprobs(base, tok, texts, words)
except ValueError as e:
print(textwrap.fill(f'ValueError: {e}', 79)) word after "Topic:" after a newline
World 4337 ' World' 10134 'World'
Sports 13180 ' Sports' 40979 'Sports'
Business 8025 ' Business' 22727 'Business'
Tech 17374 ' Tech' 34097 'Tech'
label mass after "Topic:", per prompt: 0.891, 0.158, 0.125, 0.106; mean 0.320
after "Topic: ", read at the bare words: mean 0.000
ValueError: prompt 0 ends inside a token ('inal\nTopic: ' merges with 'World'):
strip trailing whitespace from the prompt, the space belongs to the label
ValueError: label word 'Sci/Tech' after ' ' is 3 tokens [' Sci', '/T', 'ech']:
use a word that is one token there, or another sep
After the colon the label is the token for Sports with its space (13180), and after the line break that ends the rendered conversation it is the token without one (40979). No id is shared, so label tokens looked up for one kind of prompt are wrong for the other. What if we type the space ourselves and read at the bare words? The labels then receive a mass of 0.000, because in ordinary text that space is part of the next word’s token, and the model does not expect a bare word after it. A stray space at the end of a prompt is invisible on the screen and leaves the labels with no probability at all, which is why d2l.label_logprobs refuses such a prompt. It also refuses the dataset’s own class name Sci/Tech, which is three tokens, and this is why our fourth label word is Tech.
Averaged over these four 4-shot prompts, the labels hold about a third of the probability after Topic:. The average describes none of them. For the cup final the labels hold 0.89, and for the trade treaty, the oil price and the quantum chip between 0.11 and 0.16. Nothing obliges the model to use our word for a topic: a trade treaty can be filed under Politics as well as under World. Exercise 4 asks which tokens hold the rest.
When is a read-out the model’s answer? We have just seen a case that works. Behind four demonstrations the read-out of the cup final is Sports, the labels hold 0.89 of the probability, and Sports is what the model wrote in the opening. Section 18.3.2.3 measures such prompts on 200 headlines. We now take a hard case on purpose: a zero-shot prompt, our cup-final headline after a line that names the four labels. The next cell prints the read-out of this prompt and its label mass for four pairings of model and prompt. The instruct model receives the prompt through its chat template and as plain text, the base model through the template with the empty think block and with the template’s default ending. In the code, chat_multi is the layout of Section 18.3.2.1 that makes chat messages of a prompt.
chat = d2l.fewshot_prompt([], QUERY, 'chat_multi', system=SYSTEM)
plain = d2l.fewshot_prompt([], QUERY, fmt=FMT, system=SYSTEM)
render = lambda t, **kw: t.apply_chat_template( # thinking off: empty block
chat, tokenize=False, add_generation_prompt=True, **kw)
runs = {'instruct, chat template': (inst, tok_i, render(
tok_i, enable_thinking=False)),
'instruct, plain text': (inst, tok_i, plain),
'base, chat template': (base, tok, render(tok, enable_thinking=False)),
'base, chat template, no think block': (base, tok, render(tok))}
rows = {}
for name, (m, t, text) in runs.items(): # text: the rendered prompt
_, ids = d2l.label_token_ids(t, [text], NATURAL)
p = d2l.label_logprobs(m, t, [text], NATURAL)[0].exp()
rows[name] = [*p.tolist(), label_mass(m, t, [text], ids)[0]]
table = pd.DataFrame(rows, index=NATURAL + ['label mass']).T
print(table.to_string(float_format='{:.3f}'.format)) World Sports Business Tech label mass
instruct, chat template 1.000 0.000 0.000 0.000 0.378
instruct, plain text 0.999 0.001 0.000 0.000 0.985
base, chat template 0.782 0.004 0.183 0.032 0.000
base, chat template, no think block 0.384 0.327 0.133 0.156 0.019
Four pairings give four distributions for one headline, and none favors Sports. They fail for two different reasons. The rows of the base model rest on a label mass of 0.000 and of about 0.02, so they show at best a preference among words that the model will not write. The instruct model is the surprise. Its label mass is about 0.4 with the template and almost 1 in plain text, it has been told the four labels, and it gives World a probability of nearly one for a headline about a cup final. Anyone who has used a chat model will distrust this number. Is it the model’s answer, or a fault of our read-out? We let the model write, with and without the instruction line.
for system in (SYSTEM, None):
chats = [d2l.fewshot_prompt([], h, 'chat_multi', system=system)
for h in HEADLINES]
replies = d2l.generate(inst, tok_i, chats, max_new_tokens=6, chat=True,
enable_thinking=False)
print('SYSTEM line' if system else 'no instruction line')
for h, r in zip(HEADLINES, replies):
print(f' {h:40} -> {r.text!r}')SYSTEM line
Local team wins cup final -> 'World\n\nExplanation: The headline'
Parliament votes on a new trade treaty -> 'World'
Oil prices fall as supply grows -> 'World'
Researchers build a faster quantum chip -> '**Topic:** Tech'
no instruction line
Local team wins cup final -> 'The local team winning the cup'
Parliament votes on a new trade treaty -> 'The topic of a new trade'
Oil prices fall as supply grows -> 'Oil prices fell as supply increased'
Researchers build a faster quantum chip -> 'Researchers have made significant progress in'
The read-out reported the model faithfully. With the instruction line the replies name World for three of the four headlines, wrongly for the cup final and for the oil price. For the quantum chip the reply names the right topic, but it begins with markdown, which a read-out of label words cannot see. Without the line the model replies in sentences and names no label. So where the labels hold a good share of the probability, the read-out names the label that the model writes, with or without decoration around it, and here it is the wrong one.
We return to this stubborn World in Section 18.3.2.5, where it turns out to be the work of our own sentence. For now we keep two questions apart. Whether a read-out is the model’s answer, the label mass tells us. Whether the answer is right, only the true labels can tell.
18.3.2 Few-Shot Prompting
18.3.2.1 Demonstrations and Layouts
A few-shot prompt has to put the demonstrations and the query somewhere. d2l.fewshot_prompt takes demonstrations as pairs \((x, y)\) of input and label, and a query, and arranges them in one of four layouts. Two layouts return a string, and two return messages for a chat template to render. (The argument for the layout is called template. In the text we keep that word for the chat template of a model.)
def fewshot_prompt(demos, query, template='plain', *, fmt=None,
label_map=None, system=None):
"""Demonstrations demos, a list of (x, y), and a query x as a prompt.
'plain' (fmt, default 'Input: {x}\\nOutput: {y}') and 'qa'
('Q: {x}\\nA: {y}') give a string whose blocks are separated by a blank
line and which ends after the query's label field, without a space;
'chat_single' gives the same text as one user message, 'chat_multi'
one user and one assistant message per demonstration. label_map maps
each y to its label word."""
if template not in ('plain', 'qa', 'chat_single', 'chat_multi'):
raise ValueError(f'unknown template: {template!r}')
if fmt is not None:
import string
if template not in ('plain', 'chat_single'):
raise ValueError(f'template {template!r} takes no fmt')
parts = list(string.Formatter().parse(fmt))
fields = [f for _, f, _, _ in parts if f is not None]
tail = parts[-1][0] if parts and parts[-1][1] is None else ''
if (set(fields) != {'x', 'y'} or fields.count('y') > 1 or
fields[-1] != 'y' or tail.strip()):
raise ValueError('fmt needs the fields {x} and {y}, with {y} '
f'once and last: {fmt!r}')
def word(y):
if label_map is not None:
if y not in label_map:
raise KeyError(f'label {y!r} is not in label_map')
y = label_map[y]
if not isinstance(y, str):
raise TypeError(f'label {y!r} is not a string: pass label_map')
return y
demos = [(x, word(y)) for x, y in demos]
head = [] if system is None else [{'role': 'system', 'content': system}]
if template == 'chat_multi':
return head + [{'role': r, 'content': c} for x, y in demos
for r, c in (('user', x), ('assistant', y))] + [
{'role': 'user', 'content': query}]
fmt = 'Q: {x}\nA: {y}' if template == 'qa' else (
fmt or 'Input: {x}\nOutput: {y}')
text = '\n\n'.join([fmt.format(x=x, y=y) for x, y in demos] +
[fmt.format(x=query, y='').rstrip()])
if template == 'chat_single':
return head + [{'role': 'user', 'content': text}]
return text if system is None else system + '\n\n' + textHere are two demonstrations and our query in the four layouts, the chat ones as the template of the instruct model renders them.
layouts = {
'plain': d2l.fewshot_prompt(DEMOS[:2], QUERY, fmt=FMT),
'qa': d2l.fewshot_prompt(DEMOS[:2], QUERY, 'qa'),
'chat_multi': d2l.fewshot_prompt(DEMOS[:2], QUERY, 'chat_multi',
system=SYSTEM),
'chat_single': d2l.fewshot_prompt(DEMOS[:2], QUERY, 'chat_single',
fmt=FMT)}
for name, prompt in layouts.items():
if not isinstance(prompt, str): # a message list
prompt = tok_i.apply_chat_template(
prompt, tokenize=False, add_generation_prompt=True,
enable_thinking=False)
print(f'--- {name}\n{prompt}')--- plain
Headline: Leaders meet to settle a border dispute
Topic: World
Headline: Striker signs a new three-year contract
Topic: Sports
Headline: Local team wins cup final
Topic:
--- qa
Q: Leaders meet to settle a border dispute
A: World
Q: Striker signs a new three-year contract
A: Sports
Q: Local team wins cup final
A:
--- chat_multi
<|im_start|>system
Name the topic of each news headline: World, Sports, Business or Tech.<|im_end|>
<|im_start|>user
Leaders meet to settle a border dispute<|im_end|>
<|im_start|>assistant
World<|im_end|>
<|im_start|>user
Striker signs a new three-year contract<|im_end|>
<|im_start|>assistant
Sports<|im_end|>
<|im_start|>user
Local team wins cup final<|im_end|>
<|im_start|>assistant
<think>
</think>
--- chat_single
<|im_start|>user
Headline: Leaders meet to settle a border dispute
Topic: World
Headline: Striker signs a new three-year contract
Topic: Sports
Headline: Local team wins cup final
Topic:<|im_end|>
<|im_start|>assistant
<think>
</think>
The plain layout repeats a format string, here Headline: {x}\nTopic: {y}, and ends after the label field of the query, without a trailing space. The qa layout does the same with Q: and A:. Of the two chat layouts, chat_multi makes every demonstration a user turn followed by an assistant turn, and chat_single puts the plain text into one user message. An optional system line carries an instruction, as in the third prompt.
The four prompts hold the same examples and differ in almost every token around them. In this cell chat_multi also has no field names. It differs in one more respect that is easy to miss: a demonstrated answer follows assistant and a newline directly, while the answer to the query will follow the empty think block. Details of this kind matter. Sclar et al. (2024) found that separators, spacing and casing, choices that nobody would defend as meaningful, move few-shot accuracy by many points. From here on, the plain layout is the format string above and the chat layout is chat_multi with thinking off. The other two layouts are raw material for Exercise 10.
18.3.2.2 A Grid of Paired Conditions
To find out what in a prompt matters we need many prompts that differ in one respect at a time, all scored on the same test items. We build such a collection once, the grid, and read every later result from it. A condition is one setting of the factors in Table 18.3.1. The reference condition, for either model, has eight correctly labeled demonstrations in the plain layout and no instruction line.
SYSTEM unless the line is the factor.
| factor | values | varied at |
|---|---|---|
| number of demonstrations \(k\) | 0, 1, 2, 4, 8, 16; also 32 and 64 for the base model | plain layout; chat layout of the instruct model |
| layout | plain, chat, chat without the think block (base model) | \(k = 8\) |
| instruction line | none; SYSTEM: “Name the topic of each news headline: World, Sports, Business or Tech.”; the same with the labels reversed |
plain layout at \(k = 0\); chat layout of the instruct model at \(k = 0, 1, 4, 8\) |
| order of the demonstrations | four orders of the same eight | \(k = 8\) |
| labels of the demonstrations | a fraction \(\rho\) of them wrong; all of them relabeled consistently | \(k = 8\) |
| label words | natural; abstract (foo, bar, baz, zip) |
every setting of the labels |
Two design decisions matter for every table that follows. The first is the draw. Which demonstrations a prompt contains is a matter of chance, so every condition with demonstrations is built five times, from five random choices of demonstrations that we call draws. The second is that every condition is scored on the same 200 test items, 50 headlines of each class.
Why the same items? With 200 items, an accuracy near one half has a 95% interval of about \(\pm 7\) points, since \(1.96 \sqrt{0.25/200} \approx 0.07\), which is wider than most effects we are after. Two conditions that share their items can be compared item by item, and only the items on which they differ contribute noise (Section 36.5.2.6). Where two conditions agree on most items this is a large gain: the comparison of 16 demonstrations with eight will come with an interval of \(\pm 2\) points. Where many items change, as from no demonstrations to four, the interval remains about \(\pm 5\) points.
How large must a difference be, then, before we believe it? For each comparison we compute the mean difference per item with a 95% bootstrap interval, obtained by resampling the items (Section 36.5.4), and we count in how many of the five draws the difference has the sign of the mean. We read a difference as an effect only if its interval excludes zero and at least four draws agree. The rule is necessary and not sufficient. Its interval resamples the items and keeps the five draws, so it says what other test items would give with these demonstrations. About other demonstrations it says nothing, and five draws are few. Effects of twenty points and more leave no doubt. An effect of five or ten points that passes the rule may still belong to our five draws, and we will meet one that passes and supports no conclusion.
18.3.2.2.1 Construction of the Grid
The cells from here to the end of the subsection build, score and store the grid. They are reference material and can be skimmed on a first reading. The results begin in Section 18.3.2.3. The first cell registers the dataset and the stored grid.
d2l.DATA_HUB['ag-news-train'] = (
'https://huggingface.co/datasets/sh0416/ag_news/resolve/'
'70e3fa1915be9a8daebec5e840f20df9a8e18793/train.jsonl',
'4b8aa80c8d0e1bea19ec0924b720317a6a61b040')
d2l.DATA_HUB['ag-news-test'] = (
'https://huggingface.co/datasets/sh0416/ag_news/resolve/'
'70e3fa1915be9a8daebec5e840f20df9a8e18793/test.jsonl',
'6c874e265fe5ff35861f27eaf3e681dda147ba12')
d2l.DATA_HUB['lm-fewshot-grid-v2'] = (
d2l.LM_DATA_URL + 'lm-fewshot-grid-v2.csv',
'0c2a1c87635bbfcdca9cedb479723901b3d5cbd5')We use the title of each news item alone. The titles carry leftover escape codes, which d2l.clean_ag_news resolves. A second defect matters more: some training titles repeat a test title, up to case, punctuation, spacing or a trailing source tag such as (AP). A demonstration that repeats a test item hands the model its answer, so we compare titles by a key that ignores all four.
def read_jsonl(key):
path = d2l.download(key, os.path.join('..', 'data', 'lm', key))
with open(path, encoding='utf-8') as f:
return pd.DataFrame([json.loads(line) for line in f])
def dedup_key(title): # no source tag such as '(AP)', no punctuation
title = re.sub(r'\s*\([^()]*\)\s*$', '', title).lower()
title = title.translate(str.maketrans('', '', string.punctuation))
return ' '.join(title.split())The test items are the first 50 test titles of each class. Demonstrations come from the training titles whose key matches no test title. The cell also counts the titles that each cleanup rule changed.
N_PER_CLASS = 50
train, test = read_jsonl('ag-news-train'), read_jsonl('ag-news-test')
TRAIN_TITLES, changed_train = d2l.clean_ag_news(list(train.title))
TEST_TITLES, changed_test = d2l.clean_ag_news(list(test.title))
TRAIN_Y, TEST_Y = train.label.to_numpy() - 1, test.label.to_numpy() - 1
ITEMS = np.sort(test.groupby('label').head(N_PER_CLASS).index.to_numpy())
GOLD = TEST_Y[ITEMS]
assert np.bincount(GOLD).tolist() == [N_PER_CLASS] * 4
test_keys = {dedup_key(t) for t in TEST_TITLES}
in_pool = np.array([dedup_key(t) not in test_keys for t in TRAIN_TITLES])
POOL = [np.flatnonzero(in_pool & (TRAIN_Y == c)) for c in range(4)]
print(f'{len(ITEMS)} test items, the first {N_PER_CLASS} of each class in '
'file order')
print(f'demonstration pool per class: {[len(p) for p in POOL]}')
print(f'{(~in_pool).sum()} train titles removed as duplicates of test '
'titles; titles changed by each cleanup rule:')
print(pd.DataFrame({'train': changed_train, 'test': changed_test}).T
.to_string())200 test items, the first 50 of each class in file order
demonstration pool per class: [29675, 29626, 29474, 29347]
1878 train titles removed as duplicates of test titles; titles changed by each cleanup rule:
#39; is ' #36; is $ #145; to #151; other #n; &entities; <tags> \ and spaces
train 9811 267 33 22 2590 2590 4016
test 580 14 0 0 151 151 218
About 1,900 of the 120,000 training titles duplicate a test title and leave the pool. Each of the five draws is a list of 64 blocks with one title of every class in random order, and the \(k\)-shot prompt uses the first \(k\) titles. The prompts of a draw are therefore nested, and when \(k\) is a multiple of four they are balanced: every class appears equally often. The cell also fixes the reorderings and the wrong labels for Section 18.3.3.1 and Section 18.3.3.2. Every random choice comes from a seed written in the cell, and no seed was picked after looking at a result.
DRAWS = range(5)
DRAW = {} # train rows of each draw: blocks of one title per class
for s in DRAWS:
rng = np.random.default_rng(s)
picks = [rng.choice(POOL[c], 64, replace=False) for c in range(4)]
DRAW[s] = np.array([picks[c][b] for b in range(64)
for c in rng.permutation(4)])
ORDERS = {s: [np.arange(8)] + [np.random.default_rng(100 + 10 * s + o)
.permutation(8) for o in (1, 2, 3)]
for s in DRAWS}
NOISE = {} # per draw: a wrong label per position, and the order of use
for s in DRAWS:
rng = np.random.default_rng(1000 + s)
wrong = (TRAIN_Y[DRAW[s][:8]] + rng.integers(1, 4, size=8)) % 4
NOISE[s] = wrong, rng.permutation(8)
DERANGEMENTS = [p for p in itertools.permutations(range(4))
if all(i != j for i, j in enumerate(p))]
SIGMA = {s: np.array(DERANGEMENTS[np.random.default_rng(2000 + s)
.integers(len(DERANGEMENTS))])
for s in DRAWS}The function conditions writes Table 18.3.1 out as a list of dictionaries that override fields of the reference COND. The fields rho and derange are the two ways of changing labels, chat_default is the chat layout without the think block, and instr numbers the instruction lines.
MODELS, WORDS = ['base', 'instruct'], ['natural', 'abstract']
K_BASE, K_INST = [0, 1, 2, 4, 8, 16, 32, 64], [0, 1, 2, 4, 8, 16]
COND = dict(model='base', layout='plain', k=8, words='natural', rho=0.0,
derange=False, order=0, instr=0) # the reference condition
INSTR = {0: 'none', 1: 'SYSTEM', 2: 'SYSTEM, labels reversed'} # SYSTEMS
CONTENT_FREE = ['N/A', '', '[MASK]'] # in place of a headline
def conditions():
"""Every (condition, draw) of the grid; without demonstrations a
condition has the single draw -1."""
out = []
def add(**kw):
for s in ([-1] if kw.get('k', 8) == 0 else DRAWS):
out.append(dict(COND, **kw, seed=s))
for model, ks in zip(MODELS, (K_BASE, K_INST)):
for k in ks:
add(model=model, k=k)
for instr in (1, 2): # an instruction names the labels
add(model=model, k=0, instr=instr)
for k in ks if model == 'instruct' else [8]: # the chat layout
add(model=model, layout='chat', k=k, instr=1)
if model == 'instruct': # no instruction, or its labels reversed
for instr, k in itertools.product((0, 2), (0, 1, 4, 8)):
add(model=model, layout='chat', k=k, instr=instr)
if model == 'base': # the template's default end: no think block
add(model=model, layout='chat_default', instr=1)
for order in (1, 2, 3):
add(model=model, order=order)
for words, rhos in (('natural', (0.25, 0.5, 0.75, 1.0)),
('abstract', (0.0, 0.25, 0.5, 0.75, 1.0))):
for rho in rhos:
add(model=model, words=words, rho=rho)
add(model=model, words=words, derange=True)
return outThe function demos returns the demonstrations of a condition, and build_prompts its prompts.
def demos(cond):
"""The (title, label index) demonstrations of one condition."""
s, k = cond['seed'], cond['k']
if k == 0:
return []
rows = DRAW[s][:k][ORDERS[s][cond['order']]] if k == 8 else DRAW[s][:k]
y = TRAIN_Y[rows].copy()
wrong, positions = NOISE[s]
hit = positions[:round(8 * cond['rho'])] # nested in rho
assert not len(hit) or (k == 8 and cond['order'] == 0)
y[hit] = wrong[hit]
return list(zip(TRAIN_TITLES[rows],
SIGMA[s][y] if cond['derange'] else y))
def build_prompts(cond, titles):
"""One condition's prompts for the titles: strings, or message lists
in the chat layout."""
words = dict(enumerate(NATURAL if cond['words'] == 'natural'
else ABSTRACT))
if cond['layout'] == 'ask':
return [ASK.format(x=x) for x in titles]
ds, system = demos(cond), SYSTEMS[cond['instr']]
if cond['layout'].startswith('chat'):
chats = [d2l.fewshot_prompt(ds, x, 'chat_multi', label_map=words,
system=system) for x in titles]
if cond['layout'] == 'chat': # rendered by the reader, no thinking
return chats
return [tok.apply_chat_template( # base only: the default end
m, tokenize=False, add_generation_prompt=True) for m in chats]
return [d2l.fewshot_prompt(ds, x, fmt=FMT, label_map=words,
system=system) for x in titles]Besides the 200 test titles, every condition is scored on three inputs without content, N/A, the empty string and [MASK], which Section 18.3.3.3 will need.
def n_tokens(tokenizer, prompts): # per prompt, as the reader sees it
texts = [p if isinstance(p, str) else tokenizer.apply_chat_template(
p, tokenize=False, add_generation_prompt=True, enable_thinking=False)
for p in prompts]
return [len(i) for i in
tokenizer(texts, add_special_tokens=False)['input_ids']]
GRID, TITLES = conditions(), list(TEST_TITLES[ITEMS]) + CONTENT_FREE
TOKENS = {}
for model, tokenizer in zip(MODELS, (tok, tok_i)):
conds = [c for c in GRID if c['model'] == model]
TOKENS[model] = sum(sum(n_tokens(tokenizer, build_prompts(c, TITLES)))
for c in conds)
print(f'{model}: {len(conds)} (condition, draw) pairs, '
f'{len(conds) * len(TITLES):,} prompts, {TOKENS[model]:,} tokens')
assert [sum(c['model'] == m for c in GRID) for m in MODELS] == [118, 156]base: 118 (condition, draw) pairs, 23,954 prompts, 5,182,579 tokens
instruct: 156 (condition, draw) pairs, 31,668 prompts, 4,736,907 tokens
The grid has 274 pairs of condition and draw and about ten million prompt tokens. Scoring a condition yields one row per item, with the four label log-probabilities and the prediction.
COLS = ['model', 'exp', 'layout', 'k', 'words', 'rho', 'perm', 'order',
'instr', 'seed', 'item', 'lp0', 'lp1', 'lp2', 'lp3', 'pred', 'valid']
IDS = list(ITEMS) + [-1, -2, -3] # test rows, then the content-free inputs
def head(cond, exp='icl'): # the condition columns of a grid row
perm = ''.join(map(str, SIGMA[cond['seed']])) if cond['derange'] else ''
return [cond['model'], exp, cond['layout'], cond['k'], cond['words'],
cond['rho'], perm, cond['order'], cond['instr'], cond['seed']]
def score(cond):
"""Grid rows of one condition: its test items and content-free inputs,
in fixed batches (bf16 results depend on the batch)."""
model, tokenizer = (base, tok) if cond['model'] == 'base' else (
inst, tok_i)
words = NATURAL if cond['words'] == 'natural' else ABSTRACT
lp = d2l.label_logprobs(
model, tokenizer, build_prompts(cond, TITLES), words,
batch_size=32 if cond['k'] <= 16 else 8, chat=cond['layout'] == 'chat')
return [head(cond) + [i, *r.tolist(), int(r.argmax()), 1]
for i, r in zip(IDS, lp)]
def read_grid(path):
return pd.read_csv(path, dtype={'perm': str}).fillna({'perm': ''})
def matched(new, old, exp): # rows of both files, keyed by condition, item
return new[new.exp == exp].merge(old[old.exp == exp], on=COLS[:11],
suffixes=('', '_old'))For three conditions of the base model we also let the model write: the plain question of the opening, and the plain layout without demonstrations and with four. A greedy reply of eight tokens counts as a label if its first non-empty line, stripped of surrounding whitespace and punctuation and compared without regard to case, is one of the four label words. We fixed this rule before we saw a reply.
GEN = [dict(COND, k=0, layout='ask', seed=-1), dict(COND, k=0, seed=-1)] + [
dict(COND, k=4, seed=s) for s in DRAWS] # free generation, base model
def answer(text):
"""A free generation's label index by the declared rule, else -1."""
line = next((s for s in text.split('\n') if s.strip()), '')
word = line.strip(string.whitespace + string.punctuation).lower()
return next((j for j, w in enumerate(NATURAL) if w.lower() == word), -1)
def generations(cond): # greedy, 8 tokens, the test items only
out = d2l.generate(base, tok, build_prompts(cond, TITLES[:len(ITEMS)]),
max_new_tokens=8, batch_size=32)
return [head(cond, 'gen') + [i, None, None, None, None, p, int(p >= 0)]
for i, p in zip(ITEMS, (answer(g.text) for g in out))]Scoring ten million tokens takes several minutes on one GPU. A normal run of the notebook therefore downloads the stored grid and checks it against the live model by scoring one condition again. With the environment variable D2L_RERUN=1 the cell recomputes all of it.
RERUN_PATH = os.path.join('..', 'data', 'lm', 'rerun', 'lm-fewshot-grid.csv')
GRID_KEY = 'lm-fewshot-grid-v2'
registered = read_grid(d2l.download(GRID_KEY,
os.path.join('..', 'data', 'lm')))
if RERUN: # regenerate the grid (probe rows: prompting-probe)
torch.cuda.reset_peak_memory_stats()
tic = time.time()
rows = [r for c in GRID for r in score(c)]
scored = time.time() - tic # the label read-out alone
rows += [r for c in GEN for r in generations(c)]
wall = time.time() - tic
os.makedirs(os.path.dirname(RERUN_PATH), exist_ok=True)
pd.DataFrame(rows, columns=COLS).to_csv(RERUN_PATH, index=False,
float_format='%.6g')
grid = read_grid(RERUN_PATH)
tokens = sum(TOKENS.values())
print(f'{len(grid):,} rows in {wall / 60:.1f} min; {tokens:,} prompt '
f'tokens scored in {scored / 60:.1f} min ({tokens / scored:,.0f} '
f'tokens/s); peak {torch.cuda.max_memory_allocated() / 2**30:.1f}'
' GiB')
for exp in ('icl', 'gen'):
m = matched(grid, registered, exp)
print(f'{exp}: {(m.pred == m.pred_old).sum():,} of {len(m):,} '
'predictions as registered')
else:
grid = registered
print(f'{GRID_KEY}: {len(grid):,} rows')
if not SMALL: # one declared condition, re-scored live
m = matched(pd.DataFrame(score(dict(COND, seed=0)), columns=COLS),
registered, 'icl')
m = m[m.item >= 0]
print(f'base, plain, k = 8, draw 0, re-scored: '
f'{(m.pred == m.pred_old).sum()} of {len(m)} predictions as '
'registered')
margin = lambda cols: np.diff(np.sort(m[cols].to_numpy(float), 1)[
:, -2:], axis=1)[:, 0] # top label minus the runner-up
lp = ['lp0', 'lp1', 'lp2', 'lp3']
for i, a, b, same in zip(m.item, margin(lp),
margin([c + '_old' for c in lp]),
m.pred == m.pred_old):
if not same:
print(f' item {i}: margin {a:.3f} live, {b:.3f} registered')lm-fewshot-grid-v2: 63,022 rows
base, plain, k = 8, draw 0, re-scored: 200 of 200 predictions as registered
All 200 predictions of the re-scored condition equal the stored ones, so scoring is repeatable. Three helpers read a condition back as an array with one row per draw and one column per item.
def grid_values(cols, items=ITEMS, **cond):
"""Columns cols of one condition, (draws, items, cols); a condition
without demonstrations has one draw, repeated for every draw."""
c = {**COND, 'exp': 'icl', **cond}
keep = (grid.perm != '') == c.pop('derange')
for key, v in c.items():
keep &= grid[key] == v
r = grid[keep].set_index(['seed', 'item'])
seeds = sorted(r.index.unique('seed'))
v = r.loc[pd.MultiIndex.from_product([seeds, list(items)]), cols]
v = v.to_numpy(float).reshape(len(seeds), len(items), len(cols))
return v.repeat(len(DRAWS), 0) if seeds == [-1] else v
def pred(**cond): # predicted label indices, (draws, items)
return grid_values(['pred'], **cond)[..., 0].astype(int)
def correct(**cond): # 1.0 where the prediction is the gold label
return (pred(**cond) == GOLD).astype(float)The last cell implements the rule for reading a difference. The function paired_ci computes the mean difference per item and its bootstrap interval, the central 95% of the means of 2,000 resamples of the items. It is a stand-in for d2l.paired_bootstrap, which Section 18.5 develops properly. The function compare adds the number of draws in which the difference has the sign of the mean, and order_null belongs to the experiment on order.
def paired_ci(a, b=0, n_boot=2000, seed=0):
"""Mean of a - b over items, with its 95% bootstrap interval."""
d = np.asarray(a, dtype=float) - b
idx = np.random.default_rng(seed).integers(0, len(d), (n_boot, len(d)))
lo, hi = np.percentile(d[idx].mean(1), [2.5, 97.5])
return d.mean(), lo, hi
def order_null(correct, n_perm=2000, seed=0):
"""SD of accuracy over orders (correct: draws x orders x items), mean
over draws, and its p-value when each item's order labels are
permuted within a draw."""
stat = lambda c: c.mean(-1).std(-1, ddof=1).mean()
rng = np.random.default_rng(seed)
null = np.array([stat(rng.permuted(correct, axis=1))
for _ in range(n_perm)])
return stat(correct), (1 + (null >= stat(correct)).sum()) / (1 + n_perm)
def compare(a, b):
"""a - b for (draws, items) arrays: the difference with its paired
interval over items, and in how many draws it has the same sign
('n/a' when neither array varies over draws: no demonstrations)."""
diff, lo, hi = paired_ci(a.mean(0), b.mean(0))
same = (np.sign(a.mean(1) - b.mean(1)) == np.sign(diff)).sum()
fixed = all((v == v[0]).all() for v in (a, b))
return {'diff': diff, 'lo': lo, 'hi': hi,
'draws': 'n/a' if fixed else f'{same}/{len(a)}'}
def show(r): # a difference with its interval, as one string
s = f"{r['diff']:+.3f} [{r['lo']:+.3f}, {r['hi']:+.3f}]"
return s if r['draws'] == 'n/a' else f"{s} in {r['draws']} draws"18.3.2.3 Number of Demonstrations
How much do demonstrations help, and how many does it take? The first table gives accuracy against \(k\) for three curves: the base model in the plain layout, the instruct model in the chat layout with the SYSTEM line, and the instruct model in the plain layout. The last plot of the section draws them. In this table and in all later ones, diff is the difference in accuracy from the reference of the row, here \(k = 0\) of the same curve. The columns lo and hi are the ends of its interval, and draws counts the draws that agree with its sign. Beyond eight demonstrations the last column compares with \(k = 8\) as well. Under the table the cell prints one row draw by draw, the instruct model in the plain layout at \(k = 4\), for a reason that will become clear. The second table reads the free generations of the base model, where a reply counts as a label if its first line is one of the four label words.
The tables are long, and we say before each which rows to read first: here, those at \(k = 4\) and \(k = 8\) of each curve. In the text we quote accuracies as the tables print them, differences and their intervals in points, which are hundredths of accuracy, and shares of predictions in percent.
curves = {'base, plain': dict(model='base'),
'instruct, chat': dict(model='instruct', layout='chat', instr=1),
'instruct, plain': dict(model='instruct')}
rows = []
for name, c in curves.items():
zero, eight = correct(**dict(c, k=0)), correct(**dict(c, k=8))
for k in K_BASE if name == 'base, plain' else K_INST:
acc = correct(**dict(c, k=k))
rows.append({'curve': name, 'k': k, 'accuracy': acc.mean(),
**(compare(acc, zero) if k else {}),
**({'vs k = 8': show(compare(acc, eight))} if k > 8
else {})})
print_table(rows)
p4 = pred(model='instruct', k=4) # instruct, plain, k = 4: (draws, items)
acc4 = (p4 == GOLD).mean(1)
print('instruct, plain, k = 4, accuracy per draw: '
+ ', '.join(f'{a:.3f}' for a in acc4))
worst = int(acc4.argmin())
print(f' predicted labels in draw {worst}: ' + ', '.join(
f'{w} {c}' for w, c in zip(NATURAL, np.bincount(p4[worst], minlength=4))))
gain = lambda m: correct(model=m, k=4) - correct(model=m, k=0)
print('gain from k = 0 to 4, plain, instruct minus base:',
show(compare(gain('instruct'), gain('base'))))
gen = {'question': pred(exp='gen', layout='ask', k=0),
'plain, k = 0': pred(exp='gen', k=0),
'plain, k = 4': pred(exp='gen', k=4)}
rows = []
for what, f in (('valid label', lambda p: (p >= 0) * 1.0),
('exact match', lambda p: (p == GOLD) * 1.0)):
for name, p in gen.items():
rows.append({'prompt': name, 'rate of': what, 'rate': f(p).mean(),
'vs question': '' if name == 'question' else show(
compare(f(p), f(gen['question'])))})
print_table(rows) curve k accuracy diff lo hi draws vs k = 8
base, plain 0 0.650
base, plain 1 0.639 -0.011 -0.070 0.046 3/5
base, plain 2 0.705 0.055 0.008 0.102 4/5
base, plain 4 0.756 0.106 0.062 0.151 5/5
base, plain 8 0.747 0.097 0.048 0.148 5/5
base, plain 16 0.748 0.098 0.046 0.150 5/5 +0.001 [-0.017, +0.019] in 2/5 draws
base, plain 32 0.746 0.096 0.041 0.152 5/5 -0.001 [-0.027, +0.025] in 4/5 draws
base, plain 64 0.792 0.142 0.082 0.202 5/5 +0.045 [+0.013, +0.079] in 4/5 draws
instruct, chat 0 0.275
instruct, chat 1 0.667 0.392 0.320 0.462 5/5
instruct, chat 2 0.700 0.425 0.348 0.498 5/5
instruct, chat 4 0.711 0.436 0.357 0.510 5/5
instruct, chat 8 0.664 0.389 0.314 0.457 5/5
instruct, chat 16 0.711 0.436 0.359 0.507 5/5 +0.047 [+0.025, +0.070] in 4/5 draws
instruct, plain 0 0.680
instruct, plain 1 0.696 0.016 -0.043 0.077 3/5
instruct, plain 2 0.689 0.009 -0.047 0.068 3/5
instruct, plain 4 0.674 -0.006 -0.064 0.057 1/5
instruct, plain 8 0.767 0.087 0.031 0.145 5/5
instruct, plain 16 0.770 0.090 0.034 0.148 5/5 +0.003 [-0.015, +0.021] in 3/5 draws
instruct, plain, k = 4, accuracy per draw: 0.390, 0.730, 0.735, 0.750, 0.765
predicted labels in draw 0: World 123, Sports 0, Business 0, Tech 77
gain from k = 0 to 4, plain, instruct minus base: -0.112 [-0.161, -0.062] in 5/5 draws
prompt rate of rate vs question
question valid label 0.000
plain, k = 0 valid label 0.005 +0.005 [+0.000, +0.015]
plain, k = 4 valid label 0.831 +0.831 [+0.785, +0.874] in 5/5 draws
question exact match 0.000
plain, k = 0 exact match 0.005 +0.005 [+0.000, +0.015]
plain, k = 4 exact match 0.655 +0.655 [+0.597, +0.714] in 5/5 draws
For the base model, four demonstrations raise accuracy from 0.65 to 0.76. The gain of about ten points has an interval from 6 to 15 and appears in all five draws. A single demonstration does not help. From four to 32 demonstrations the curve moves by less than the width of its intervals. At 64 it lies 4.5 points above its value at eight, with an interval from 1 to 8 in four draws of five, so we cannot call the curve saturated.
Ten points is a modest gain for the change that the opening showed, and the second table explains why. In free generation the zero-shot base model writes a label word in at most 1 reply of 200. With four demonstrations 83% of its replies are a label word, and exact-match accuracy, the share of replies that are the right label, rises from nothing to 0.655, with an interval from 0.60 to 0.71. The read-out asks which of four words the model prefers, and the zero-shot model already prefers the right one in two cases of three. This is the well-informed preference that we announced: a later table will show that the four words together hold less than 2% of the zero-shot model’s probability. Generation asks whether the model names a label at all. What the demonstrations teach first is the form of the answer.
The instruct model is less tidy. In the plain layout it starts about where the base model does, and its row at \(k = 4\) deserves a second look, because the mean does not move. The two lines under the table say why. Four of the five draws score between 0.73 and 0.765, a gain of five points and more over the 0.68 without demonstrations. Draw 0 scores 0.39. With its four demonstrations the model calls 123 headlines World and 77 Tech, and not one Sports or Business, and a prompt that predicts two labels of four cannot score above one half. A mean over five draws can be the work of one of them. The same draw supplies most of the 11 points by which the gain of the instruct model falls short of the base model’s, in the last line before the second table. In the other four draws the shortfall is about five points. At eight demonstrations the gain is 9 points, with an interval from 3 to 15, in all five draws. Exercise 3 follows the unlucky draw from one demonstration to sixteen.
In the chat layout the instruct model starts at 0.275, which is the World answer of Section 18.3.1.2 at the scale of the test set. One demonstration lifts it to 0.67, and the curve then stays between 0.66 and 0.71. This curve differs from the other two in two respects at once: its prompts pass through the chat template, and they carry the instruction line. We take the two apart next.
18.3.2.4 Templates and Instructions
The next table compares each row with the plain layout at the same \(k\), without an instruction. For the base model it includes the chat layout with the default ending of the template, which has no think block. Read the two chat rows of the base model first.
rows = []
for model in MODELS:
pairs = {'chat, k = 8': (dict(layout='chat', instr=1), {}),
'plain + instruction, k = 0': (dict(k=0, instr=1), dict(k=0))}
if model == 'base': # the same template without the empty think block
pairs['chat, no think block, k = 8'] = (
dict(layout='chat_default', instr=1), {})
if model == 'instruct':
pairs['chat, k = 0'] = (dict(layout='chat', k=0, instr=1), dict(k=0))
for name, (c, ref) in pairs.items():
a, b = correct(model=model, **c), correct(model=model, **ref)
rows.append({'model': model, 'prompt': name, 'accuracy': a.mean(),
'plain, same k': b.mean(), **compare(a, b)})
print_table(rows) model prompt accuracy plain, same k diff lo hi draws
base chat, k = 8 0.258 0.747 -0.489 -0.554 -0.422 5/5
base plain + instruction, k = 0 0.755 0.650 0.105 0.050 0.160 n/a
base chat, no think block, k = 8 0.774 0.747 0.027 -0.010 0.062 4/5
instruct chat, k = 8 0.664 0.767 -0.103 -0.140 -0.068 5/5
instruct plain + instruction, k = 0 0.310 0.680 -0.370 -0.445 -0.290 n/a
instruct chat, k = 0 0.275 0.680 -0.405 -0.485 -0.320 n/a
Does the chat template hurt the base model? As we render it, with the empty think block, it certainly does. The base model scores 0.26 with eight demonstrations, the accuracy of guessing. The label mass had warned us: in Section 18.3.1.2 the same ending left the labels with 0.000 of the probability. Without the think block the base model scores 0.77. That is level with plain text, since the difference of 3 points has an interval from \(-1\) to 6. This row changes two things at once, the template and the instruction line that the chat prompt carries, and together they do no harm.
So the base model handles the chat layout. What it cannot handle is the four tokens <think>\n\n</think>\n\n. To its post-trained sibling they say that thinking is over. To a model that was never taught to think they say nothing, and they stand directly before the answer. Four tokens at the end of a prompt of well over a hundred take the base model from 0.77 to chance.
Note where the four tokens came from: we followed the rule of Section 18.1, always to pass enable_thinking, which was made for post-trained models. A base model is best prompted in plain text, and a template deserves no trust merely because it renders without an error.
Does a line that names the labels help? The two rows at \(k = 0\) in the plain layout give opposite answers. For the base model the line, without any demonstration, is worth 10.5 points, with an interval from 5 to 16. It brings the model to about 0.75, as much as eight demonstrations. For the instruct model the same line takes accuracy from 0.68 to 0.31, and in the chat layout the model scores 0.275.
Does the chat layout hurt the instruct model? Its row at \(k = 8\) lies ten points below plain text, in all five draws and with an interval that excludes zero, so the difference passes our rule. This is the case that we announced: the row supports no conclusion about the layout. It changes two things at once, and the second is under suspicion, for the chat prompt carries the line that has just misled this model. The next table will show World taking 42% of its predictions even behind eight demonstrations. Nor do five draws settle the rest. At four demonstrations the difference has the other sign, because of the one plain prompt that collapsed, and neither our interval nor a resampling of the five draws can know how often the next draw collapses (Exercise 3). A conclusion needs more draws, and a comparison that changes one thing.
Does the order of the labels in the line matter? The zero-shot rows hold for one particular line, so we vary it, at first only a little: no line, SYSTEM, and SYSTEM with its labels reversed. The first table follows the instruct model in the chat layout over \(k\) and adds the most frequently predicted label and its share of the predictions, which is 0.25 for a predictor without preference. The second applies the three lines to both models in the plain layout at \(k = 0\). Read the rows at \(k = 0\) first, and leave the block without a line aside for the moment.
def top(p): # the most-predicted label and its share, over draws and items
counts = np.bincount(p.ravel(), minlength=4)
return NATURAL[counts.argmax()], counts.max() / counts.sum()
rows = []
for instr, line in INSTR.items():
c = dict(model='instruct', layout='chat', instr=instr)
for k in (0, 1, 4, 8):
label, top_share = top(pred(**c, k=k))
rows.append({'instruction': line, 'k': k,
'accuracy': correct(**c, k=k).mean(), 'top label': label,
'top share': top_share, **(compare(
correct(**c, k=k), correct(**c, k=0)) if k else {})})
print('instruct, chat layout; each k against k = 0 with the same line')
print_table(rows)
rows = [] # each line against none
for model, (instr, line) in itertools.product(MODELS, INSTR.items()):
label, top_share = top(pred(model=model, k=0, instr=instr))
acc = correct(model=model, k=0, instr=instr)
rows.append({'model': model, 'plain, k = 0, instruction': line,
'accuracy': acc.mean(), 'top label': label,
'top share': top_share, **(compare(acc, correct(
model=model, k=0)) if instr else {})})
print('\nplain layout, k = 0; each line against none')
print_table(pd.DataFrame(rows).drop(columns='draws'))instruct, chat layout; each k against k = 0 with the same line
instruction k accuracy top label top share diff lo hi draws
none 0 0.575 World 0.405
none 1 0.505 Business 0.386 -0.070 -0.123 -0.017 3/5
none 4 0.533 Sports 0.412 -0.042 -0.095 0.016 3/5
none 8 0.648 Sports 0.321 0.073 0.014 0.133 5/5
SYSTEM 0 0.275 World 0.975
SYSTEM 1 0.667 World 0.366 0.392 0.320 0.462 5/5
SYSTEM 4 0.711 World 0.334 0.436 0.357 0.510 5/5
SYSTEM 8 0.664 World 0.419 0.389 0.314 0.457 5/5
SYSTEM, labels reversed 0 0.370 World 0.730
SYSTEM, labels reversed 1 0.620 World 0.416 0.250 0.178 0.321 5/5
SYSTEM, labels reversed 4 0.644 World 0.433 0.274 0.204 0.344 5/5
SYSTEM, labels reversed 8 0.630 World 0.468 0.260 0.194 0.325 5/5
plain layout, k = 0; each line against none
model plain, k = 0, instruction accuracy top label top share diff lo hi
base none 0.650 Business 0.370
base SYSTEM 0.755 Business 0.320 0.105 0.050 0.160
base SYSTEM, labels reversed 0.700 World 0.355 0.050 0.000 0.100
instruct none 0.680 Business 0.345
instruct SYSTEM 0.310 World 0.830 -0.370 -0.445 -0.290
instruct SYSTEM, labels reversed 0.485 World 0.535 -0.195 -0.270 -0.120
Reversing a list of four words changes what the zero-shot instruct model does. World takes 97.5% of its predictions with one line and 73% with the other, in which it is named last, and accuracy is 0.275 and 0.37. The gain from four demonstrations is accordingly 44 points with one line and 27 with the other. A statement such as “four demonstrations add 40 points” means nothing without the line it was measured with. Demonstrations weaken the pull of the line and do not remove it: with eight of them World still takes 42% and 47% of the predictions, where a quarter of the items are World.
In the plain layout the base model gains 10.5 points with SYSTEM, while its gain of 5 points with the reversed list is not established, since the interval runs from 0 to 10. The instruct model loses 37 and 19.5 points. The same sentence helps one checkpoint and harms its sibling.
18.3.2.5 Answers and Preferences
Which of the accuracies that we have quoted are a model’s answers? Zero-shot read-outs have served as baselines throughout, and one block of the last table has gone without comment, the chat layout without any line, whose accuracies look respectable. The next table computes the label mass over the 200 test items for the read-outs we have used. For prompts with demonstrations it uses draw 0 only and prints their accuracy in a column of its own, accuracy (draw 0), so those entries differ from the five-draw means above. Read the three rows without an instruction and without demonstrations first.
MASS = [('base', 'plain', 0, 0), ('base', 'plain', 0, 1),
('base', 'plain', 4, 0), ('instruct', 'plain', 0, 0),
('instruct', 'plain', 0, 1), ('instruct', 'chat', 0, 0),
('instruct', 'chat', 0, 1), ('instruct', 'chat', 0, 2),
('instruct', 'chat', 4, 0), ('instruct', 'chat', 4, 1),
('instruct', 'chat', 8, 0)]
rows = []
for model, layout, k, instr in MASS: # (model, layout, k, line)
cond = dict(model=model, layout=layout, k=k, instr=instr,
seed=0 if k else -1) # k > 0: draw 0 only
m, t = (base, tok) if model == 'base' else (inst, tok_i)
texts = build_prompts(dict(COND, **cond), TEST_TITLES[ITEMS])
if layout == 'chat': # rendered as the reader renders it
texts = [t.apply_chat_template(x, tokenize=False,
add_generation_prompt=True,
enable_thinking=False) for x in texts]
_, ids = d2l.label_token_ids(t, texts, NATURAL)
mass = label_mass(m, t, texts, ids)
row = {'model': model, 'layout': layout, 'k': k,
'instruction': INSTR[instr], 'mean mass': mass.mean(),
'median mass': np.median(mass)}
if not SMALL: # the grid's accuracy for the same condition
row['accuracy (draw 0)' if k else 'accuracy'] = correct(**cond).mean()
rows.append(row)
print_table(rows) model layout k instruction mean mass median mass accuracy accuracy (draw 0)
base plain 0 none 0.016 0.008 0.650
base plain 0 SYSTEM 0.838 0.863 0.755
base plain 4 none 0.644 0.723 0.715
instruct plain 0 none 0.008 0.003 0.680
instruct plain 0 SYSTEM 0.685 0.751 0.310
instruct chat 0 none 0.000 0.000 0.575
instruct chat 0 SYSTEM 0.608 0.731 0.275
instruct chat 0 SYSTEM, labels reversed 0.548 0.618 0.370
instruct chat 4 none 0.000 0.000 0.405
instruct chat 4 SYSTEM 0.990 1.000 0.700
instruct chat 8 none 0.009 0.000 0.660
Without an instruction line and without demonstrations, the four labels hold between 0 and 2% of the model’s probability. The zero-shot accuracies of 0.65 and 0.68 that have served as baselines are therefore preferences among words that the model was not going to write. They are sound measurements of a preference, and a gain over them is a gain of the read-out. They must not be taken for the accuracy of a model that answers.
The instruct model in the chat layout without a line is the extreme case. Its label mass stays below 1% even with eight demonstrations, so every point of that curve is a preference. Such a curve shows how a preference shifts as demonstrations are added. It says nothing about what the model would answer, which is why we have not read it.
For the base model either source of information moves the mass onto the labels: 0.84 with the line alone, and 0.64 with four demonstrations alone. (The third of Section 18.3.1.2 was an average over four invented headlines, and this is an average over the 200 test items.)
The rows that teach most are those of the instruct model at \(k = 0\) with a line. Their mass lies between 0.55 and 0.7, so these read-outs are, more often than not, what the model would write. At 0.275 to 0.37 they are far less accurate than the preference of 0.68 that the same model showed in plain text without the line. Here the answer is worse than the preference. The label mass says whether a read-out is the model’s answer. It does not say that the answer is good. Both have to be measured: the mass beside every read-out, and the accuracy again once a line or demonstrations have raised the mass.
Why World? We can say what the cause is not. It is not our read-out, since the model writes World when it generates. It is not the place of the word in the list, since World keeps most of the predictions when it is named last. It is not the chat template, since the plain layout shows the same preference. Two things remain, and we chose both of them: the sentence itself, and the switch that kept the model from thinking before it answers.
The next cell tries both on the instruct model in the chat layout, without demonstrations. It words the line in three more ways: as a question, as a request to classify the headline into one of four topics, and as that request followed by “Answer with the topic only.” Every version names the four labels in the same order, and the label is read from the next token as before. The three new sentences are the only ones that we tried, and the table shows each of them. Then the cell returns to the line that failed, switches thinking on and lets the model write up to 1,024 tokens. The label is taken from what follows the think block, by the rule for generated replies of Section 18.3.2.2: the first line must be one of the four label words. Each row is compared with SYSTEM, thinking off, on the same 200 items.
WORDINGS = { # the instruction line in other words, all naming four labels
'SYSTEM': SYSTEM,
'which topic': 'Which topic does this news headline belong to: World, '
'Sports, Business or Tech?',
'classify': 'Classify the news headline into one of four topics: '
'World, Sports, Business or Tech.',
'classify, topic only': 'Classify the news headline into one of four '
'topics: World, Sports, Business or Tech. '
'Answer with the topic only.'}
sel = np.arange(len(ITEMS)) if not SMALL else np.arange(0, len(ITEMS), 25)
titles, gold = list(TEST_TITLES[ITEMS][sel]), GOLD[sel]
chats = {name: [d2l.fewshot_prompt([], x, 'chat_multi', system=line)
for x in titles] for name, line in WORDINGS.items()}
preds = {(name, 'off, read-out'): d2l.label_logprobs(
inst, tok_i, c, NATURAL, batch_size=32, chat=True
).argmax(-1).numpy() for name, c in chats.items()}
replies = d2l.generate(inst, tok_i, chats['SYSTEM'], max_new_tokens=1024,
chat=True, enable_thinking=True, batch_size=50)
preds['SYSTEM', 'on, generated'] = np.array( # the answer after </think>
[answer(g.text.split('</think>')[-1]) for g in replies])
ref = (preds['SYSTEM', 'off, read-out'] == gold) * 1.0
rows = []
for (name, thinking), p in preds.items():
acc = (p == gold) * 1.0
label, top_share = top(p[p >= 0])
rows.append({'instruction': name, 'thinking': thinking,
'accuracy': acc.mean(), 'top label': label,
'top share': top_share, **(compare(acc[None], ref[None])
if name != 'SYSTEM' or thinking[:2] == 'on' else {})})
print(f'instruct, chat layout, k = 0, {len(sel)} items; '
'each row against SYSTEM with thinking off')
print_table(pd.DataFrame(rows).drop(columns='draws'))
p = preds['SYSTEM', 'on, generated']
cut = sum(g.finish_reason == 'length' for g in replies)
length = np.median([len(g.token_ids) for g in replies])
print(f'thinking on: {(p < 0).sum()} replies name no label by the rule, '
f'{cut} reach 1,024 tokens,\n median length {length:.0f} tokens')
del inst, replies # not needed below
gc.collect()
torch.cuda.empty_cache()instruct, chat layout, k = 0, 200 items; each row against SYSTEM with thinking off
instruction thinking accuracy top label top share diff lo hi
SYSTEM off, read-out 0.275 World 0.975
which topic off, read-out 0.310 World 0.855 0.035 -0.010 0.080
classify off, read-out 0.605 World 0.445 0.330 0.255 0.405
classify, topic only off, read-out 0.635 World 0.445 0.360 0.285 0.435
SYSTEM on, generated 0.700 Business 0.274 0.425 0.335 0.505
thinking on: 32 replies name no label by the rule, 1 reach 1,024 tokens,
median length 276 tokens
The collapse needs both: this sentence, and a model that is not allowed to think. Put as a question, the line does no better. It scores 0.31, with World in 85.5% of the predictions, and the difference of 3.5 points has an interval that includes zero. Told to classify, the same model scores 0.605, and 0.635 when it is also asked for the topic only. These are 33 and 36 points above our line, and neither interval reaches below 25. The largest change needs no new sentence at all. With thinking on, the line that failed scores 0.70, about 42 points more, and no label is preferred any longer: the most frequent one takes little more than a quarter of the replies that name a label. The 0.70 is a lower bound, since about one reply in six names no label by our rule and counts as wrong.
So the practice of telling a chat model its labels stands. It works when the line states the task as a classification, and it works when the model may reason before it answers. What failed was one sentence, read by a model that had to commit itself with its next token. Why “Name the topic” and “Which topic” send this checkpoint to World while “Classify” does not, four sentences cannot tell us.
The repair is not complete, and it is not free. Under both lines that say “Classify”, World still takes 44.5% of the predictions, nearly twice its share of the items. And accuracies of 0.6 to 0.64 lie in the range of the preferences that this model showed without any line, 0.575 in the chat layout and 0.68 in plain text. Thinking costs a median of nearly 300 generated tokens for each headline, where the read-out generates none. Note also that the cell prints no label mass for the new lines, so by our own rule we do not yet know whether their read-outs are the model’s answers (Exercise 5).
Of four sentences that any of us might have written, two failed. Whoever writes a system line should measure what it does.
18.3.3 Sensitivity to the Demonstrations
The experiments on order and on labels return to the reference condition for both models: eight demonstrations in the plain layout, without an instruction line, where the base model scores 0.75 and the instruct model 0.77.
18.3.3.1 Order
The eight demonstrations of a prompt have to come in some order, and nothing about the task says which. For each draw we score the same eight in four orders. The cell reports the accuracy of each order, the flip rate, which is the fraction of test items whose predicted label differs between two orders, and the standard deviation of accuracy over the four orders.
Is that standard deviation more than chance? Scoring the same prompts twice changes no prediction, so the chance in question is of another kind. The order might change single predictions, some for the better and some for the worse, without any order being better than another, and the four accuracies of a draw would then still differ a little. The function order_null simulates this null hypothesis. It shuffles each item’s four outcomes among the orders, which keeps the item’s difficulty and removes any systematic difference between orders. The \(p\)-value is the fraction of 2,000 shuffles whose standard deviation is at least the observed one. Read the row pooled of each model first.
ORDER_ACC = {}
p_text = lambda p: '<0.001' if p < 0.001 else f'{p:.3f}' # p >= 1/2001
for model in MODELS:
C = np.stack([correct(model=model, order=o) for o in range(4)], 1)
P = np.stack([pred(model=model, order=o) for o in range(4)], 1)
acc = ORDER_ACC[model] = C.mean(-1) # (draws, orders)
table = pd.DataFrame(acc, columns=[f'order {o}' for o in range(4)])
table['SD over orders'] = acc.std(1, ddof=1)
table['flip rate'] = np.mean([(P[:, a] != P[:, b]).mean(-1) for a, b in
itertools.combinations(range(4), 2)], 0)
p_draws = [order_null(C[s:s + 1])[1] for s in range(len(C))]
sd, p = order_null(C) # pooled over draws
table.loc['pooled'] = [*acc.mean(0), sd, table['flip rate'].mean()]
table['p (null)'] = [p_text(v) for v in p_draws + [p]]
print(f"{model}:\n{table.to_string(float_format='{:.3f}'.format)}")
print(f' SD over orders, mean over draws: {acc.std(1, ddof=1).mean():.3f}'
f'; SD over draws, order 0: {acc[:, 0].std(ddof=1):.3f}')base:
order 0 order 1 order 2 order 3 SD over orders flip rate p (null)
0 0.785 0.775 0.720 0.745 0.030 0.142 0.036
1 0.785 0.720 0.800 0.750 0.036 0.136 0.004
2 0.780 0.755 0.775 0.795 0.017 0.116 0.350
3 0.655 0.740 0.780 0.710 0.053 0.153 <0.001
4 0.730 0.785 0.795 0.745 0.031 0.118 0.011
pooled 0.747 0.755 0.774 0.749 0.033 0.133 <0.001
SD over orders, mean over draws: 0.033; SD over draws, order 0: 0.056
instruct:
order 0 order 1 order 2 order 3 SD over orders flip rate p (null)
0 0.760 0.750 0.765 0.745 0.009 0.154 0.876
1 0.805 0.750 0.790 0.770 0.024 0.115 0.094
2 0.765 0.775 0.770 0.810 0.020 0.087 0.094
3 0.755 0.750 0.790 0.715 0.031 0.134 0.023
4 0.750 0.800 0.825 0.775 0.032 0.124 0.005
pooled 0.767 0.765 0.788 0.763 0.023 0.123 0.004
SD over orders, mean over draws: 0.023; SD over draws, order 0: 0.022
The order changes about one prediction in eight, 13% for the base model and 12% for the instruct model. Accuracy moves less, because flips in the two directions cancel: its standard deviation over orders is 3.3 and 2.3 points. That is more than shuffling produces when pooled over the draws (\(p < 0.001\) and \(p = 0.004\)), so within a draw some orders are better than others. The draws differ a great deal, though. In draw 3 the base model ranges from 0.655 to 0.78 over four orders of the same eight examples, while in draw 2 its orders cannot be told apart.
Each block ends with the standard deviation over draws in one fixed order, 5.6 points for the base model and 2.2 for the instruct model. This is the spread that the intervals of our tables leave out. Five draws are too few to say whether order or the choice of demonstrations matters more, and Exercise 9 settles it with twenty of each.
Lu et al. (2022) documented this sensitivity, and Zhao et al. (2021) traced part of it to recency: the labels of the last demonstrations pull the prediction towards themselves (Exercise 8). The plot shows all forty accuracies.
x = [i + np.repeat(np.linspace(-0.3, 0.3, len(DRAWS)), 4) for i in (0, 1)]
d2l.plot(x, [ORDER_ACC[m].ravel() for m in MODELS], 'draws of each model',
'accuracy at k = 8', legend=MODELS, fmts=('o', 'o'), figsize=(4, 3))
ax = d2l.plt.gca()
ax.set_xticks([0, 1], MODELS)
for i, m in enumerate(MODELS): # draw means, then the model's mean
ax.hlines(ORDER_ACC[m].mean(1), x[i][::4] - 0.05, x[i][::4] + 0.05,
color=f'C{i}')
ax.axhline(ORDER_ACC[m].mean(), color=f'C{i}', linestyle='--', lw=0.8)Each column of dots is one draw in its four orders, with a bar at their mean, and the dashed lines are the means of the two models. The spread within a column is due to order alone. A few-shot accuracy that is quoted without further detail is one of these dots.
18.3.3.2 Label Correctness and Label Words
Do the demonstrations teach the model which label goes with which input? If so, wrong labels should do damage. Min et al. (2022) reported that random labels barely hurt, and concluded that demonstrations mainly convey the format, the set of labels and the kind of input. Wei et al. (2023) found that it depends on the size of the model: large models follow labels that contradict the meaning of the label words, and small ones do not. We run both tests at \(k = 8\).
In the first, a fraction \(\rho\) of the eight labels is replaced by wrong ones; at \(\rho = 0.75\) one label in four is right, as with random labels. In the second, every label \(y\) is replaced by \(\sigma(y)\), where \(\sigma\) is a permutation of the four classes that leaves none in place. The demonstrations are then perfectly consistent, and they consistently contradict the words: every sports headline is called, say, Business. We score the predictions against the true labels \(y\) and against the demonstrated mapping \(\sigma(y)\).
Both tests run with the natural label words and with the abstract words foo, bar, baz and zip. With abstract words the model can learn only from the pairing of inputs and labels, and a consistent relabeling merely renames the classes. Accuracy against \(\sigma(y)\) should then equal the accuracy at \(\rho = 0\), which gives us a control.
The cell prints the accuracies and, below them, differences with their intervals, of which we quote only some. Two notes help in reading the output. It calls the consistent relabeling deranged, after the name of a permutation that leaves nothing in place, a derangement. And in the first two rows of each model in the lower table, the column diff holds an accuracy with its interval.
RHOS = [0.0, 0.25, 0.5, 0.75, 1.0]
SIGMA_Y = np.stack([SIGMA[s][GOLD] for s in DRAWS]) # demonstrated labels
LABEL_ACC, rows, effects = {}, [], []
for model in MODELS:
for words in WORDS:
c = dict(model=model, words=words)
sigma = (pred(**c, derange=True) == SIGMA_Y) * 1.0
LABEL_ACC[model, words] = [correct(**c, rho=r).mean() for r in RHOS]
LABEL_ACC[model, words, 'sigma'] = sigma.mean()
rows.append({'model': model, 'words': words,
**dict(zip(map(str, RHOS), LABEL_ACC[model, words])),
'deranged vs y': correct(**c, derange=True).mean(),
'deranged vs sigma(y)': sigma.mean()})
if words == 'natural': # accuracies, each with its interval
for name, v in (('y', correct(**c, derange=True)),
('sigma(y)', sigma)):
d, lo, hi = paired_ci(v.mean(0))
effects.append({'model': model, 'effect': 'natural, '
f'deranged: accuracy against {name}',
'diff': d, 'lo': lo, 'hi': hi})
else: # the control: renaming abstract classes changes nothing
effects.append({'model': model, 'effect': 'abstract: sigma(y) '
'deranged minus rho = 0', **compare(
sigma, correct(**c, rho=0.0))})
drop = lambda w: (correct(model=model, words=w, rho=0.0) -
correct(model=model, words=w, rho=1.0))
effects += [{'model': model, 'effect': f'drop rho 0 to 1, {w}',
**compare(drop(w), np.zeros_like(drop(w)))} for w in WORDS]
effects += [
{'model': model, 'effect': 'drop rho 0 to 1, abstract minus natural',
**compare(drop('abstract'), drop('natural'))},
{'model': model, 'effect': 'natural: rho = 0.75 minus k = 0',
**compare(correct(model=model, rho=0.75),
correct(model=model, k=0))}]
print_table(rows)
print()
print_table(effects) model words 0.0 0.25 0.5 0.75 1.0 deranged vs y deranged vs sigma(y)
base natural 0.747 0.667 0.644 0.633 0.450 0.508 0.158
base abstract 0.313 0.297 0.280 0.243 0.200 0.208 0.324
instruct natural 0.767 0.710 0.704 0.635 0.545 0.516 0.136
instruct abstract 0.335 0.326 0.311 0.258 0.256 0.236 0.336
model effect diff lo hi draws
base natural, deranged: accuracy against y 0.508 0.454 0.564
base natural, deranged: accuracy against sigma(y) 0.158 0.135 0.181
base abstract: sigma(y) deranged minus rho = 0 0.011 -0.027 0.048 3/5
base drop rho 0 to 1, natural 0.297 0.249 0.347 5/5
base drop rho 0 to 1, abstract 0.113 0.083 0.145 4/5
base drop rho 0 to 1, abstract minus natural -0.184 -0.228 -0.143 4/5
base natural: rho = 0.75 minus k = 0 -0.017 -0.063 0.028 2/5
instruct natural, deranged: accuracy against y 0.516 0.468 0.565
instruct natural, deranged: accuracy against sigma(y) 0.136 0.114 0.158
instruct abstract: sigma(y) deranged minus rho = 0 0.001 -0.052 0.055 2/5
instruct drop rho 0 to 1, natural 0.222 0.182 0.263 5/5
instruct drop rho 0 to 1, abstract 0.079 0.048 0.110 4/5
instruct drop rho 0 to 1, abstract minus natural -0.143 -0.193 -0.093 4/5
instruct natural: rho = 0.75 minus k = 0 -0.045 -0.101 0.011 2/5
With natural words, accuracy falls as labels are corrupted. The base model goes from 0.75 with correct labels to 0.63 at \(\rho = 0.75\) and to 0.45 when every label is wrong, a drop of 30 points in all. The instruct model drops by 22. So the labels are read.
How does this square with Min et al.? Our numbers support one half of their account. The set of labels does carry much of the benefit: one line that named the labels gave the base model, without a single demonstration, the ten points that eight correct demonstrations gave it (Section 18.3.2.4). But wrong labels are not harmless here. With three labels in four wrong, as with random labels, eight demonstrations are no better than none: against \(k = 0\) the difference is \(-2\) points for the base model and \(-4.5\) for the instruct model, with intervals that include zero. Such demonstrations still display the label words and the form of the answer. If that display is worth the ten points that the line gave, the wrong labels cost about as much, and the two cancel.
With abstract words the models learn almost nothing. Eight correct demonstrations yield 0.31 and 0.335, a few points above the 0.25 of guessing. This is the most direct evidence in the section on how much these models learn from the pairing of inputs and labels alone: from eight examples, hardly anything. The control agrees, although so close to guessing it had little room to do otherwise: scoring the relabeled prompts against \(\sigma(y)\) changes accuracy by 1 point and by 0, with intervals from \(-3\) to 5 and from \(-5\) to 5.5.
The consistent relabeling with natural words gives one of the clearest results of the section. When eight demonstrations agree that sports is called Business, the models still give the true label for about half of the items (0.51 and 0.52) and follow the demonstrated mapping for about 15%, less often than a random guess would. At 1.7 billion parameters the meaning of a label word mostly outweighs eight consistent examples to the contrary, as Wei et al. found for small models. In the plot, open markers show the relabeled prompts scored against \(\sigma(y)\).
keys = [(m, w) for m in MODELS for w in WORDS]
names = [f'{m}, {w}' for m, w in keys]
d2l.plot(RHOS, [LABEL_ACC[key] for key in keys], 'fraction of wrong labels',
'accuracy', legend=names, xlim=(-0.05, 1.12), ylim=(0, 1),
fmts=('C0-o', 'C0--s', 'C1-o', 'C1--s'), figsize=(4.5, 3))
ax = d2l.plt.gca()
ax.legend(names, loc='lower center', bbox_to_anchor=(0.5, 1.0), ncol=2)
ax.axhline(0.25, color='gray', linestyle=':') # chance
for i, (m, w) in enumerate(keys): # derangement, scored against sigma(y)
ax.plot([1.06], [LABEL_ACC[m, w, 'sigma']], 'os'[i % 2], mfc='none',
color=f'C{i // 2}', markersize=8)Circles are natural words and squares are abstract words, and the dotted line is the accuracy of guessing. The open circles lie below it. It would be a stretch to say that these models learned the task from the demonstrations. They were told which task it was.
18.3.3.3 Contextual Calibration
A prompt can favor a label before the query is read. A single demonstration shows one label and no other, late demonstrations weigh more than early ones, and some label words are simply more frequent. Zhao et al. (2021) proposed to measure this preference and remove it.
The idea takes three lines. Suppose the read-out behaves like a posterior that combines evidence from the headline \(x\) with a prior \(\pi(y)\) that the rest of the prompt induces,
\[\log p(y \mid x) = \log q(x \mid y) + \log \pi(y) - \log Z(x),\]
where \(q(x \mid y)\) measures how well the headline fits label \(y\), and \(Z(x)\) normalizes. Now replace the headline by an input \(x_0\) without content, such as N/A. If such an input fits every label equally well, \(q(x_0 \mid y) = c\), the read-out returns the prior, \(\log p(y \mid x_0) = \log \pi(y) + \textrm{const}\). This is the bold step of the argument, and we will test it. Subtracting the prior from the first equation leaves
\[ \log p_\textrm{cal}(y \mid x) = \log p(y \mid x) - \log p(y \mid x_0) + \textrm{const}, \tag{18.3.2}\]
which is the posterior under a uniform prior. Take two labels with \(p(\cdot \mid x) = (0.6, 0.4)\) and \(p(\cdot \mid x_0) = (0.8, 0.2)\). The ratios are \((0.75, 2)\), which normalize to \((0.27, 0.73)\). The prompt favored the first label so strongly that a probability of 0.6 for it is evidence for the second, and the prediction flips.
Dividing by the prior is the correction for label shift of Section 3.6.3, applied here to a prediction, with the prior of the prompt as the source and a uniform target. The name should not be confused with the calibration of Section 3.4, which asks whether the confidence of a classifier matches its accuracy. d2l.calibrate_labels implements Equation 18.3.2. It averages the log-probabilities of several content-free inputs, and we call the resulting distribution over the labels the content-free prior.
def calibrate_labels(logprobs, content_free_logprobs):
"""Contextual calibration: subtract the mean log-probabilities (M, L)
of content-free inputs from logprobs (N, L) and renormalize over the
L labels; one content-free input may be given as an (L,) row. The
mean is taken in log space; Zhao et al. (2021) average the
probabilities instead."""
logprobs = torch.as_tensor(logprobs)
cf = torch.as_tensor(content_free_logprobs)
if cf.ndim not in (1, 2) or cf.shape[-1] != logprobs.shape[-1]:
raise ValueError(f'content-free log-probabilities {tuple(cf.shape)}'
f' are not (M, {logprobs.shape[-1]}) or '
f'({logprobs.shape[-1]},)')
return torch.log_softmax(logprobs - cf.reshape(-1, cf.shape[-1]).mean(0),
dim=-1)We apply it to both models in the plain layout at \(k = 0\), 1 and 4, with N/A, the empty string and [MASK] in place of the headline. The first table gives accuracy before and after, and the second the share of the most frequently predicted label, which is 0.25 for balanced predictions.
LP, n = ['lp0', 'lp1', 'lp2', 'lp3'], len(ITEMS)
item_boot = np.random.default_rng(0).integers(0, n, (2000, n))
draw_top_share = lambda p: (p[..., None] == np.arange(4)).mean(-2).max(-1)
CAL, acc_rows, share_rows = {}, [], [] # CAL: (before, after) predictions
for model, k in itertools.product(MODELS, (0, 1, 4)):
v = torch.tensor(grid_values(LP, IDS, model=model, k=k))
before = v[:, :n].argmax(-1).numpy() # (draws, items)
after = torch.stack([d2l.calibrate_labels(d[:n], d[n:])
for d in v]).argmax(-1).numpy()
CAL[model, k] = before, after
acc_rows.append({'model': model, 'k': k,
'before': (before == GOLD).mean(),
'after': (after == GOLD).mean(),
**compare((after == GOLD) * 1.0, (before == GOLD) * 1.0)})
change = draw_top_share(after) - draw_top_share(before) # per draw
lo, hi = np.percentile((draw_top_share(after[:, item_boot]) -
draw_top_share(before[:, item_boot])).mean(0),
[2.5, 97.5])
same = (np.sign(change) == np.sign(change.mean())).sum()
share_rows.append({'model': model, 'k': k,
'before': draw_top_share(before).mean(),
'after': draw_top_share(after).mean(),
'change': show({'diff': change.mean(), 'lo': lo,
'hi': hi, 'draws': 'n/a' if k == 0
else f'{same}/{len(change)}'})})
print('accuracy, before and after calibration')
print_table(acc_rows)
print('\nshare of the most-predicted label, before and after calibration')
print_table(share_rows)accuracy, before and after calibration
model k before after diff lo hi draws
base 0 0.650 0.685 0.035 -0.005 0.080 n/a
base 1 0.639 0.709 0.070 0.030 0.110 2/5
base 4 0.756 0.752 -0.004 -0.040 0.033 2/5
instruct 0 0.680 0.690 0.010 -0.040 0.065 n/a
instruct 1 0.696 0.729 0.033 0.005 0.062 4/5
instruct 4 0.674 0.682 0.008 -0.023 0.038 4/5
share of the most-predicted label, before and after calibration
model k before after change
base 0 0.370 0.350 -0.020 [-0.065, +0.020]
base 1 0.520 0.348 -0.172 [-0.211, -0.105] in 5/5 draws
base 4 0.318 0.342 +0.024 [-0.018, +0.064] in 3/5 draws
instruct 0 0.345 0.290 -0.055 [-0.095, +0.020]
instruct 1 0.441 0.328 -0.113 [-0.158, -0.038] in 5/5 draws
instruct 4 0.364 0.422 +0.058 [+0.016, +0.091] in 4/5 draws
A single demonstration makes the predictions lopsided. One label takes 52% of the predictions of the base model and 44% of those of the instruct model, and calibration brings both to about a third, in each of our five draws. Without demonstrations there was no comparable imbalance to remove. At \(k = 4\) calibration does the opposite for the instruct model: the share of its favorite label rises from 36% to 42%, with an interval for the change from 2 to 9 points, in four draws of five. A correction can add a preference as well as remove one.
Balance is not accuracy. Only one row of the first table passes our rule, the instruct model at \(k = 1\), with a gain of 3 points, an interval from 0.5 to 6 and four draws of five in agreement. The larger average gain of the base model has the same sign in only two draws. The next table looks at \(k = 1\) draw by draw: the label of the single demonstration, the probability that the content-free prior gives it, and the share of the predictions that go to it before and after calibration.
rows = []
for model in MODELS:
v = torch.tensor(grid_values(LP, IDS, model=model, k=1))
before, after = CAL[model, 1]
for s in DRAWS:
y = TRAIN_Y[DRAW[s][0]] # the one demonstrated label
prior = v[s, n:].mean(0).softmax(-1) # as calibrate_labels uses it
rows.append({'model': model, 'draw': s, 'demo': NATURAL[y],
'prior of demo': prior[y].item(),
'acc. before': (before[s] == GOLD).mean(),
'acc. after': (after[s] == GOLD).mean(),
'share before': (before[s] == y).mean(),
'share after': (after[s] == y).mean()})
print('k = 1, by draw; share: of the predictions, the demonstrated label')
print_table(rows)k = 1, by draw; share: of the predictions, the demonstrated label
model draw demo prior of demo acc. before acc. after share before share after
base 0 Tech 0.848 0.680 0.680 0.485 0.070
base 1 Business 0.977 0.570 0.710 0.650 0.135
base 2 World 0.854 0.575 0.820 0.525 0.165
base 3 Tech 0.910 0.640 0.615 0.505 0.090
base 4 Tech 0.881 0.730 0.720 0.435 0.115
instruct 0 Tech 0.807 0.670 0.720 0.515 0.350
instruct 1 Business 0.934 0.685 0.720 0.425 0.210
instruct 2 World 0.303 0.680 0.745 0.440 0.285
instruct 3 Tech 0.954 0.700 0.725 0.415 0.225
instruct 4 Tech 0.739 0.745 0.735 0.410 0.275
Before calibration the demonstrated label attracts 41 to 65% of the predictions. The content-free prior gives that label a probability between 0.74 and 0.98 in nine of the ten rows, and subtracting it overcorrects. For the base model the demonstrated label ends with 7 to 17% of the predictions, less than its fair quarter, in every draw. Here the bold step fails: the content-free input is not neutral. A model with nothing to read copies the one label it has seen more readily than it does when a real headline stands in front of it. So \(q(x_0 \mid y)\) favors the demonstrated label, the prior that we subtract is too strong, and Exercise 2 works out what follows.
Contextual calibration is therefore a correction for a visibly lopsided prompt, to be checked by the share of the predicted labels before and after. Balanced demonstrations remove the cause, which is better.
18.3.4 In-Context Learning and Weight Updates
18.3.4.1 Copying in Context
What does a model do when it uses its context? One mechanism is familiar. In Section 10.7 a two-block model completed random patterns that it had never seen. Its induction head attends to the token that followed the previous occurrence of the current token and copies it (Section 10.7.4.1), and such heads form in large language models too (Section 10.7.4.2). We look for their signature in the released model with the test used there, a sequence of random tokens that is repeated once.
We know what to expect. Whatever a model predicts, its expected cross-entropy on a target drawn uniformly from \(V\) tokens is at least the entropy of the target, \(\log V\). With the \(V = 151{,}643\) ordinary tokens of this vocabulary, no model can average less than 11.93 nats on the first copy, and a model that expects text will be above that. On the second copy, a model that copies should be close to zero.
V = tok.vocab_size # ordinary tokens; the ids above are special or padding
assert V == min(tok.added_tokens_decoder)
seq = torch.randint(0, V, (32, 64), generator=torch.Generator().manual_seed(0))
X = torch.cat([seq, seq], 1)[:8 if SMALL else 32]
losses = []
for chunk in X.split(8): # the full logits of 8 sequences at a time
chunk = chunk.to(base.device)
with torch.inference_mode():
logits = base(input_ids=chunk, use_cache=False).logits[:, :-1]
losses.append(F.cross_entropy(logits.float().transpose(1, 2),
chunk[:, 1:], reduction='none').cpu())
loss = torch.cat(losses) # loss[:, j]: predicting token j + 1
first, second = loss[:, :63].mean(1), loss[:, 64:].mean(1) # without 64
print(f'{len(X)} sequences of 2 x 64 tokens; bound ln {V:,} = '
f'{math.log(V):.2f} nats')
for name, v in (('first copy', first), ('second copy', second)):
print(f'{name}: {v.mean():.2f} nats per token (SD over sequences '
f'{v.std():.2f})')32 sequences of 2 x 64 tokens; bound ln 151,643 = 11.93 nats
first copy: 14.25 nats per token (SD over sequences 0.20)
second copy: 0.33 nats per token (SD over sequences 0.19)
The first copy costs 14.25 nats per token, above the bound as expected, and the second 0.33 nats, a geometric-mean probability of about 0.7 for the right token out of 151,643. Nothing but the context can tell the model what comes next.
Among the levels of evidence in Table 10.7.1 this is the weakest, behavioral evidence: it shows that the model copies, and it names no component that does the copying. Exercise 8 in Section 18.6 looks for the heads. We have already seen the same behavior inside a task, when the label of a single demonstration took 41 to 65% of the predictions.
Classifying a new headline asks for more than copying, since the right label must be chosen among those in the context. Whether a pretrained language model does this by something like a step of gradient descent on the demonstrations, which a single linear attention head can compute (Exercise 7 of Section 10.7), is disputed (Oswald et al. 2023; Shen et al. 2024). We leave the mechanism open and compare procedures instead: the same labeled examples go to in-context learning and to an explicit weight update, and we see which predicts better.
18.3.4.2 A Probe on Frozen Features
The simplest weight update that uses a pretrained model leaves the model alone. A probe is a linear classifier fit to features that a frozen model computes. Ours is deliberately plain. Its features are the last hidden states of the base model for a headline with no prompt around it, averaged over the tokens and standardized. To these it fits a logistic regression with an L2 penalty. Neither the layer nor the penalty is tuned.
def features(model, tokenizer, titles, batch_size=64):
"""Mean-pooled last hidden states of the titles alone, (n, d) fp32."""
out = []
for i in range(0, len(titles), batch_size):
enc = tokenizer(list(titles[i:i + batch_size]), padding=True,
return_tensors='pt').to(model.device)
pos = (enc.attention_mask.cumsum(-1) - 1).clamp(min=0)
with torch.inference_mode():
h = model.model(**enc, position_ids=pos,
use_cache=False).last_hidden_state.float()
m = enc.attention_mask.unsqueeze(-1).float()
out.append(((h * m).sum(1) / m.sum(1)).cpu())
return torch.cat(out).numpy()
def probe_accuracy(X_train, y_train, X_test, y_test):
"""Accuracy and log-probabilities of a logistic-regression probe on
standardized features (L2, C = 1) fit to the labeled examples."""
scale = StandardScaler().fit(X_train)
probe = LogisticRegression(C=1.0, max_iter=2000).fit(
scale.transform(X_train), y_train)
logp = probe.predict_log_proba(scale.transform(X_test))
assert logp.shape[1] == 4, 'every class needs a labeled example'
return (logp.argmax(1) == y_test).mean(), logpThe stored grid holds the predictions of the probe for every draw at 4 to 64 examples, the same titles that served as demonstrations, and at 256. One fit is repeated live.
K_PROBE = [4, 8, 16, 32, 64, 256]
if RERUN: # every draw and size; completes the regenerated grid
test_x, rows = features(base, tok, TEST_TITLES[ITEMS]), []
for s in DRAWS:
train_x = features(base, tok, TRAIN_TITLES[DRAW[s]])
for k in K_PROBE:
_, logp = probe_accuracy(train_x[:k], TRAIN_Y[DRAW[s][:k]],
test_x, GOLD)
cond = dict(COND, layout='none', k=k, seed=s)
rows += [head(cond, 'probe') + [i, *r, int(r.argmax()), 1]
for i, r in zip(ITEMS, logp)]
pd.concat([grid, pd.DataFrame(rows, columns=COLS)]).to_csv(
RERUN_PATH, index=False, float_format='%.6g')
grid = read_grid(RERUN_PATH)
with open(RERUN_PATH, 'rb') as f:
sha1 = hashlib.sha1(f.read()).hexdigest()
print(f'{RERUN_PATH}: {len(grid):,} rows, sha1 {sha1}')
m = matched(grid, registered, 'probe')
print(f'probe: {(m.pred == m.pred_old).sum():,} of {len(m):,} '
'predictions as registered')
elif not SMALL: # one fit, live: the 16 demonstrations of draw 0
train_x = features(base, tok, TRAIN_TITLES[DRAW[0]]) # batched as above
acc, logp = probe_accuracy(train_x[:16], TRAIN_Y[DRAW[0][:16]],
features(base, tok, TEST_TITLES[ITEMS]), GOLD)
same = (logp.argmax(1) == pred(exp='probe', layout='none', k=16)[0]).sum()
print(f'probe, draw 0, 16 examples: accuracy {acc:.3f}; {same} of '
f'{len(ITEMS)} predictions as registered')
else:
print('probe, draw 0, 16 examples: accuracy '
f'{correct(exp="probe", layout="none", k=16)[0].mean():.3f}\n'
'(the registered 1.7B run; without a GPU the probe is not fit)')probe, draw 0, 16 examples: accuracy 0.565; 200 of 200 predictions as registered
With the 16 demonstrations of draw 0 the probe reaches 0.565 and reproduces its stored predictions. The plot puts the probe beside the three in-context curves, and the table after it compares the in-context accuracy of the base model with the probe at equal numbers of labeled examples.
series = {'base, ICL (plain)': (K_BASE, dict(model='base')),
'instruct, ICL (chat)': (K_INST, dict(model='instruct',
layout='chat', instr=1)),
'instruct, ICL (plain)': (K_INST, dict(model='instruct')),
'base, probe': (K_PROBE, dict(exp='probe', layout='none'))}
acc = [np.array([correct(**c, k=k).mean(1) for k in ks]) # (k, draws)
for ks, c in series.values()]
at = lambda ks: np.log2(np.maximum(ks, 0.5)) # a log2 axis, 0 at the left
d2l.plot([at(ks) for ks, _ in series.values()], [a.mean(1) for a in acc],
'labeled examples', 'accuracy', legend=list(series),
ylim=(0.25, 0.85), fmts=[f'C{i}-o' for i in range(4)],
figsize=(5, 3.2))
ticks = sorted(set(K_BASE + K_PROBE))
ax = d2l.plt.gca()
for i in (0, 3): # the range over draws: base ICL and the probe
ks = list(series.values())[i][0]
ax.fill_between(at(ks), acc[i].min(1), acc[i].max(1), color=f'C{i}',
alpha=0.15, lw=0)
ax.set_xticks(at(ticks), [str(k) for k in ticks])
ax.legend(list(series), loc='lower center', bbox_to_anchor=(0.5, 1.0),
ncol=2); # above the axes, clear of the curvesrows = [{'examples': k, **compare(correct(k=k), correct(
exp='probe', layout='none', k=k))} for k in K_PROBE[:-1]]
print('ICL (base, plain) minus probe, at equal labeled data')
print_table(rows)
print(f'probe at 256: '
f'{correct(exp="probe", layout="none", k=256).mean():.3f}')ICL (base, plain) minus probe, at equal labeled data
examples diff lo hi draws
4 0.365 0.307 0.420 5/5
8 0.265 0.209 0.319 5/5
16 0.172 0.116 0.226 5/5
32 0.068 0.022 0.112 5/5
64 0.069 0.026 0.111 5/5
probe at 256: 0.759
The lines are means over the five draws, and the bands show the range over draws for the in-context curve of the base model and for the probe. The leftmost point of the instruct model’s chat curve is the zero-shot read-out that depends on the instruction line. In-context learning is ahead of this probe at every size we can compare, in all five draws. Its lead is 36.5 points at four examples and 17 at 16. At 32 and at 64 it is still 7 points, with intervals from about 2 to 11. The gap narrows and does not close. With 256 examples the probe arrives at 0.76, the accuracy that the prompt had with four to eight. A tuned probe on better features would presumably be closer, and we have not tried one.
The reason for the gap is not hard to see. The prompt starts from what the model knows about the word Sports. The probe starts from nothing and must find four directions in about two thousand dimensions from a handful of points. At the other end, long-context models keep improving for hundreds or thousands of demonstrations (Agarwal et al. 2024), a regime that our 64 only touch.
The comparison is at equal labeled data, and the costs are far from equal. A demonstration is processed again with every query, whereas the examples of the probe are processed once, when it is fit. The last cell counts the prompt tokens per query and the memory that they take in the key–value cache of Section 11.3, which stores a key and a value per token for each of 8 key–value heads in each of 28 layers.
cfg = base.config # K and V of every layer, per token, in bf16 as served
kv_bytes = (cfg.num_hidden_layers * 2 * cfg.num_key_value_heads *
cfg.head_dim * torch.bfloat16.itemsize)
probe_tokens = np.mean(n_tokens(tok, list(TEST_TITLES[ITEMS]))) # headline
rows = []
for k in K_BASE:
cond = dict(COND, k=k, seed=-1 if k == 0 else 0)
t = np.mean(n_tokens(tok, build_prompts(cond, TEST_TITLES[ITEMS])))
rows.append({'k': k, 'tokens per query': t, 'vs probe': t / probe_tokens,
'KV cache (MB)': t * kv_bytes / 1e6})
table = pd.DataFrame(rows)
table.insert(2, 'vs k = 0', table['tokens per query'] / table.iloc[0, 1])
print(f'probe: {probe_tokens:.1f} tokens per query; KV cache {kv_bytes:,} '
'bytes per token in bf16')
print_table(table, digits=1)probe: 10.0 tokens per query; KV cache 114,688 bytes per token in bf16
k tokens per query vs k = 0 vs probe KV cache (MB)
0 15.4 1.0 1.5 1.8
1 38.4 2.5 3.8 4.4
2 57.4 3.7 5.7 6.6
4 90.4 5.9 9.1 10.4
8 162.4 10.5 16.3 18.6
16 293.4 19.1 29.4 33.6
32 589.4 38.3 59.0 67.6
64 1163.4 75.5 116.5 133.4
A headline has 10 tokens, and that is all the forward pass of the probe reads. A 16-shot prompt has about 290 tokens, 30 times as many, and occupies 34 MB of cache; at 64 shots it has over a thousand tokens and 133 MB. This is the cost on a server that computes every prompt from scratch. The demonstrations are a prefix shared by all queries, so a server can compute their keys and values once, after which a query costs about its own tokens (Exercise 7).
Conditioning on demonstrations changes no weight and is repeated with every query. A probe changes the weights of a small classifier and leaves the model as it is. Fine-tuning changes the model itself. For a handful of labeled examples and a few queries the prompt is the right tool, by a wide margin. For a fixed task with hundreds of labeled examples and many queries, a fitted classifier reaches the accuracy of the 8-shot prompt and is far cheaper to run.
18.3.4.3 The Scope of a Few-Shot Score
What, then, does a few-shot score measure? The number that comes out belongs to everything that went in: the checkpoint, the template and its thinking switch, the instruction line, the demonstrations, their number and order, the label words, and the way the answer is read. A report should state all of them, average over draws and orders, and compare models only under the same prompt. We have varied all of these but the last. Apart from two comparisons with generated replies, every number in this section came from one next token, restricted to four words that we knew in advance, with the model’s thinking switched off. Most tasks have no answers of that kind: their options are whole sentences, or the answer is generated, or the model is meant to reason before it replies. The one time that we let a model reason, its accuracy rose from 0.275 to 0.70. How the way of reading an answer changes a score is the question of Section 18.4.
18.3.5 Summary
A prompt reaches the model as token ids, and for a chat model the template chooses them, down to the four tokens that switch thinking off. A label can be read from the next token by restricting the softmax to the label words, and the label mass says whether that read-out is the model’s answer or only its preference among words it would not write. On two checkpoints of 1.7 billion parameters, four tokens of an empty think block took the base model from 0.77 to chance, and one instruction line was worth eight demonstrations to one checkpoint and misled its sibling. The sibling recovered once the line said “Classify”, or once it was allowed to think. The demonstrations taught the form of the answer first, changed one prediction in eight through their order alone, and mostly failed to overrule the meaning of the label words. At equal labeled data, in-context learning beat a plain linear probe up to 64 examples, at many times the tokens per query.
18.3.6 Exercises
- Sample size for a paired difference. Two conditions are scored on the same \(n\) items. Their predictions differ in correctness on 15% of the items, and their accuracies differ by 3 points.
- Show that the standard error of the paired difference is close to \(\sqrt{0.15/n}\), and find the \(n\) at which the 95% half-width \(1.96 \sqrt{0.15/n}\) equals the difference of 3 points.
- If the two conditions were scored on different items, each accuracy near one half, how many items per condition would the same half-width take?
- Compute the paired half-width for the 200 items of this section and compare it with the intervals in the tables. How large must an effect of order or of layout be before 200 items can establish it?
- Contextual calibration, examined. Assume \(\log p(y \mid x) = \log q(x \mid y) + \log \pi(y) - \log Z(x)\).
- Write the constant in Equation 18.3.2 as a sum over the labels. Does it depend on \(x\), and can it change a prediction?
- Suppose the content-free input carries evidence, \(q(x_0 \mid y) = c(y)\). Show that the calibrated distribution keeps a bias \(-\log c(y)\). Which rows of the draw-by-draw table of Section 18.3.3.3 look like such a bias?
- Calibration adds one constant per class to the logits. Show that it cannot correct an item on which the evidence term \(q(x \mid y)\) itself ranks a wrong label first.
d2l.calibrate_labelsaverages log-probabilities over the content-free inputs, while Zhao et al. (2021) average probabilities. Construct two content-free distributions over two labels for which the two averages lead to different predictions for \(p(\cdot \mid x) = (0.6, 0.4)\). Which average is dominated by one confident content-free input?
- [code] Draw by draw. The tables of this section average over five draws. All parts run on the stored grid, without a GPU.
- In Section 18.3.2.3, draw 0 of the instruct model predicted two labels of four at \(k = 4\). The prompts of a draw are nested, so follow this draw in the plain layout from \(k = 1\) to \(k = 16\), and tabulate its accuracy and its predicted labels. At which \(k\) does the first label disappear, and at which \(k\) has the prompt recovered? The base model reads the same demonstrations. Does it stumble at the same \(k\)?
- For both models in the plain layout, compute the gain from \(k = 0\) to \(k = 4\) separately for each draw. Recompute the difference of the two gains, with its paired interval, without draw 0. How much of the mean difference of \(-0.11\) was the work of this one draw?
- The intervals of
compareresample items and keep the five draws fixed. Write a bootstrap that first resamples the draws with replacement and then the items. Apply it to the comparison of the chat layout with the plain layout for the instruct model at \(k = 8\) (Section 18.3.2.4), and to the same comparison at \(k = 4\), where one plain prompt collapsed. At which \(k\) does the interval now span zero? At \(k = 8\) it still excludes zero. Why does that not show that plain text is the better layout for this model?
- [code] Where the mass goes. The label mass says how much of the probability the labels hold. It does not say what holds the rest.
- For the four 4-shot prompts of Section 18.3.1.2, the labels hold 0.89 of the probability after the cup final and at most 0.16 after the other three headlines. Print the ten most probable next tokens of the base model after
Topic:for each prompt. Which tokens hold the probability that the four labels lack? Would other label words have collected more? - Print the same list for the instruct model in the chat layout, for the four headlines without demonstrations, with the
SYSTEMline and without it. How do the replies begin that do not begin with a label? - Add the four demonstrations as assistant turns and leave the line out. In Section 18.3.2.5 the label mass of such prompts was below 1%. What does the model begin to write? Leave the empty think block out of the end of the prompt and compare.
- For the four 4-shot prompts of Section 18.3.1.2, the labels hold 0.89 of the probability after the cup final and at most 0.16 after the other three headlines. Print the ten most probable next tokens of the base model after
- [code] The wording of the line. ● The cell that rewords the instruction line in Section 18.3.2.5 leaves three questions open. It deletes the instruct model when it is done, so work before that point.
- Compute the label mass over the 200 test items for each of the four wordings, as the table of label masses does for
SYSTEM. Which of the read-outs are the model’s answers? - Reverse the order of the labels in the line that says “Classify”. With
SYSTEM, reversing them took the share of World from 97.5% to 73%. What happens to its share of 44.5%, and to accuracy? Give paired intervals. - With thinking on, about one reply in six names no label by the rule. Read these replies. What do they write in place of a label word, and how many would a more lenient rule count as right? Why must such a rule be fixed before the replies are read?
- Compute the label mass over the 200 test items for each of the four wordings, as the table of label masses does for
- [code] Copying, position by position. The experiment of Section 18.3.4.1 averages the loss over each copy and leaves out the first token of the second copy.
- Why can no model predict that token?
- Plot the mean loss against the position for all 127 predicted tokens. How many tokens into the second copy does the loss fall below 1 nat, and why not at once?
- Append a third copy. Is it cheaper than the second? Repeat with sequences of 8 and of 256 tokens, and describe how the cost of the second copy depends on the length of the pattern.
- [code] Prefix caching. ● The demonstrations of a few-shot prompt are a prefix shared by all queries.
- For the 16-shot plain prompts of draw 0, check that the token ids of every prompt begin with the token ids of the shared prefix. At which character must the prefix end for this to hold?
- Run the base model once over the prefix with
use_cache=True, keep the returnedpast_key_values, expand them to the batch size, and compute the label log-probabilities of the 200 test items from the cached prefix. Check that the predictions equal those ofd2l.label_logprobsand that the log-probabilities differ by no more than batching did in the check of Section 18.3.1.2. - Time both paths with
d2l.Benchmark, and compare the speedup with the ratio of the prompt tokens at \(k = 16\) and at \(k = 0\) in the last table of the section. What limits the speedup?
- [code] Recency. ● For each draw and each class \(c\), reorder the eight demonstrations so that the two of class \(c\) come last, and score the 200 test items and the three content-free inputs with the base model in the plain layout.
- By how much does the share of predictions for class \(c\) exceed its share when the two demonstrations of class \(c\) come first? Give a paired interval.
- Apply
d2l.calibrate_labels. Does the excess disappear, and does accuracy change? Is recency a prior in the sense of Equation 18.3.2?
- [code] Order against draws. ●● A reported 8-shot accuracy is one draw in one order. For the base model in the plain layout, score 20 draws of eight demonstrations, each in 20 random orders, on the 200 test items.
- Estimate the variance of accuracy between draws and the variance between the orders of one draw, each with a bootstrap interval over draws and orders, after subtracting the part that item sampling alone contributes to each.
- Which of the two is larger? How many draws and orders should a report average over so that the standard error of its mean accuracy from these two sources is below one point?
- Repeat the permutation test of Section 18.3.3.1 for each of the 20 draws. In what fraction of draws is \(p\) below 0.05?
- [extended] A better prompt for the base model. ●● The base model scores 0.75 with eight demonstrations in the plain layout. Design a prompt that beats it by a margin that fresh draws confirm. You may change the layout (
qaandchat_singleof Section 18.3.2.1 are places to start), the format string, the instruction line, the label words and the order, but not the demonstrations. Develop the prompt on draws 0 to 4 and report it on five draws that you did not look at before, and say why that separation is needed. Report accuracy with paired intervals, the label mass, and the prompt tokens per query of each prompt.