TExcelTAD
Home › Probability Theory › Sampling from Language Models

Sampling from Language Models

A language model does not write text directly. At each step it outputs a probability distribution over its vocabulary for the next token, and a sampling procedure picks one. Generation is therefore a random process, a Markov chain on prefixes, and its "settings" (temperature, top-k, top-p) are simple operations on probability distributions. This lesson explains them with the tools of this course.

From logits to probabilities

The model outputs a score (logit) ziz_i for every token ii. The softmax with temperature TT turns scores into probabilities:

pi=ezi/T∑jezj/Tp_i = \frac{e^{z_i / T}}{\sum_j e^{z_j / T}}
  • T=1T = 1: the model's own distribution.
  • T→0T \to 0: all mass on the highest logit (greedy decoding).
  • T>1T > 1: flatter, more random.

The entropy H=−∑ipilog⁡2piH = -\sum_i p_i \log_2 p_i measures how uncertain the distribution is, in bits; temperature moves it up or down.

python · try it yourself
import math

tokens = ["the", "a", "cat", "dog", "pizza", "quantum"]
logits = [3.0, 2.5, 1.5, 1.4, 0.2, -1.0]

def softmax(z, T):
    m = max(z)
    e = [math.exp((x - m) / T) for x in z]       # subtract the max for numerical stability
    s = sum(e)
    return [x / s for x in e]

for T in [0.2, 0.7, 1.0, 1.5]:
    p = softmax(logits, T)
    H = -sum(x * math.log2(x) for x in p if x > 0)
    print(f"T={T}: " + " ".join(f"{t}={x:.3f}" for t, x in zip(tokens, p)) + f"   entropy {H:.2f} bits")
T=0.2: the=0.923 a=0.076 cat=0.001 dog=0.000 pizza=0.000 quantum=0.000   entropy 0.40 bits
T=0.7: the=0.578 a=0.283 cat=0.068 dog=0.059 pizza=0.011 quantum=0.002   entropy 1.56 bits
T=1.0: the=0.474 a=0.287 cat=0.106 dog=0.096 pizza=0.029 quantum=0.009   entropy 1.90 bits
T=1.5: the=0.377 a=0.270 cat=0.139 dog=0.130 pizza=0.058 quantum=0.026   entropy 2.19 bits

Truncation: top-k and top-p

Even at T=1T = 1, a long tail of unlikely tokens collectively has noticeable probability, and sampling one of them can derail a text. Two common fixes keep only the head of the distribution and renormalise (a conditional distribution given "the token is in the kept set"):

  • top-k: keep the kk most probable tokens.
  • top-p (nucleus): keep the smallest set of top tokens whose total probability is at least pp; its size adapts to how confident the model is.
python · try it yourself
import math
import random
from collections import Counter

tokens = ["the", "a", "cat", "dog", "pizza", "quantum"]
logits = [3.0, 2.5, 1.5, 1.4, 0.2, -1.0]
e = [math.exp(z) for z in logits]
p = [x / sum(e) for x in e]

def top_k(p, k):
    keep = sorted(range(len(p)), key=lambda i: -p[i])[:k]
    s = sum(p[i] for i in keep)
    return {i: p[i] / s for i in keep}

def top_p(p, threshold):
    order = sorted(range(len(p)), key=lambda i: -p[i])
    keep, total = [], 0.0
    for i in order:
        keep.append(i)
        total += p[i]
        if total >= threshold:
            break
    return {i: p[i] / total for i in keep}

for name, dist in [("top-k=3", top_k(p, 3)), ("top-p=0.9", top_p(p, 0.9))]:
    print(name, {tokens[i]: round(q, 3) for i, q in dist.items()})

rng = random.Random(0)
dist = top_p(p, 0.9)
draws = Counter(tokens[i] for i in rng.choices(list(dist), weights=list(dist.values()), k=10_000))
print("10,000 draws with top-p 0.9:", dict(sorted(draws.items(), key=lambda kv: -kv[1])))
top-k=3 {'the': 0.547, 'a': 0.331, 'cat': 0.122}
top-p=0.9 {'the': 0.492, 'a': 0.299, 'cat': 0.11, 'dog': 0.099}
10,000 draws with top-p 0.9: {'the': 4884, 'a': 3017, 'cat': 1150, 'dog': 949}

Generation as a Markov chain

