SysDesignAtlas

Decoding & Sampling

How logits become tokens, why temperature and top-p behave the way they do, constrained decoding for structured output, and speculative decoding — the trick that gets latency for free.

CoreMedium12 min readaidecodingsamplingspeculative
Confidence

#The last step of every forward pass

A forward pass doesn't end with a word. It ends with a score for every token in the vocabulary — one number each, maybe 100,000 of them, called logits. Something then has to convert those scores into a single chosen token, and that choice is the decoding strategy.

It's the cheapest place in the entire stack to change how a model behaves: no retraining, no redeployment, one configuration value.

   hidden state  ──►  unembedding  ──►  logits (one per vocab token)
                                             ↓
                                        softmax / sampling
                                             ↓
                                        one token ID
                                             ↓
                                     appended, loop again

#Temperature

The scores are turned into probabilities by a step called softmax, which squashes them so they're all positive and add up to one. Temperature is a single number that divides the scores before that step: low temperature exaggerates the gaps between them and makes the top choice near-certain; high temperature flattens them and gives unlikely tokens a real chance.

Temperature 0 is greedy decoding, and it is not the same as "the best answer." Greedy picks the highest-probability token at every step. The best-looking word now can commit the sentence to a direction where every later option is poor — like always taking the street that points most directly at your destination and ending up in a dead end. It also produces repetition loops, because the highest-probability continuation of a repeated phrase is often to repeat it again.

#Truncation: top-k and top-p

The problem with pure sampling is the tail — the long list of individually unlikely tokens. In a vocabulary of 100,000 tokens, 99,000 may each have a tiny probability, but together they can still add up to a noticeable share. Sampling from that share occasionally picks a genuinely incoherent token. And because every later token is generated from everything before it, that one bad token drags the rest of the output off course.

   TOP-K (k = 40)              TOP-P / NUCLEUS (p = 0.9)

   keep the 40 most likely     keep the smallest set whose
   renormalise, sample         cumulative probability ≥ 0.9

   Fixed count, regardless     Adaptive:
   of how confident:             confident step → maybe 2 tokens
     confident step → still      uncertain step → maybe 300
     considers 40 options
                               → matches the model's own
   → too permissive when         uncertainty
     confident, too narrow
     when uncertain

Top-p (nucleus) is the better default, precisely because it adapts. When the model is sure the next token is " it considers almost nothing; when it's writing creative prose it considers a wide set. Typical production settings: temperature 0.7, top_p 0.95 for general use; temperature 0 for extraction, classification, and anything where you want reproducibility.

Two more knobs you'll see:

  • Min-p — keep tokens with probability at least min_p × max_prob (with min_p = 0.1 and a top token at 60%, keep everything above 6%). Because the cut-off moves with the top token's confidence, it behaves better than top-p at high temperature, where flattening lets top-p's set fill up with junk.
  • Repetition / frequency / presence penalties — subtract from the logits of tokens already emitted. Blunt instruments; they suppress legitimate repetition too (a variable name in code, a word in a list). Prefer fixing the prompt.

#Constrained decoding

