Skip to content

How a language model picks its next token

Logits, temperature, top-k and top-p — and why the same prompt gives different answers. With runnable Python.

NZNarjis Zekhnini3 Nov 20263 min readDrafted with Inky · reviewed by Narjis

Every time a model writes a word, it is choosing from tens of thousands of candidates. That choice is not magic: it is a few lines of arithmetic you can write yourself.

From logits to probabilities

The last layer of a language model outputs one raw score per token in its vocabulary. These scores are called logits. They can be any real number, so we turn them into probabilities with the softmax function: exponentiate each score, then divide by the total.

import numpy as np
 
def softmax(z):
    z = z - z.max()          # subtract the max for numerical stability
    e = np.exp(z)
    return e / e.sum()
 
logits = np.array([4.1, 3.2, 2.2])   # scores for "the", "a", "this"
print(softmax(logits).round(2))      # [0.64 0.26 0.1 ]

Subtracting the maximum does not change the result, but it prevents exp from overflowing on large scores.

Temperature

Before softmax, many APIs divide the logits by a temperature T.

  • T < 1 makes large scores even larger relative to small ones: the model becomes more predictable.
  • T > 1 flattens the distribution: unlikely tokens get a real chance.
for T in (0.3, 1.0, 2.0):
    print(T, softmax(logits / T).round(2))
# 0.3 [0.95 0.05 0.  ]
# 1.0 [0.64 0.26 0.1 ]
# 2.0 [0.49 0.31 0.19]

A temperature of 0 is usually implemented as greedy decoding — always take the top token — rather than a division by zero.

Top-k and top-p

Sampling from the full vocabulary means a tiny chance of picking something absurd at every step. Two common filters cut off that long tail:

  • Top-k keeps only the k most likely tokens.
  • Top-p (nucleus sampling) keeps the smallest set of tokens whose probabilities add up to p, for example 0.9.
def top_p_filter(probs, p=0.9):
    order = np.argsort(probs)[::-1]
    cumulative = np.cumsum(probs[order])
    keep = order[: np.searchsorted(cumulative, p) + 1]
    filtered = np.zeros_like(probs)
    filtered[keep] = probs[keep]
    return filtered / filtered.sum()
 
def sample(logits, temperature=0.8, top_p=0.9, rng=np.random.default_rng()):
    probs = softmax(logits / temperature)
    probs = top_p_filter(probs, top_p)
    return rng.choice(len(probs), p=probs)

Top-p adapts to the situation: when the model is confident, only one or two tokens survive; when it is unsure, many do.

Why the same prompt gives different answers

With any temperature above zero, generation is a random draw at every step, and one different token early on changes everything after it. Even at temperature 0 you can see small differences, because GPU arithmetic on batched requests is not always perfectly deterministic.

If you need repeatable outputs for tests, use temperature 0, fix a seed where the API allows it, and compare meaning rather than exact strings.

Takeaways

  • A model outputs scores; sampling turns scores into words.
  • Temperature controls how spread out the choice is.
  • Top-k and top-p remove unlikely tokens before the draw.
  • For creative writing, raise the temperature; for extraction and code, keep it low.

Keep reading

Get the next tutorial by email

One email a week. No spam.

How a language model picks its next token · Tokenfield