Transformer Decoder Explained
← /learn

Sampling

Logits → next token. Greedy, temperature, top-k, top-p.

Check yourself ↓ three questions and what to remember, at the end

Generation is a loop: run the model, turn the last position's logits into a distribution, reshape and trim it, draw one token, append it, and go round again. Below, every step of that loop runs on your prompt, and the KV cache grows by one column per block each round. Move the temperature slider at any step to watch the distribution reshape.

Loading the animation…

The KV cache is why generation is cheap per token and expensive in memory: each round adds one key and one value column per block, and every later token reads them all. LLM Inference Explained's KV-cache chapter takes it from here: how big the cache gets, and what a server does about it.

Concept

The decoder gives you logits — one number per token in the vocabulary, for each position. The number at position i, vocab id v is "how plausible is it that the next token after position i is v?".

But logits aren't a token. To turn logits into a next token, we need a sampling rule. There are four standard ones:

  • Greedy — pick the highest-logit token. Deterministic, often dull.
  • Temperature τ — divide logits by τ before softmax. Low τ sharpens the distribution (closer to greedy); high τ flattens it (closer to uniform).
  • Top-k — keep only the top k logits, drop the rest, then sample from the survivors. Cuts off the long tail of unlikely options.
  • Top-p (nucleus) — keep the smallest set of tokens whose cumulative probability exceeds p. Adapts the cutoff to the local distribution.

Defaults vary by vendor and task; many APIs expose temperature, top-p and top-k together. Try it below — type a prompt, pick a mode, hit "sample" repeatedly to generate one character at a time.

Mode

Maths

For logits ℓ∈RV\ell \in \mathbb{R}^{V}, the softmax probability of token vv under temperature τ\tau is

p(v)=exp⁡(ℓv/τ)∑uexp⁡(ℓu/τ)p(v) = \frac{\exp(\ell_v / \tau)}{\sum_{u} \exp(\ell_u / \tau)}

Top-k sets the bottom V−kV - k logits to −∞-\infty before softmax, so their probabilities become exactly zero (zeroing a logit would still leave it probability mass). Top-p sorts tokens by probability, keeps the smallest prefix whose cumulative mass exceeds pp, and sets the rest to −∞-\infty.

After masking, the sampler draws u∼U[0,1)u \sim \mathcal{U}[0, 1) and walks the cumulative distribution: it returns the smallest ii such that ∑j≤ip(j)>u\sum_{j \le i} p(j) \gt u.

Code

// src/lib/transformer/sampling.ts (excerpt)
export function sample(logits: Vector, mode: SampleMode, rng = Math.random) {
  switch (mode.kind) {
    case "greedy":
      return argmax(logits);
    case "temperature":
      return sampleFromProbs(
        softmax(applyTemperature(logits, mode.temperature)),
        rng,
      );
    case "top-k": {
      const masked = topKMask(
        applyTemperature(logits, mode.temperature ?? 1),
        mode.k,
      );
      return sampleFromProbs(softmax(masked), rng);
    }
    case "top-p": {
      const masked = topPMask(
        applyTemperature(logits, mode.temperature ?? 1),
        mode.p,
      );
      return sampleFromProbs(softmax(masked), rng);
    }
  }
}

/api/compute/sample calls this directly. The widget passes the final position's logits, your chosen mode and parameters, and gets back a single token id.

Check yourself

Commit to an answer before you reveal it: a wrong guess you can explain teaches more than a right one you skimmed. Every number in the answers comes from the same tested model as the chapter’s.

Q1Three tokens have logits 2, 1 and 0. Halve the temperature from 1 to 0.5: what probability does the top token get now?
Reveal the answer

Answer: 86.7% (counted right within 5%)

86.7%, up from 66.5% at τ=1\tau = 1: dividing the logits by 0.5 doubles their gaps, so the softmax sharpens towards the top token. As τ→0\tau \to 0 sampling becomes greedy.

Temperature →

Commit to a number, then reveal.

Q2Same logits at τ = 1, top-p with p = 0.9: how many of the three tokens survive?
Reveal the answer

Answer: 2 (exact)

2. The top token alone has 66.5%, short of 0.9; adding the second takes the total past it, so the third is set to −∞-\infty and the two survivors are renormalised.

Top-p →

Commit to a number, then reveal.

Q3Suppose top-k set the dropped logits to 0 instead of −∞. Could they still be drawn?
Reveal the answer

Answer: Yes: e⁰ = 1, so they keep some probability

Yes: the softmax gives a logit of 0 the weight e0=1e^0 = 1, as much as any other logit of 0. Only −∞-\infty becomes probability exactly 0, which is why the masks use it.

Why −∞ →

Pick one, then reveal.


What happens at inference time → Sampling one token is one step of a loop that runs once per output token, for many users at once. The companion site, LLM Inference Explained, picks up here: the generation loop, the KV cache, batching, memory, speculative decoding, serving metrics and disaggregated serving, each with a live interactive.

Comments

Be the first to leave a comment on this section.

Sign in (top-right) to leave a comment.