GPT-2 · RoBERTa Lab · Part II — The GPT family
07

Decoding:
temperature, top-k and top-p

The model returns a distribution. Turning that into words is your decision — and it changes the result more than switching models does.

Chapter 07 of 15 Prerequisite: chapter 06

1 What the model really returns

There is a very widespread misunderstanding: that "the model chooses the next word". It does not choose. The model returns a score for each of the 50,257 tokens in the vocabulary — and stops there. Choosing is the job of a separate algorithm, which runs afterwards and which you control.

These raw scores are called logits. They range from −∞ to +∞ and do not sum to anything in particular. To become probabilities, they pass through the softmax:

P(token i) = exp(zi)Σj=150257 exp(zj) zi is the logit of token i. After this, the 50,257 numbers are positive and sum to 1.

From here on, everything is decoding strategy. And the choice of strategy accounts for an enormous share of perceived quality — switching from gpt2 to gpt2-xl often changes the text less than switching from greedy to top-p.

2 Greedy: always the most likely

token = argmaxi P(i) Take the winner and be done. Deterministic: same input, same output, every time.

It seems like the obvious choice — if we want the most likely text, we pick the most likely word at each step, right?

Wrong, and for two independent reasons.

Reason 1: greedy is not optimal

The most likely word right now can lead into a dead end where every continuation is bad. A slightly less likely word now could open up a much better sequence. Greedy never discovers this, because it never backtracks. It is the same problem as any greedy algorithm.

Reason 2: the most likely text is boring — and that is measurable

This is the deep reason, and it was demonstrated in an important paper (Holtzman et al., 2020, "The Curious Case of Neural Text Degeneration"). The authors measured the probability a model assigns to human-written text, and compared it with the text the model itself generates in greedy mode.

Result: human text is far less likely. Humans constantly pick surprising words. A text where every word is as predictable as possible does not sound human — it sounds like a scratched record.

gpt2, greedy, prompt "The capital of France is":

  "the capital of the French Republic, and the capital of the
   French Republic, and the capital of the French Republic..."

The loop is not a bug. It is the CORRECT behavior of greedy: once
the sequence enters a high-probability cycle, each repetition
makes the next one even more likely. It gets stuck.
The central paradox of text generation

Maximizing probability produces low-quality text. To sound human, you have to deliberately not always choose the most likely. Every technique in this chapter is a disciplined way of introducing surprise without introducing garbage.

3 Pure sampling, and why it fails too

The opposite extreme: draw the token according to the distribution. If " Paris" has 40% and " the" has 12%, you draw with those weights.

This fixes the repetition, but creates a new and treacherous problem: the long tail.

There are 50,257 tokens. Suppose the 50 thousand irrelevant tokens each have a minuscule probability of 0.001%. Individually, nothing. Summed: a 50% chance of a completely random token coming out.

In practice the distribution is more concentrated than that, but the effect is real: pure sampling produces text that goes along fine and suddenly plunges into a meaningless word — and, since the model is autoregressive, it now has to continue from that out-of-place word. One error contaminates everything that follows.

We need to cut the tail. The two ways of doing that are top-k and top-p.

4 Temperature: the boldness knob

Before the softmax, divide all the logits by a number T:

P(i) = exp(zi / T)Σj exp(zj / T) The name comes from statistical physics: in the Boltzmann distribution, temperature controls how much a system explores high-energy states. It is exactly the same equation.

Notice that it is the same operation as the √dk in attention (chapter 03). Dividing before the softmax controls how concentrated the distribution is.

Effect of temperature on an example with logits [4.0 · 2.0 · 1.0].
TEffectResulting distributionWhen to use
0.1almost greedy0.999 · 0.000 · 0.000factual answers, code
0.7conservative0.822 · 0.061 · 0.015the sensible default
1.0raw distribution0.665 · 0.090 · 0.033neutral
1.5creative0.506 · 0.131 · 0.067fiction, brainstorming
3.0chaotic0.332 · 0.171 · 0.122almost never
A detail that confuses many people

temperature=0 is a division by zero and, mathematically, undefined. Libraries treat it as a special case: T=0 becomes pure greedy. In transformers, the correct way is do_sample=False. Passing temperature=0 with do_sample=True either raises an error or is silently ignored, depending on the version.

5 Top-k: fixed cutoff

Keep only the k most likely tokens, zero out everything else, renormalize, and draw among the survivors.

k = 5, prompt "The capital of France is":

  kept:      ' the' 0.28 | ' Paris' 0.19 | ' a' 0.09 |
             ' now' 0.06 | ' one' 0.04
  discarded: the other 50,252 tokens
  renormalize to sum to 1 and draw.

Simple and effective. But it has a conceptual flaw: k is fixed and the distribution is not.

6 Top-p (nucleus sampling): adaptive cutoff

The elegant solution, available as a parameter in the main generation libraries and APIs. Instead of fixing how many tokens to keep, fix how much cumulative probability to keep:

  1. Sort the tokens from most likely to least.
  2. Keep adding up the probabilities.
  3. Stop as soon as the sum exceeds p (typically 0.9 or 0.95).
  4. Discard everything else, renormalize, draw.