If the output must be valid JSON matching a schema, you can guarantee it rather than hope for it — by masking out every token that would make the output invalid, before sampling.

   Target schema:  { "name": string, "age": integer }

   Generated so far:  {"name": "Ada", "age":

   Valid next tokens: digits, whitespace, minus
   Everything else:  logit = −∞  →  probability 0

   → the model CANNOT emit an invalid token.
     Not "usually doesn't". Cannot.

Implementations compile the schema (JSON Schema, a regex, or a context-free grammar) into a state machine, and at each step compute the set of vocabulary tokens that keep the output on a valid path.

ApproachGuaranteeCost
Prompt "return JSON"NoneFree, fails a few percent of the time
Retry on parse failureEventual, probabilisticExtra full generations
Constrained decodingAbsoluteMask computation per step; can be near-zero with precomputed state machines
Fine-tuning for formatHigh, not absoluteTraining cost

The efficient implementations (Outlines, XGrammar, llama.cpp's GBNF) precompute the allowed-token mask for each state of the machine ahead of time, so the per-step cost is a lookup rather than a schema evaluation.

#Speculative decoding

The most elegant idea in inference optimisation, and it follows directly from inference arithmetic.

Decode is memory-bandwidth-bound: producing one token requires reading all the weights. But that same weight read could process several token positions in one pass at almost no additional cost — the arithmetic is nearly free, the memory read is the expense.

So: have a small, fast model guess the next few tokens, then have the large model verify all of them in a single forward pass.

   1. DRAFT — small model generates k = 4 candidate tokens
                (cheap: it's maybe 1/20th the size)

        "The capital of France is" → "Paris and it"

   2. VERIFY — large model runs ONE forward pass over all
                4 positions in parallel, producing what IT
                would have said at each position

   3. ACCEPT — compare, keep the longest matching prefix

        draft:   Paris   and    it     is
        target:  Paris   and    is     ...
                  ✓       ✓      ✗
        → accept 2 tokens, plus the target's own correction
          at the mismatch = 3 tokens from one large-model pass

   Cost:  one large forward pass + 4 small ones
   Yield: 3 tokens instead of 1

The critical property: rejection sampling makes the output distribution mathematically identical to decoding from the large model alone. This is not an approximation and not a quality tradeoff. Each draft token is accepted with probability min(1, p_target/p_draft): always, if the large model likes that token at least as much as the draft did; only sometimes, if the draft was over-keen on it. On a rejection, the replacement is sampled from the leftover probability — the tokens the large model wanted more than the draft offered them. The maths works out so that every token has exactly the probability the large model alone would give it. You get the same distribution, faster.

Variants that avoid needing a separate draft model:

  • Medusa — extra prediction heads on the target model itself, each guessing a future position.
  • EAGLE — a small draft head predicts the target model's next internal hidden state (its "features") rather than the next token directly; higher acceptance rates.
  • EAGLE-3 (2025) — stops forcing the draft to predict those features exactly, and instead feeds it features combined from several layers of the target model; acceptance rises further, and it's widely supported in serving engines.
  • Multi-token prediction heads — trained alongside the model itself (DeepSeek-V3 does this), so the model ships with its own drafter.
  • Lookahead / n-gram — draft by copying from the prompt. Extremely effective for code editing and summarisation, where much of the output is verbatim from the input.
  • Self-speculative — skip layers to form a cheap draft from the same weights.

#Beam search, and why it fell out of favour

Beam search keeps b candidate sequences in play at once. At each step it extends all of them and keeps the b with the highest combined probability over the whole sequence so far. It remains standard for translation and other tasks with one correct answer.

For open-ended generation it is worse than sampling, and the reason is interesting: the highest-probability sequence is not the best text. Optimising for total likelihood produces short, generic, repetitive output — the model's idea of the safest possible thing to say. Human text is surprising in a measurable way, and sampling reproduces that; maximising likelihood specifically removes it.

Beam search also costs b times the memory and compute, which for an LLM means b times the KV cache. Rarely worth it.

#Check yourself

What does temperature do?Show answer
It divides logits before softmax: below 1 sharpens the distribution, above 1 flattens it, 0 is greedy argmax — which is not "best" and tends to loop.
Why is top-p a better default than top-k?Show answer
Top-p keeps the smallest set reaching cumulative probability p, adapting to confidence (2 tokens when sure, hundreds when uncertain); top-k keeps a fixed count either way.
Why isn't temperature 0 deterministic?Show answer
Batch composition changes floating-point reduction order, MoE routing depends on the batch, and hardware or kernel versions change numerics. Pin versions or use batch-invariant kernels; test on structure, not exact strings.
How does constrained decoding work, and what does it guarantee?Show answer
A schema or grammar compiles to a state machine; at each step tokens that would break validity get −∞ logits. Format is guaranteed (0.98²⁰ ≈ 67% clean agent runs becomes 100%) — content is not.
How does speculative decoding work?Show answer
A cheap drafter proposes k tokens; the large model verifies all in one pass (nearly free, since decode is bandwidth-bound); keep the longest matching prefix plus its correction.
Does speculative decoding change the output?Show answer
No — rejection sampling (accept with probability min(1, p_target/p_draft), else resample from the residual) keeps the distribution identical to the large model alone.
Why disable speculative decoding at high batch?Show answer
It uses idle compute to cut single-request latency. At high batch the GPU isn't idle, so verification competes with real work and can reduce throughput — enable it adaptively.
Why did beam search lose for open-ended text?Show answer
Maximising total likelihood produces short, generic, repetitive text — human writing is measurably surprising — and it costs b× the KV cache.

#What to carry forward

  • Temperature scales logits; top-p adapts to the model's own uncertainty. Top-p is the better default.
  • Temperature 0 is not determinism — batch composition, MoE routing, and kernel versions all leak in.
  • Constrained decoding guarantees format, turning a probabilistic interface into a deterministic one. It does not guarantee content.
  • Speculative decoding is free latency at low batch because decode is bandwidth-bound — and preserves the output distribution exactly.
  • It costs throughput at high batch. Enable it adaptively.
  • Highest-probability text is not best text, which is why beam search lost for open-ended generation.
00:00
/ 12m