9. Sampling & Generation

From probabilities to prose

At the end of a forward pass, the transformer outputs a vector of raw scores — one per vocabulary token — called logits. Run those through a softmax and you get a probability distribution: for every possible next word, a number between 0 and 1 that all sum to 1. The model has done its job. Now someone has to pick a token.

That "someone" is the sampling strategy, and the choice matters enormously. Pick the wrong one and your model becomes a broken record. Pick a good one and the same set of weights can produce everything from tightly constrained technical writing to wild, surprising creative prose.

Greedy Decoding

The simplest strategy: always pick the most probable token.

next_token = argmax(logits)

It's fast, deterministic, and terrible for long generations. The problem is that greedy decoding has no lookahead. Committing to the locally best token at step 5 might lead you into a dead end at step 10 — a phrase that forces a highly repetitive completion. Real text isn't like this; humans don't always say the statistically most expected next word.

In practice, greedy decoding tends to produce flat, generic output. Ask a greedy model to continue "The weather is" and you'll get "the weather is good" — correct, boring, and exactly the same every time you ask.

Temperature Scaling

Before the softmax is applied, you can divide all the logits by a temperature value T:

p(token) = softmax(logits / T)

Temperature as a Sharpness Knob

T < 1: dividing by a small number makes large logits larger and small logits smaller — the distribution sharpens, and the most likely token dominates. At T → 0, this becomes greedy decoding.

T = 1: no change. You sample from the model's raw distribution.

T > 1: logit differences shrink, the distribution flattens, and unlikely tokens become more competitive. Output becomes more varied and surprising — and eventually incoherent.

Here is what temperature does to the same distribution at three settings:

Diagram

Temperature scaling

T = 0.5 sharp / deterministic a b c d e T = 1.0 unchanged distribution a b c d e T = 2.0 flat / random a b c d e Same logits, same token b dominates — but how much depends on temperature

Most production APIs default to something like T = 0.7–1.0. Creative writing tools often expose the slider directly. Code generation models frequently run at lower temperatures where precision matters more than variety.

Top-k Sampling

Temperature sampling still assigns some probability to truly terrible tokens. Even at T = 0.7, a token that was almost certainly wrong can occasionally sneak through.

Top-k fixes this by truncation: only the k most probable tokens are kept in the pool. Everything else is zeroed out and the remaining probabilities are renormalized before sampling.

Top-k = 3 in action

Suppose the distribution over five tokens is:

TokenOriginal probabilityAfter top-3
cat0.400.47
dog0.280.33
ran0.170.20
the0.09excluded
xyz0.06excluded

You can still sample cat, dog, or ran, but the and xyz are off the table entirely — no matter how high you crank the temperature.

The weakness of top-k is that k is a fixed number regardless of context. In some positions the model is very confident (maybe only 2–3 tokens are plausible), and in others the distribution is genuinely spread across 50 candidates. Fixing k at 40 means being too permissive in high-confidence situations and too restrictive when the model is legitimately uncertain.

Top-p (Nucleus) Sampling

Top-p, introduced by Holtzman et al. in 2019, adapts the cutoff to the shape of the distribution. Instead of "keep the top k tokens", it says: sort tokens by probability descending, and keep adding until the cumulative probability reaches p.

Diagram

Top-p nucleus sampling

Top-p = 0.9 — nucleus sampling A B C D E F G 0.35 0.25 0.18 0.10 0.07 0.03 0.02 p = 0.9 included in nucleus excluded

The nucleus shrinks when the model is confident (maybe just two tokens cover 90% of the mass) and expands when it is uncertain (you might need 40 tokens to reach 90%). Top-p with p = 0.9 or 0.95 is the most widely used sampling strategy today.

Combining Strategies

In practice, temperature and top-p are almost always used together. A typical recipe:

  1. Apply temperature

    Divide logits by T before softmax, sharpening or flattening the distribution.

  2. Apply top-p cutoff

    Sort the resulting probabilities, accumulate from highest, drop the tail beyond p.

  3. Renormalize

    The remaining probabilities no longer sum to 1 — divide each by their sum.

  4. Sample

    Draw one token from the trimmed, renormalized distribution.

Setting temperature low (0.3–0.5) with top-p = 0.9 gives focused, reliable output. Setting temperature high (1.0–1.2) with top-p = 0.95 gives varied, exploratory output. Most user-facing products tune these defaults carefully per use-case.

Repetition Penalty

Even with top-p and temperature, models can get stuck in repetitive loops. If "the quick brown fox" keeps appearing, the model has learned that this sequence is probable — so it keeps predicting it.

A repetition penalty addresses this by downscaling the logit of any token that has already appeared in the output. The penalty factor α > 1 divides the logit before softmax:

penalized_logit = logit / α  (for tokens already seen)

A value around 1.1–1.3 is typical. Too high and the model starts avoiding words it needs to repeat (common function words like "the", "is", "a") — output becomes stilted. Too low and loops persist.

Beam Search

All of the above strategies are single-path — they commit to one token at each step and move on. Beam search maintains k candidate sequences in parallel (the "beams"), expands each one by one step, then keeps only the k highest-scoring sequences across all expansions.

Beam search with k = 2

Start: two beams, both empty. At step 1, expand each by the top-2 tokens:

BeamSequenceLog-prob
1The−0.3
2A−0.8

At step 2, expand both beams and keep the top-2 overall:

BeamSequenceLog-prob
1The cat−0.7
2The dog−1.1

Notice that both surviving beams start with "The" — "A" was outcompeted. The algorithm finds the globally highest-scoring sequence within its budget.

Beam search is deterministic and produces high-probability output — great for machine translation and summarization where a single best answer is desired. For open-ended generation it produces bland, over-generic text for the same reason greedy decoding does: high probability is not the same as interesting.

Why Randomness Matters

This might seem counterintuitive. We trained a model to be accurate — why would we deliberately inject randomness?

The answer is that language is genuinely ambiguous. Given "Once upon a time, there was a", there are thousands of perfectly valid, interesting continuations. The model has learned a distribution over all of them. If you sample from that distribution, you get variety that reflects the real space of possibilities. If you always pick the mode, you collapse that entire space to a single boring path.

There's also a practical problem with purely deterministic decoding: once a model starts down a suboptimal path, it doubles down. Sampling provides an escape hatch.

Key Takeaways

  • After the forward pass, the model outputs logits — raw scores over the vocabulary
  • Greedy decoding picks the top token every time: fast, deterministic, repetitive
  • Temperature T scales logits before softmax — T<1 sharpens, T>1 flattens, T=1 is unchanged
  • Top-k sampling restricts selection to the k most probable tokens at each step
  • Top-p (nucleus) sampling keeps the smallest set of tokens whose cumulative probability reaches p — the nucleus adapts to the distribution shape
  • Temperature and top-p are usually combined; most APIs expose both as parameters
  • Repetition penalty discounts already-seen tokens to break repetitive loops
  • Beam search maintains k candidate sequences in parallel and is preferred for tasks needing a single best output
  • Randomness in sampling isn't a bug — it reflects genuine ambiguity in language and avoids degenerate repetition

Try It — Sampling Playground

A fixed probability distribution over 15 tokens is shown as faded background bars. Change the sampling strategy and parameters to see the modified (eligible) distribution overlaid in colour. Hit Sample to draw one token; Sample 10 to generate a short sequence.


Sampling determines how a model generates output. The next question is whether that output is actually aligned with what we want — whether the model is helpful, honest, and safe. That's the domain of alignment, which is where the real difficulty lies.