V(p) = smallest set such that   Σx ∈ V(p) P(x) ≥ p The "nucleus" of the distribution. Its size changes at every step, automatically.

The real measurement, on this machine's gpt2

All with the same p = 0.9. The nucleus size varies by a factor of five thousand.
Context1st tokenP(1st)Nucleus p=0.9
"The United States of"" America"0.9661
"It was the best of"" times"0.59745
"The capital of France is"" the"0.0851,503
"He opened the door and saw"" a"0.1611,648
"Yesterday I went to the"" store"0.0235,548

Read the first and last rows together. In "The United States of" the model is 96.6% certain — the nucleus is a single token, and there really should be nothing to draw. In "Yesterday I went to the" it has no idea (the favorite has 2.3%) — and the nucleus opens up to 5,548 tokens, because anything is plausible there.

A fixed top_k=50 would treat the two situations the same: it would leave 49 bad candidates in the first and amputate the variety in the second. Top-p handles both with the same parameter, with no manual tuning. That is the whole insight.

A side finding that confirms chapter 06

Notice that "The capital of France is" lands in the doubt range, with a nucleus of 1,503 tokens and the favorite worth only 8.5%. gpt2 small is genuinely not confident about this question — which confirms, by a completely different route, what the logit lens (chapter 05) and the scale test (chapter 06) had already shown. Three independent measurements, the same conclusion. That is how you gain confidence in a result.

7 Repetition penalty, and the ready-made recipes

The repetition_penalty divides the logit of any token already used, discouraging repetitions. Values between 1.1 and 1.2 help a lot in small models. Above 1.3, the text gets strange — the model starts avoiding words that need to repeat, such as articles and prepositions.

Recipes that work. Start with these before inventing your own.
GoalConfigurationWhy
Factual / codedo_sample=Falsedeterministic and reproducible; repetition is an acceptable price
General usetemperature=0.7, top_p=0.9a common combination; balances coherence and naturalness
Creativetemperature=1.0, top_p=0.95more variety without opening the long tail
Small GPT-2temperature=0.8, top_p=0.9,
repetition_penalty=1.15
the small repeats a lot; the penalty compensates
Reproducing a resultany + fixed seedsampling with a fixed seed is deterministic
Common mistake: combining top-k and top-p without thinking

Libraries usually apply both in sequence (first top-k, then top-p). If you leave top_k=50 on together with top_p=0.95, top-k has already cut to 50 before top-p gets a chance to decide. In open contexts, where the nucleus would need 200 tokens, you never get there. If you want real top-p, turn top-k off (top_k=0).

8 Beam search — and why it is not used here

Beam search keeps b candidate sequences in parallel and at the end picks the one with the highest total probability. It solves greedy's problem 1 (greedy short-sightedness), but makes problem 2 worse: by searching even more effectively for the most likely sequence, it produces text that is even more predictable and repetitive.

That is why beam search is excellent for translation and summarization — tasks where there is one right answer and you want to find it — and bad for open-ended generation, where the goal is to sound natural. Do not use it to chat with GPT-2.

9 In the lab

.venv\Scripts\python.exe lab\07_decoding.py
  1. Shows the raw distribution of the next token for a prompt, with the 15 most likely candidates and their probabilities. It is the "raw material" that every strategy manipulates.
  2. Applies each temperature to the same distribution and shows the flattening happening, with the entropy measured.
  3. Measures the top-p nucleus size in confident and open contexts — the demonstration of adaptivity.
  4. Generates the same prompt with 6 different configurations, on the same model, with a fixed seed. The difference between the outputs is larger than between different models.
  5. Measures the repetition rate (fraction of repeated 4-grams) of each strategy. Greedy will come out above 50%.

Exercise 7 — predict before running

  1. With logits [4.0 · 2.0 · 1.0], compute the probabilities by hand with T=1 and T=2. (Hint: e²≈7.39, e¹≈2.72.) Confirm with the script.
  2. If p=1.0 in top-p, what happens? And if p=0.01?
  3. Why is high temperature with low top_p a strange combination? What does one do that the other undoes?
  4. Hard: temperature is applied to the logits before top-p. Does that matter? Consider a case where changing the order would change the set of surviving tokens.
References

The primary sources for the concepts in this chapter. The numbers in the text were measured in the lab; the ideas come from here.

Technical terms here carry their machine-learning meaning. The course glossary shows that meaning next to the others the same words have in IT.

  1. Holtzman, A., Buys, J., Du, L., Fang, M. and Choi, Y. (2020). The Curious Case of Neural Text Degeneration. ICLR 2020. arXiv:1904.09751
  2. Fan, A., Lewis, M. and Dauphin, Y. (2018). Hierarchical Neural Story Generation. ACL 2018. arXiv:1805.04833

We now know how the model predicts and how we choose among the predictions.
Chapter 08 goes back one step: what exactly it learned, and how that is measured with a single number.