Session S20

Decoding & Inference

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.

Two sessions share today's class, and HW3 is due Monday

Before the material, the course items for today and the next two sessions.

  • Today, S20 and S21 share one class: decoding and prompting on this deck, then alignment on S21's deck.
  • HW3 (Transformer from scratch) is due next session (S22, Monday) at 11:59 PM Pacific; the 12-hour grace period applies. Its 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.
  • Quiz 3 (Module 3) is at S23, in the final 30 minutes, in Canvas. It covers S13–S22, both of today's sessions included.
  • Project: the proposal is due at the end of the S23 week.

S19 adapted a pretrained model through a small update

S19 changed a pretrained model's weights, cheaply. From S19's answer:

  • Full fine-tuning costs about 16 bytes per trained parameter before activations (104 GiB for 7B), and a full model per task.
  • A low-rank update: freeze \(W\) and train \(\frac{\alpha}{r}BA\), \(r(d_{\text{in}}+d_{\text{out}})\) parameters; with \(B=0\), training starts at the pretrained model. Merged, the update is part of one matrix, so it costs nothing extra at inference.
  • Prompt tuning, one of LoRA's relatives, learns continuous virtual-token embeddings placed before the input, with the network frozen.

Today every weight stays fixed: we choose how to read the model's output, and what to put in its input.

Today's three parts follow the title page's three questions

Three parts, each answering one clause of the title page's question; a fourth closes. Then S21's deck.

partthe question it answers
1 · One step at a timewhat 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 samplershow 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 · Promptinghow can a prompt change the task without changing a weight? Examples placed in the prompt, and what is known about why that works
4 · Closefour 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.

At every step the model outputs a distribution; decoding picks one token

Part 1 · One step at a time. At each step the model outputs a probability for every possible next token:

Thecatprompt: where usersmeet the modelmodela probability for each possible next tokensatransleptisjumpedflewquantumlasagnadecodingpicks one tokensatappend it and run the model again: one step per token
  • In tensors: the model returns logits of shape (B, T, V) (S17); the next token uses the last position's row, \(V\) logits, through a softmax.
  • Decoding, the rule that picks one token from that distribution, changes the text without changing a weight: greedy decoding can loop on a phrase ("I don't know. I don't know."), while sampling varies the wording (slides 10 and 14).

Each new token runs the model once more. What does one step cost?

