# How does a model pick the next word?

Alfonso Campodonico · 2026-11-24 · https://alfonsocampodonico.com/posts/how-does-a-model-pick-the-next-word

> The model only ranks the options. A few lines of code after it do the picking.

## Why the same question gets different answers

Ask a chatbot the same question twice and you'll often get two different answers. People take that as a sign the model is moody, or thinking. It isn't. The model gives the same scores both times. What changes is a dice roll that happens after the model has finished.

In [What happens after you hit send](/posts/what-happens-after-you-hit-send) I covered that roll in two bullet points. This post is about those two bullets: what the model hands back, how a sampler turns it into one word, and what the settings called temperature, top-k, top-p and min-p actually do.

The short version: the model ranks every possible next token. The sampler reshapes that ranking, cuts off the long tail and draws one at random. All the settings you've seen in an API are knobs on those three steps.

## How it works, in one minute

Picture a chef halfway through a dish, deciding what to add next.

1. **A hunch for everything.** The chef has a gut score for every ingredient in the pantry. Salt is a strong yes. Cinnamon, probably not. Soap, never. Those scores are **logits**, one per token in the vocabulary.
2. **Hunches into odds.** The chef turns the scores into a raffle: every ingredient gets tickets, and the strong hunches get far more of them. That's **softmax**.
3. **How adventurous tonight?** A cautious chef gives almost every ticket to the favourite. A bold one spreads them out. That's **temperature**.
4. **Clear the pantry.** Before drawing, the chef throws out the long shots: keep the top five, or keep whatever covers 90% of the tickets, or keep anything at least a tenth as appealing as the favourite. Those are **top-k**, **top-p** and **min-p**.
5. **Draw a ticket.** One ingredient goes in. Then the chef tastes again and repeats, one ingredient at a time, until the dish is plated. Plating is the **end-of-sequence token**.

A chef who always adds the favourite cooks the same dish every night, and sometimes gets stuck adding salt forever. That's **greedy decoding**, and it's why most chat uses the raffle.

## The deep dive

The rest of this post takes the same steps with real names and numbers. The consoles use made-up scores for a handful of tokens, but the maths is the real thing: the same softmax, cuts and draws an inference server runs.

## Scores: one number per token

At the top of the model, the last position's vector is multiplied by one big matrix. Out comes one number for every token in the vocabulary: about 128,000 numbers for a Llama 3 model. Those are the logits. They're not probabilities. They can be negative, they don't add up to anything, and only the gaps between them matter.

Softmax turns them into probabilities. Raise *e* to the power of each logit, then divide each one by the total. Big logits become most of the total, small ones become nearly nothing, and the result adds up to 1.

Temperature sits inside that step. Every logit is divided by the temperature before the exponent:

```txt
p(token) = exp(logit / T) / sum of exp(logit / T) over every token
```

- **T below 1** stretches the gaps, so the favourite takes even more of the odds.
- **T above 1** shrinks them, so the long shots get a real chance.
- **T of 0** would divide by zero, so servers special-case it: always take the highest logit.

Temperature never changes the order. " blue" stays the favourite at any temperature. It only changes by how much.

*Interactive diagram on the page: From scores to odds.*

## Cutting the tail: top-k, top-p, min-p

With 128,000 tokens, the tail is enormous. Each token in it is unlikely, but together they can add up to a few percent. Draw a hundred tokens and one of them is likely to come from the tail, and one bad token can derail the rest of the answer. So samplers cut the tail off before drawing:

- **Top-k** keeps the *k* likeliest tokens[^topk]. It's simple, but *k* doesn't adapt: 40 options is too many after "The capital of France is", and too few at the start of a poem.
- **Top-p**, or nucleus sampling, keeps the smallest set of the likeliest tokens whose probabilities add up to *p*[^topp]. When the model is sure, that's one or two tokens. When it isn't, it's hundreds.
- **Min-p** keeps every token at least *p* times as likely as the favourite[^minp]. With min-p 0.1 and a favourite at 0.6, anything under 0.06 goes. It scales with how confident the model is, like top-p, and it holds up better at high temperatures.

After a cut, the survivors' probabilities are scaled back up so they add up to 1 again. The cuts can be stacked. The order varies by server, but most apply temperature first and the cuts after it.

