Lesson 8.5core2 h⚡ live demo

Decoding and sampling

From a probability distribution to the next token — every knob explained

A language model outputs a distribution over the vocabulary; decoding decides what to do with it. The same model can be repetitive or creative, deterministic or diverse, valid JSON or a mess, purely because of temperature, top-p and constraints. These settings are the last thing between the model and the user, they interact with prompting (8.4 Prompting as programming) and inference cost (7.10 Efficient inference: KV cache, GQA, FlashAttention, speculative decoding, quantization), and constrained decoding is what makes structured outputs and tool calls reliable (9.6 Generation side: context assembly, citations, structured outputs and tool calling, 10.2 Tool use and function calling).

You'll be able to

  • Write the softmax-with-temperature formula and compute how temperature reshapes a distribution
  • Explain greedy, beam, top-k, top-p and min-p sampling and when each is appropriate
  • Describe repetition penalties, stop sequences, logit bias and grammar-constrained decoding
  • Choose decoding settings for code, chat, extraction and creative tasks
  • Explain why 'temperature 0' is not perfectly deterministic in practice

Key ideas

  1. Decoding chooses a token from softmax(z/T); temperature rescales sharpness without changing the ranking.
  2. Greedy and beam search favor probable sequences and loop or go bland in open-ended text; beam suits translation-like tasks.
  3. Top-k keeps k tokens; top-p keeps the smallest set with cumulative probability ≥ p and adapts to confidence; min-p scales with the top probability.
Show 4 more key ideas
  1. Repetition/frequency/presence penalties, no-repeat n-grams, stop sequences and logit bias give fine control — strong penalties break code.
  2. Grammar-constrained decoding masks invalid tokens each step, guaranteeing schema-valid JSON — the basis of structured outputs and tool calling.
  3. Temperature 0 is only approximately deterministic on batched GPU hardware; reasoning models prefer default sampling plus a thinking budget.
  4. Speculative decoding speeds generation without changing the output distribution.

Suggested path through this lesson