The KV cache keeps every token's key and value

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.

  • Without a cache, step \(t\) re-projects all \(t\) tokens (K = X[:t] @ W_k). We count work in MACs (multiply-accumulates: one multiply and one add, as in S14's \(T^2\) count).
  • The key-value (KV) cache projects each new token's key and value once and appends them.

# 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))
  
K_cacheV_cachek1v1t = 1q1k1v1k2v2t = 2q2k1v1k2v2k3v3t = 3q3each step appends one key rowand one value row (thick: new);the query scores every cached key

The cache gives the same outputs with 6× fewer projection MACs

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
  
naive: step t projects 2t + 1 rows1step t16294,912 MACscached: 3 rows at every step1step t1649,152 MACskey rowvalue rowquery roweach cell: one row through ad × d projection, d2 = 1024 MACs
  • Saved: one row through a \(d\times d\) projection is \(d^2\) MACs. Naive step \(t\) projects \(t\) keys, \(t\) values and 1 query: \(\sum_{t=1}^{16}(2t+1)\cdot32^2=(2\cdot136+16)\cdot1024=294{,}912\), since \(1+2+\cdots+16=136\). Cached, 3 rows a step: \(16\cdot3\cdot32^2=49{,}152\), a ratio of 6.0.

The cache does not remove the attention work

The cache saves projections. The scores and the memory are another matter.

  • Not removed: step \(t\) still scores \(t\) keys, so generation's total work stays quadratic, as in S14's \(T^2\) count.
  • The cost: the same run prints the cache's size.

cache size at T = 16: 2 * 16 * 32 floats per attention layer
  
scores at generation, T = 16keys →116step t scores t keysAll steps togetherfill a triangle:quadratic in T,as in S14's T2 count.K_cache(16, 32)V_cache(16, 32)2 · 16 · 32 floats per attention layer; each step adds one row to each (thick: new).an RNN's stateone vector,the same sizeat every step,the whole historycompressed into it

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.

Self-check on the cache's cost, size and outputs

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.

Four ways to pick the next token

Part 2 · Four samplers. Four rules for one distribution (\(T\) here is the temperature, not a length):

  • Greedy: the argmax at every step. Deterministic and locally optimal per step, which is not the same as the most probable sequence; known for loops ("I don't know. I don't know."), the neural text degeneration Holtzman et al. (2020) documented.
  • Temperature: \(p_i\propto\exp(z_i/T)\), where \(z_i\) is token \(i\)'s logit, the model's score before the softmax. \(T=1\) is the model's distribution; \(T<1\) sharpens it toward the mode; \(T>1\) flattens it; \(T\to0\) is greedy.
  • Top-k (Fan et al., 2018): keep the \(k\) most probable tokens, renormalize, sample. A fixed \(k\) is crude: too small when the distribution is flat, too large when it is peaked.
  • Top-p, or nucleus (Holtzman et al., 2020): keep the smallest top set whose cumulative probability reaches \(p\), renormalize, sample. Adapts to the distribution's shape.

The next two pages apply all four to reading 3.7's distribution after "The cat".

Greedy and temperature on one distribution

Reading 3.7's toy distribution: the model has read "The cat". Its eight logits \(z_i\) and their softmax:

greedy: the argmax, sat0.37210.22570.16720.11210.08300.03050.00680.0025sat2.0ran1.5slept1.2is0.8jumped0.5flew−0.5quantum−2.0lasagna−3.0probabilitypitokenlogit zi
  1. Any two tokens: \(p_i/p_j=e^{(z_i-z_j)/T}\): \(T>0\) scales every logit gap and never reorders.
  2. \(T\to0\): \(p_i=1/\sum_j e^{(z_j-z_i)/T}\). For the largest \(z_i\), all other terms go to 0 and \(p_i\to1\); for any other \(i\), the largest \(z_j\)'s term grows without bound and \(p_i\to0\): greedy.
  3. \(T\to\infty\): every \(z_i/T\to0\), so every \(p_i\to1/V\), here \(1/8\).

Temperature acts on the logits before the softmax, at inference; it changes no weight.

Top-k and top-p keep different sets from the same distribution

Top-k counts tokens. Top-p adds the probabilities, largest first, until the running sum reaches \(p\):

top-k, k = 3: three tokens0.37210.22570.16720.11210.08300.03050.00680.0025running sum reachesp = 0.9 at jumpedsat0.372ran0.598slept0.765is0.877jumped0.960flew0.991quantum0.997lasagna1.000probabilitytokenrunning sumkept by top-p, p = 0.9: five tokensdropped by top-p
  • Top-k, \(k=3\): sat, ran and slept, whatever their mass.
  • Top-p, \(p=0.9\): \(0.3721+0.2257+0.1672+0.1121=0.877<0.9\); adding jumped's \(0.083\) gives \(0.960\ge0.9\). The nucleus is the five tokens down to jumped.

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 samplers in reading 3.7's code

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,).
  • An excerpt: the full script (imports, 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?

10,000 samples per rule show the sharpening, the flattening and the cut

Yes: at \(T=2.0\) "sat" is still the most frequent (0.257). Reading 3.7's printed frequencies:

satransleptisjumpedflewquantumlasagnagreedyalways———————argmax: always sattrue dist.0.37210.22570.16720.11210.08300.03050.00680.0025the model's distributionT = 0.50.5770.2180.1160.0530.0320.0040.000—sharper: the mode rises 0.37 → 0.58,and the tail nearly vanishesT = 1.00.3660.2260.1680.1130.0870.0310.0070.002the true distribution, to samplingnoise (0.366 vs 0.3721)T = 2.00.2570.1910.1650.1400.1250.0670.0340.020flatter: lasagna rises 0.25% → 2%top-k, k = 30.4830.2950.222—————keeps 3 tokenstop-p, p = 0.90.3940.2300.1790.1160.081———keeps 5: the nucleus adaptsdown to jumpedA dashed outline is the true distribution; a dash means the token was never sampled or was filtered out.

Temperature trades diversity against fidelity, never reordering; top-k and top-p cut the tail.

Getting top-p right comes down to the boundary condition

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.

  • Correct rule: keep the smallest prefix whose cumulative mass reaches \(p\); drop token \(i\) only if the mass before it already reached \(p\): \(C_i-p_i\ge p\).
  • On the eight tokens: the mass before jumped is 0.877, below 0.9, so jumped stays; before flew it is 0.960, so flew goes. The top token always stays: the mass before it is 0.

The correct filter, in code

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,).
  • The buggy version, the reading's top_p_filter_buggy, differs in its keep line, sorted_idx[cum < p] with no shift, and returns zeros when nothing is kept.

