Session S20
A trained language model outputs a probability distribution over the next token at every step. What does each step cost, how do four samplers turn that distribution into text, and how can a prompt change the task without changing a single weight?
Deep Learning · CS 4715/5715 · University of Idaho
S20 and S21 share this class: this deck first, then S21's.
Before the material, the course items for today and the next two sessions.
generate uses today's first two samplers: temperature=0 is greedy decoding, the argmax, and temperature>0 samples from softmax(logits / temperature). Top-k and top-p are not in the assignment.S19 changed a pretrained model's weights, cheaply. From S19's answer:
Today every weight stays fixed: we choose how to read the model's output, and what to put in its input.
Three parts, each answering one clause of the title page's question; a fourth closes. Then S21's deck.
| part | the question it answers |
|---|---|
| 1 · One step at a time | what does each generation step cost? What the model outputs at each step, and the cache that keeps each step's projection work constant |
| 2 · Four samplers | how do four samplers turn the distribution into text? The four rules worked by hand on one distribution, then sampled 10,000 times; a top-p bug and its fix; the settings every report needs |
| 3 · Prompting | how can a prompt change the task without changing a weight? Examples placed in the prompt, and what is known about why that works |
| 4 · Close | four common mistakes and today's answer; then S21's deck |
Reading-only today: beam search and the length penalty, speculative decoding, and constrained decoding (reading 3.7). Quiz 3's decoding question is about the four samplers.
Each of Parts 1–3 ends on a self-check. First, what the model outputs at each step.
Part 1 · One step at a time. At each step the model outputs a probability for every possible next token:
(B, T, V) (S17); the next token uses the last position's row, \(V\) logits, through a softmax.Each new token runs the model once more. What does one step cost?
S14's \(T^2\) count is for a whole sequence at once, as in training. At generation, each new token's query scores the keys of all tokens so far.
K = X[:t] @ W_k). We count work in MACs (multiply-accumulates: one multiply and one add, as in S14's \(T^2\) count).
# reading 3.2 (excerpt): d, T = 32, 16; X (T, d), a row per token
# W_q, W_k, W_v (d, d): S14's projections W_Q, W_K, W_V
# attend(q, K, V): S14's attention for one query; K, V are (t, d)
K_cache = np.zeros((0, d)); V_cache = np.zeros((0, d))
outputs_cached, proj_macs_cached = [], 0
for t in range(1, T + 1):
k_new = X[t - 1] @ W_k # one row, not t rows
v_new = X[t - 1] @ W_v
q = X[t - 1] @ W_q
proj_macs_cached += 3 * d * d
K_cache = np.vstack([K_cache, k_new])
V_cache = np.vstack([V_cache, v_new])
outputs_cached.append(attend(q, K_cache, V_cache))
Reading 3.2 ran the cached loop and the uncached one (K = X[:t] @ W_k every step) with \(d=32\), \(T=16\). Here step \(t\) is position \(t\): the toy has no prompt, and all 16 given rows are processed one per step. In a real model the prompt is first projected in one pass (prefill); each generated token is then one step. The outputs agree to 6.66e-16 (float64 round-off): the cache changes when numbers are computed, not what.
max |naive - cached| over all 16 steps: 6.66e-16
projection MACs, naive: 294,912
projection MACs, cached: 49,152
The cache saves projections. The scores and the memory are another matter.
cache size at T = 16: 2 * 16 * 32 floats per attention layer
The cache costs \(2\cdot T\cdot d\) floats per layer, growing with \(T\): attention keeps every token's key and value, while an RNN (S13) compresses the whole history into one fixed-size state.
Three questions on Part 1.
(a) Generate \(T=32\) tokens with \(d=32\); one row through a \(d\times d\) projection is \(d^2=1024\) MACs. Naive step \(t\) projects \(2t+1\) rows, cached 3. Total projection MACs each way, and their ratio?
(b) The cache holds a key row and a value row per token, each of length \(d\). Its size at \(T=32\), per attention layer?
(c) Does the cache change any output?
(a) \(1+\cdots+32=528\). Naive \((2\cdot528+32)\cdot1024=1{,}114{,}112\); cached \(32\cdot3\cdot1024=98{,}304\): about 11.3×, up from 6.0× at 16.
(b) \(2\cdot32\cdot32=2{,}048\) floats, twice the size at \(T=16\).
(c) No: the outputs agree to round-off. The cache changes when the projections are computed, not what.
That settles one step's cost. Next comes Part 2, which token to pick from the distribution.
Part 2 · Four samplers. Four rules for one distribution (\(T\) here is the temperature, not a length):
The next two pages apply all four to reading 3.7's distribution after "The cat".
Reading 3.7's toy distribution: the model has read "The cat". Its eight logits \(z_i\) and their softmax:
Temperature acts on the logits before the softmax, at inference; it changes no weight.
Top-k counts tokens. Top-p adds the probabilities, largest first, until the running sum reaches \(p\):
From one distribution, top-k keeps 3 tokens and top-p 5. A flatter distribution gives top-p more tokens, a peaked one fewer.
The reading samples each rule 10,000 times from the eight logits, shape (8,). One function holds three rules:
logits = torch.tensor([2.0, 1.5, 1.2, 0.8, 0.5, -0.5, -2.0, -3.0])
def sample(logits, n, temperature=1.0, top_k=None, top_p=None):
logits = logits / temperature
if top_k is not None:
kth = torch.topk(logits, top_k).values[-1]
logits = logits.masked_fill(logits < kth, float("-inf"))
p = F.softmax(logits, dim=-1)
return torch.multinomial(p, n, replacement=True)
topk(...).values[-1] is the \(k\)-th largest logit; masked_fill sets every smaller one to \(-\infty\); multinomial draws n indices from p, shape (n,).torch.manual_seed(0), the top-p branch) is in the reading, and the next page is its real output. Greedy there is torch.argmax(logits), not temperature=0 (dividing by 0 gives nan); HW3's generate treats 0 as the argmax.Predict: at \(T=2.0\), is "sat" still the most frequent token?
Yes: at \(T=2.0\) "sat" is still the most frequent (0.257). Reading 3.7's printed frequencies:
Temperature trades diversity against fidelity, never reordering; top-k and top-p cut the tail.
Sort the probabilities, largest first, and let \(C_i\) be the cumulative probability through token \(i\) (the running sum; the code's cum). The rule "keep tokens while \(C_i\) is below \(p\)" looks right and fails.
Predict: the buggy rule on \([0.97, 0.015, 0.008, 0.004, 0.003]\) with \(p=0.9\) keeps which tokens?
None: \(C_0=0.97>0.9\) already, so the output is all zeros (verified two pages on). Any token above \(p\) does this: a crash or garbage output.
Reading 3.7's top_p_filter: one distribution in, the renormalized nucleus out.
def top_p_filter(probs, p):
# probs: shape (V,), one next-token distribution (not a batch)
"""Smallest prefix of the sorted tokens whose cumulative probability >= p."""
sorted_p, sorted_idx = torch.sort(probs, descending=True)
cum = torch.cumsum(sorted_p, dim=-1)
# shift: a token is removed only if the mass BEFORE it already reached p,
# so the top token always survives
remove = cum - sorted_p >= p
keep = sorted_idx[~remove]
out = torch.zeros_like(probs)
out[keep] = probs[keep]
return out / out.sum()
remove = cum - sorted_p >= p is the previous page's rule: cum - sorted_p is the mass before each sorted token. sorted_p, cum and remove all have shape (V,).top_p_filter_buggy, differs in its keep line, sorted_idx[cum < p] with no shift, and returns zeros when nothing is kept.Reading 3.7 runs both filters on a peaked and a flat distribution of five tokens:
peaked distribution [0.9700, 0.0150, 0.0080, 0.0040, 0.0030], p=0.9
buggy -> [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]
correct -> [1.0000, 0.0000, 0.0000, 0.0000, 0.0000]
flat distribution [0.4000, 0.2500, 0.2000, 0.1000, 0.0500], p=0.9
buggy keeps ['yes', 'no', 'maybe'] -> [0.4706, 0.2941, 0.2353, 0.0000, 0.0000]
correct keeps ['yes', 'no', 'maybe', 'perhaps'] -> [0.4211, 0.2632, 0.2105, 0.1053, 0.0000]
The bug: cum < p drops the token whose running sum crosses \(p\). Peaked, that is the top token, so nothing is kept; flat, it is "perhaps", so the kept mass is 0.85, short of 0.9.
Two evaluations of the same checkpoint can differ dramatically when only the decoding differs (reading 3.7):
generate's temperature is this setting.(a) First token "the" (0.55) or "a" (0.45); after "the" every token has 0.25; after "a", "boat" has 0.9. Greedy's start? The more probable two-token start?
(b) Two tokens have logits 1.0 and 0.0. What is the ratio of their probabilities (the first over the second) at \(T=1\), 0.5 and 2? Does the more likely token change?
(c) \([0.6, 0.3, 0.1]\), \(p=0.8\): what do the buggy and the correct rule keep?
(a) "the", yet \(0.55\cdot0.25=0.1375\) against "a boat" \(0.45\cdot0.9=0.405\).
(b) \(p_1/p_2=e^{(1-0)/T}=e^{1/T}\): 2.72, 7.39, 1.65. The first token stays more likely at every \(T\).
(c) Sums 0.6, 0.9, 1.0. Buggy: the first only. Correct: the first two (the mass before them is 0 and 0.6).
Sampling chooses from the distribution; the prompt changes which distribution the model produces (conditioning, no gradient updates). Part 3 turns to the prompt.
Part 3 · Prompting. GPT-3 (Brown et al., 2020): the task is shown in the prompt.
Three kinds of evidence, of different strength (reading 3.7):
None of this fully explains what a 100B model does with your five examples: treat confident one-sentence explanations of ICL with suspicion.
Three questions on Part 3.
(a) A prompt holds an instruction, three solved examples and a new input. How many shots? Which weights change?
(b) 5-shot accuracy is 71% with one order of the examples and 64% with another. What do you report?
(c) A prompt ends "the dog ran home. the dog". What does an induction head predict next?
(a) 3-shot. None: it all happens in the forward pass, with no gradient updates.
(b) Neither number alone: evaluate several orders and phrasings, and report the mean and the spread.
(c) "ran": it finds the earlier "dog" and copies the token that followed it.
That settles prompting. Next comes the close, four mistakes and today's answer.
Part 4 · Close. Reading 3.7's three pitfalls, and one about settings:
| symptom | cause | fix |
|---|---|---|
| generated text loops on a phrase | greedy or low-temperature decoding repeating a high-probability cycle | sample with temperature or top-p; repetition penalties lower repeated tokens' scores but leave the cause |
the error RuntimeError: invalid multinomial distribution on rare inputs | a top-p filter that keeps tokens below \(p\) returns an empty nucleus | use the shifted cumulative sum; unit-test the peaked case |
| few-shot numbers swing between runs | the choice, order and format of the demonstrations, with sampling noise on top | evaluate several prompts and seeds; report the mean and the spread |
| two evaluations of one checkpoint disagree | different decoding settings | fix and report the temperature, top-k or top-p, the maximum length, the stop conditions, and the seed if sampling |
Back to the title page's question, clause by clause.
Next in this class comes S21's deck, on alignment. The class's "For next time" is its last page.