*Interactive diagram on the page: Cutting the tail.*

## Rolling the dice

The draw itself is plain. Line the survivors up, give each a stretch of the number line as wide as its probability, pick a random number between 0 and 1 and see whose stretch it lands in. A token at 0.57 wins about 57 draws in 100.

That's the whole source of variety. Over many draws, the counts settle to the odds. Over one draw, anything that survived the cut can come up.

*Interactive diagram on the page: A hundred draws.*

## Greedy is worse than it sounds

Always taking the favourite sounds like the safest choice. For short, factual answers it often is. Over a long answer it goes wrong in two ways:

- **It's bland.** The single likeliest next token is usually the most generic one. Strung together, they make text that reads like nobody wrote it.
- **It loops.** Once a phrase repeats, the repetition makes the same phrase likelier, and greedy has no way out. The model talks itself into a circle.

Sampling gets out of both, because now and then it takes the second or third choice. Below, the scores at each step come from nine scripted answers to "Why is the sky blue?". At temperature 0 every run is the same answer. Turn the temperature up and they start to differ.

*Interactive diagram on the page: Same question, five answers.*

## Other knobs on the same scores

Everything else in an API's sampling settings edits the logits before the draw:

- **Repetition penalties.** Frequency and presence penalties lower the logit of tokens that have already appeared, by a fixed amount or by how often. They're a blunt fix for looping.
- **Logit bias.** Add or subtract a fixed amount for specific token IDs. Set one to a large negative number and that token can never come up.
- **Constrained decoding.** Before each draw, the server works out which tokens could continue valid JSON (or a schema, or a grammar) and sets every other logit to minus infinity[^grammar]. The model still picks, but only among tokens that keep the output parseable. That's how "structured outputs" can promise valid JSON.

None of these change the model. They all happen in the few lines between its output and the draw.

## When to stop

The loop stops in one of three ways:

- **The end-of-sequence token comes up.** It's in the vocabulary like any other token, and the model learned during training to rank it high when an answer is done. It's drawn like any other token, too.
- **A stop sequence appears.** The caller can name strings, like `"\n\nUser:"`, that end the answer as soon as they're written.
- **The token limit is hit.** The answer is cut off mid-sentence. APIs report which of the three it was, so you can tell a finished answer from a truncated one.

## Why temperature 0 isn't always the same answer

In theory, temperature 0 is fully deterministic. In practice, the same prompt at temperature 0 can still give two different answers. The model isn't drawing at random. The scores themselves wobble.

GPUs add numbers in whatever order is fastest, and floating-point addition isn't associative: `(a + b) + c` can differ from `a + (b + c)` in the last bit. The order depends on how many other requests share the batch, which changes from second to second. When two tokens have nearly equal logits, a last-bit difference can flip which one wins, and from that token on, the answers diverge[^nondeterminism].

A seed fixes the dice, not the scores. It gets you the same draws, and on a quiet server that usually means the same answer, but it's not a promise.

## What I'd set

- **Code, extraction, anything you'll parse:** low temperature, 0 to 0.3, and constrained decoding if the output has a shape.
- **Normal chat:** the provider's defaults. They're tuned for their model.
- **Brainstorming:** a higher temperature, with min-p or top-p to keep the tail out.

And change one knob at a time. Temperature and top-p both control how much of the tail gets through, so moving both at once makes it hard to tell which one did what.

[^topk]: Introduced for story generation in [Fan, Lewis and Dauphin, 2018](https://arxiv.org/abs/1805.04833).
[^topp]: From [Holtzman et al., 2019](https://arxiv.org/abs/1904.09751), which is also the paper that named greedy's blandness and looping "neural text degeneration".
[^minp]: [Nguyen et al., 2024](https://arxiv.org/abs/2407.01082).
[^grammar]: Open-source libraries for this include [Outlines](https://github.com/dottxt-ai/outlines) and [XGrammar](https://github.com/mlc-ai/xgrammar).
[^nondeterminism]: Thinking Machines traced this to kernels that aren't batch-invariant, and showed how to fix it, in [Defeating Nondeterminism in LLM Inference](https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/).