Running both filters shows the bug and the fix

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.

01p = 0.9peakedflatyesthe other four0.97buggy: none, all zeros, so multinomial fails; correct: yes alone, as greedyyesnomaybeperhapspossibly0.850.95buggy stops at maybe; correct keeps perhaps, the token that crosses pboth rules keeponly the correct rule keepsboth dropThe buggy rule keeps a token if the mass up to and including it is below p;the correct rule keeps it if the mass before it is below p.

Decoding settings are part of your experiment

Two evaluations of the same checkpoint can differ dramatically when only the decoding differs (reading 3.7):

one checkpointgreedyT = 0.8, p = 0.95evaluationevaluationcan differdramaticallyWhen comparing models,fix and report:temperaturetop-k / top-pmax lengthstop conditionsthe seed, if sampling
  • Benchmark scores, "creativity" impressions, even safety behavior shift with sampling settings. A surprising result? Check the sampler before theorizing about the model.
  • This applies directly to your project evaluations; in HW3, generate's temperature is this setting.

Self-check on greedy, temperature and top-p

(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.

Prompting and in-context learning (ICL)

Part 3 · Prompting. GPT-3 (Brown et al., 2020): the task is shown in the prompt.

few-shot: k examples in the prompt (here k = 2)instructionsinput 1output 1input 2output 2new input?zero-shot: instructions onlyinstructionsnew input?modelweights fixed:no gradient updatesoutput
  • A prompt with \(k\) examples is \(k\)-shot; instructions alone, zero-shot. The paper reports ICL improving with model scale and with the number of demonstrations; on some benchmarks it approached fine-tuned models of the time.
  • How you prompt matters: chain-of-thought prompting (Wei et al., 2022) asks for intermediate reasoning steps and substantially improves multi-step problems.
  • Reordering, rephrasing or reformatting the demonstrations can shift accuracy by many points, so prompt-based evaluations need several prompts and error bars (S27).

Why ICL works is partially open

Three kinds of evidence, of different strength (reading 3.7):

  • Supported: next-token prediction on web text is implicitly multi-task; continued patterns, followed formats and obeyed instructions are all in the training distribution.
  • Mechanistic: Olsson et al. (2022) describe induction heads (below), with correlational and interventional evidence linking them to ICL.
    thecatsatonthematthecatsatThe head finds the earlier cat (dashed),attends to the token after it (thick), and copies it: sat.
  • Theoretical: Transformers can implement learning-like updates (gradient steps on a linear model, for example) in the forward pass, in stylized settings (von Oswald et al., 2023).

None of this fully explains what a 100B model does with your five examples: treat confident one-sentence explanations of ICL with suspicion.

Self-check on shots, prompt sensitivity and induction heads

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.

Four mistakes with samplers and prompts, with their causes and fixes

Part 4 · Close. Reading 3.7's three pitfalls, and one about settings:

symptomcausefix
generated text loops on a phrasegreedy or low-temperature decoding repeating a high-probability cyclesample with temperature or top-p; repetition penalties lower repeated tokens' scores but leave the cause
the error RuntimeError: invalid multinomial distribution on rare inputsa top-p filter that keeps tokens below \(p\) returns an empty nucleususe the shifted cumulative sum; unit-test the peaked case
few-shot numbers swing between runsthe choice, order and format of the demonstrations, with sampling noise on topevaluate several prompts and seeds; report the mean and the spread
two evaluations of one checkpoint disagreedifferent decoding settingsfix and report the temperature, top-k or top-p, the maximum length, the stop conditions, and the seed if sampling

A cached step, four sampling rules and the prompt answer today's question

Back to the title page's question, clause by clause.

  • What a step costs: one forward pass per new token. The KV cache stores each token's key and value once: the same outputs and 6× fewer projection MACs at 16 steps, for \(2d\) more floats per layer with every token; the scores stay quadratic.
  • How four samplers turn the distribution into text: greedy takes the argmax, locally optimal per step; temperature divides the logits by \(T\), sharper below 1, flatter above, greedy as \(T\to0\), never reordering; top-k keeps \(k\) tokens, and top-p the smallest set reaching \(p\), dropping a token only if the mass before it reached \(p\).
  • How a prompt changes the task: examples in the prompt condition the distribution, with no gradient updates. Why that works is partially open, and results move with the prompt, so report several.

Next in this class comes S21's deck, on alignment. The class's "For next time" is its last page.