Each generated token is appended to the prefix, and the next distribution depends on the whole prefix. With a fixed context window, this is a Markov chain on the last few thousand tokens. The probability of a whole sequence is the product of the step probabilities (the multiplication rule), so its log-probability is a sum, and the perplexity 2−1n∑log⁡2p(tokent)2^{-\frac{1}{n}\sum \log_2 p(\text{token}_t)} is the effective number of choices per step.

python · try it yourself
import math
import random

# a toy "model": bigram probabilities
model = {
    "<s>": {"the": 0.6, "a": 0.4},
    "the": {"cat": 0.5, "dog": 0.4, "end": 0.1},
    "a":   {"cat": 0.3, "dog": 0.3, "pizza": 0.4},
    "cat": {"sat": 0.6, "ran": 0.3, "end": 0.1},
    "dog": {"sat": 0.3, "ran": 0.6, "end": 0.1},
    "pizza": {"end": 1.0},
    "sat": {"end": 1.0},
    "ran": {"end": 1.0},
}

def generate(rng, T=1.0):
    tok, out, logp = "<s>", [], 0.0
    while tok != "end":
        nxt = model[tok]
        w = [q ** (1 / T) for q in nxt.values()]          # temperature on probabilities
        tok2 = rng.choices(list(nxt), weights=w)[0]
        logp += math.log2(nxt[tok2])
        out.append(tok2)
        tok = tok2
    return " ".join(out[:-1]), logp, len(out)

rng = random.Random(1)
for _ in range(4):
    text, logp, n = generate(rng)
    print(f"{text:16s} probability {2 ** logp:.3f}  perplexity {2 ** (-logp / n):.2f}")
the dog ran      probability 0.144  perplexity 1.62
the cat ran      probability 0.090  perplexity 1.83
the cat ran      probability 0.090  perplexity 1.83
a cat sat        probability 0.072  perplexity 1.93

Determinism and seeds

With T=0T = 0 (greedy) or a fixed seed, generation can be reproducible; most APIs still have small sources of nondeterminism from parallel floating-point arithmetic. Lowering the temperature reduces variety but also makes repetitive loops more likely, which is why "repetition penalties" adjust logits of recently used tokens.

In software

Every chat model and code assistant exposes these settings. Low temperature suits extraction and code; higher temperature suits brainstorming. Techniques like self-consistency sample several answers and take a majority vote, an application of the law of large numbers to reasoning. The AI & LLMs course covers the models themselves.

Exercises

Exercise 1: Temperature extremes

Two tokens have logits 2 and 0. Find their probabilities at T=1T = 1 and T=0.5T = 0.5.

Answer

T=1T = 1: 0.8810.881 and 0.1190.119. T=0.5T = 0.5: 0.9820.982 and 0.0180.018.

Solution

p1=11+e−2/Tp_1 = \frac{1}{1 + e^{-2/T}}: 11+e−2≈0.881\frac{1}{1 + e^{-2}} \approx 0.881 and 11+e−4≈0.982\frac{1}{1 + e^{-4}} \approx 0.982.

Exercise 2: Perplexity

A model assigns probability 1/81/8 to every token of a 10-token text. What is the perplexity?

Answer
Solution

The average of −log⁡2p-\log_2 p is 3 bits, and 23=82^3 = 8: the model is as uncertain as a uniform choice among 8 tokens.

Exercise 3: Nucleus size (code)

For logits [5,4,3,2,1,0][5, 4, 3, 2, 1, 0], find how many tokens top-p keeps for p=0.5,0.9,0.99p = 0.5, 0.9, 0.99.

Answer

1, 3 and 5 tokens.

Solution
python · try it yourself
import math

z = [5, 4, 3, 2, 1, 0]
e = [math.exp(x) for x in z]
p = [x / sum(e) for x in e]
print([round(x, 4) for x in p])
for threshold in [0.5, 0.9, 0.99]:
    total, k = 0.0, 0
    while total < threshold:
        total += p[k]
        k += 1
    print(threshold, k)
[0.6337, 0.2331, 0.0858, 0.0315, 0.0116, 0.0043]
0.5 1
0.9 3
0.99 5

Test yourself

What happens to the next-token distribution as the temperature goes to 0?

  1. It becomes uniform
  2. All probability goes to the highest-logit token
  3. It becomes normal
  4. Nothing changes

Top-p (nucleus) sampling keeps…

  1. the pp most likely tokens
  2. the smallest set of top tokens with total probability at least pp
  3. tokens with probability above pp
  4. a random fraction pp of the vocabulary