Concept notebookChecking saved investigationReading browser-local route memory before showing a continuation.

Decoding & Sampling: Temperature, Top-p & Inference-Time Control

How inference settings reshape the next-token distribution into actual model behavior: temperature, nucleus sampling, and why decoding is a control knob.

published · difficulty 3/5 · 16 min read

01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

PredictName the object in plain language, then predict what should change.Leave with one reusable mental picture before notation appears.

Training gives you a next-token distribution. Decoding is what turns that distribution into actual behavior.

Two products can ship the "same model" and feel completely different because decoding choices differ:

  • greedy vs sampling,
  • temperature (how sharp the distribution is),
  • top-p/top-k truncation (how much tail you delete),
  • penalties and constraints (repetition, min length, format forcing).

So decoding is not a cosmetic detail. It's an inference-time control surface that trades off determinism, diversity, and failure modes like repetition loops.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

InspectTrack the same object through the notation and check each symbol.Leave with the invariant the equations preserve.

Let ziz_izi be the logits for token iVi \in \mathcal ViV at some step.

Temperature rescales logits

Temperature τ>0\tau > 0τ>0 produces:

pτ(i)=ezi/τjezj/τ.p_\tau(i) = \frac{e^{z_i/\tau}}{\sum_j e^{z_j/\tau}}.pτ(i)=jezj/τezi/τ.
  • Smaller τ\tauτ sharpens (more deterministic).
  • Larger τ\tauτ flattens (more exploratory).

Nucleus (top-p) truncation deletes the tail, then renormalizes

Let SpS_pSp be the smallest set of tokens whose probability mass is at least ppp (after sorting by probability):

Sp=min{S:iSp(i)p},p(i)=p(i)1[iSp]jSpp(j).S_p = \min\left\{S: \sum_{i\in S} p(i) \ge p\right\}, \qquad p'(i) = \frac{p(i)\,\mathbf 1[i\in S_p]}{\sum_{j\in S_p} p(j)}.Sp=min{S:iSp(i)p},p(i)=jSpp(j)p(i)1[iSp].

Then you sample from pp'p, the truncated and renormalized distribution.

This is why top-p changes behavior: it literally changes the distribution you sample from.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

TraceMatch variables to symbols before reading the implementation.Leave with a runnable witness for the math.
import numpy as np

def softmax(z):
    z = z - z.max()
    ez = np.exp(z)
    return ez / ez.sum()

def top_p_filter(p, probs):
    idx = np.argsort(-probs)
    keep = np.zeros_like(probs, dtype=bool)
    cum = 0.0
    for i in idx:
        keep[i] = True
        cum += probs[i]
        if cum >= p:
            break
    q = probs * keep
    return q / q.sum()

rng = np.random.RandomState(0)
logits = np.array([3.0, 2.0, 1.0, 0.2, -0.5])  # 5 tokens

for tau, p in [(1.0, 1.0), (0.7, 0.9), (1.4, 0.9)]:
    probs = softmax(logits / tau)
    probs = top_p_filter(p, probs)
    samples = rng.choice(len(probs), size=20000, p=probs)
    counts = np.bincount(samples, minlength=len(probs)) / len(samples)
    print("tau=", tau, "top_p=", p, "freqs=", np.round(counts, 3))
Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

ManipulateChange one control and predict the visible response before reveal.Leave with the observed invariant or a repaired model.

Live Concept Demo

Explore Decoding & Sampling: Temperature, Top-p & Inference-Time Control

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 3/5undergraduatecode-aligned
Demo inquiry checkpoint

Manipulate one control and predict the visible change.

01Choose lensTrace a quantity
02ObserveDemo state pending
03GroundName the equation, invariant, or control that explains it.
04CarryNext: Speculative Decoding: Lossless Multi-Token Generation

Choose what to inspect in Decoding & Sampling: Temperature, Top-p & Inference-Time Control. This shared fallback is an observation guide, not evidence of learning.

Loading interactive demo...

Use the demo to see how temperature/top-p reshape the distribution step by step, and how small changes alter which toy tokens survive.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

4/4 sections ready

Concept: Decoding & Sampling: Temperature, Top-p & Inference-Time Control

What is the smallest example that makes Decoding & Sampling: Temperature, Top-p & Inference-Time Control click without losing the math?

BeforeMaximum LikelihoodNow4/4 sections readyTryManipulate one control and predict the visible change.NextSpeculative Decoding: Lossless Multi-Token Generation
Object contextLLM Systems
ConceptLearner lens

Decoding & Sampling: Temperature, Top-p & Inference-Time Control

What is the smallest example that makes Decoding & Sampling: Temperature, Top-p & Inference-Time Control click without losing the math?

Mode questionCan I say the mechanism back in one sentence before I reveal anything?

Start with the prediction checkpoint, then compare the reveal to the mental model.

Take this move

Study modes

Keep the object fixed; change the lens.

Route back through the notebook

Carry the same object through intuition, math, code, and demo.

4/4 sections ready
Carry inMaximum Likelihood

Bring the mental model from Maximum Likelihood; this page will reuse it instead of restarting from zero.

Work hereDecoding & Sampling: Temperature, Top-p & Inference-Time Control

How inference settings reshape the next-token distribution into actual model behavior: temperature, nucleus sampling, and why decoding is a control knob.

Carry outSpeculative Decoding: Lossless Multi-Token Generation

The next edge should feel earned: use the demo prediction here before following Speculative Decoding: Lossless Multi-Token Generation.

After The First Pass

Turn the concept into an inspected object.

The lower panels are one second act: keep the object fixed, inspect it visually, check source boundaries, practice transfer, then attach the research question.
ConceptDecoding & Sampling: Temperature, Top-p & Inference-Time ControlLLM Systems

Mechanism Storyboard

See the idea move before the page explains it

How inference settings reshape the next-token distribution into actual model behavior: temperature, nucleus sampling, and why decoding is a control knob.

Demo notes open01 / Intuition
Editorial LLM-systems illustration of logit distributions, top-p filtering, temperature shaping, and sampled token paths.
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Decoding & Sampling: Temperature, Top-p & Inference-Time Control should make visible.

Visual Inquiry

Make the image answer a mathematical question

How inference settings reshape the next-token distribution into actual model behavior: temperature, nucleus sampling, and why decoding is a control knob.

4/4 stages readyDemo notes connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Decoding & Sampling: Temperature, Top-p & Inference-Time Control easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

Object - ConceptDecoding & Sampling: Temperature, Top-p & Inference-Time ControlQuestion

What is the smallest example that makes Decoding & Sampling: Temperature, Top-p & Inference-Time Control click without losing the math?

concept:llm-systems/decoding-sampling
Boundary

sources: holtzman-2019-nucleus

Check

Open the closest source note before trusting the local explanation.

Evidence

1 selected-object source shown first; 1 reference total.

Next move

Audit the claim boundary, then ask from the same selected object.

selected object source · paper · 2019The Curious Case of Neural Text DegenerationHoltzman et al.
Located CF editorial boundary

Primary nucleus sampling source. Sec. 3.1 defines the top-p vocabulary, rescales the truncated distribution, and samples from a dynamically sized nucleus; Sec. 3.3 defines temperature softmax.

Used here as

Holtzman et al. define nucleus sampling as a top-p vocabulary whose cumulative probability exceeds p, then rescale that truncated distribution for sampling; the candidate set changes with...

Caveat

Checks temperature softmax and nucleus top-p truncation/renormalization only; not universal decoding-quality settings, safety behavior, task optimality, top-k guarantees, repetition penal...

Open source

Claim Review

How inference settings reshape the next-token distribution into actual model behavior: temperature, nucleus sampling, and why decoding is a control knob.

Object - ConceptDecoding & Sampling: Temperature, Top-p & Inference-Time ControlQuestion

What is the smallest example that makes Decoding & Sampling: Temperature, Top-p & Inference-Time Control click without losing the math?

concept:llm-systems/decoding-sampling
Boundary

sources: holtzman-2019-nucleus

Check

Treat every claim as provisional until source support and a local witness agree.

Evidence

1 structured claim check on this concept.

Next move

Run the prediction or practice transfer before asking for a grounded review.

1 CF editorial source-scope review recorded

Publisher-side editorial review is not independent replication. Claims without it still need exact source-support review. 1 reference and 3 local witnesses are available for inspection.

Decoding settings reshape the next-token distribution at inference time: temperature rescales probabilities, while nucleus sampling truncates the unreliable tail and renormalizes the remaining dynamic token set.
Used here as

Holtzman et al. define nucleus sampling as a top-p vocabulary whose cumulative probability exceeds p, then rescale that truncated distribution for sampling; the candidate set changes with distribution shape....

Local witness
Equation 1
pτ(i)=ezi/τjezj/τ.p_\tau(i) = \frac{e^{z_i/\tau}}{\sum_j e^{z_j/\tau}}.
Equation 2
Sp=min{S:iSp(i)p},p(i)=p(i)1[iSp]jSpp(j).S_p = \min\left\{S: \sum_{i\in S} p(i) \ge p\right\}, \qquad p'(i) = \frac{p(i)\,\mathbf 1[i\in S_p]}{\sum_{j\in S_p} p(j)}.
Code witness 1import numpy as np def softmax(z): z = z - z.max() ez = np.exp(z) return ez / ez.sum() def to...
Caveat

Checks temperature softmax and nucleus top-p truncation/renormalization only; not universal decoding-quality settings, safety behavior, task optimality, top-k guarantees, repetition penalties, beam-search be...

Review stateCF editorial source-scope reviewClaim metadata: source checkedPublisher-side editorial review only; not independent replication. Check caveats and exact source scope.

Checked Holtzman Sec. 3.1 and 3.3: temperature is softmax re-estimation over logits divided by temperature, while nucleus/top-p selects a smallest cumulative-probability set, rescales the truncated distribution, samples from a dynamically sized nucleus, and targets the unreliable tail. The first two equations, first code witness, and updated demo are toy/local distribution-shaping witnesses only.

Reviewer: codex+oracle; reviewed 2026-05-07

Practice notebook

Use the idea, then test it somewhere new

How inference settings reshape the next-token distribution into actual model behavior: temperature, nucleus sampling, and why decoding is a control knob.

AttemptNo learning claim inferred
Object - ConceptDecoding & Sampling: Temperature, Top-p & Inference-Time ControlQuestion

What is the smallest example that makes Decoding & Sampling: Temperature, Top-p & Inference-Time Control click without losing the math?

concept:llm-systems/decoding-sampling
Boundary

sources: holtzman-2019-nucleus

Check

Use one state from Decoding & Sampling: Temperature, Top-p & Inference-Time Control to explain what changes, why it changes, and which assumption the explanation needs.

Evidence

No learner move yet; no learning state is inferred.

Next move

Write first, use only the help you need, then try a new case without it.

Explain

Use one state from Decoding & Sampling: Temperature, Top-p & Inference-Time Control to explain what changes, why it changes, and which assumption the explanation needs.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Grounded object roomClose
Selected object routeAsk from this object; carry one invariant back.sources: holtzman-2019-nucleus
  1. ObjectConceptDecoding & Sampling: Temperature, Top-p & Inference-Time Control
  2. PredictBefore revealDecoding & Sampling: Temperature, Top-p & Inference-Time Control pred...
  3. WitnessCompare codeDecoding & Sampling: Temperature, Top-p & Inference-Time Control code...
  4. RoomAsk groundedChecking local snapshot
ConceptDecoding & Sampling: Temperature, Top-p & Inference-Time ControlLLM Systems
Code witness comparisonDecoding & Sampling: Temperature, Top-p & Inference-Time Control code witness 1z = z - z.max()Prediction before revealDecoding & Sampling: Temperature, Top-p & Inference-Time Control predictionManipulate one control and predict the visible change.
Grounded room questionWhat is the smallest example that makes Decoding & Sampling: Temperature, Top-p & Inference-Time Control click without losing the math?Checking local snapshot

Research Room

Attach the question to an exact object

Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptLLM Systems

Decoding & Sampling: Temperature, Top-p & Inference-Time Control

Anchored question

What is the smallest example that makes Decoding & Sampling: Temperature, Top-p & Inference-Time Control click without losing the math?

Source boundaryInspect source ids: holtzman-2019-nucleusStable content-object key attached
Role lenses for this object

These are fixed, deterministic perspectives derived from the selected object. They do not represent people, community contributions, or independent review.

Learner evidence requestAsk what would make "Decoding & Sampling: Temperature, Top-p & Inference-Time Control" feel predictable rather than familiar.
Assumption

Source ids holtzman-2019-nucleus must support the exact object, not just the surrounding topic.

Source-checking summary

Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion.

Proposed experiment

Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo.

Next action

The learner can state the mechanism in their own words

Evidence4 checks
PredictionChecking carried observation
ActionReady for one action
AILearner handoff ready
Open source object
01PredictionChecking browser-local route memory
02EvidenceChecking for a carried observation
03BoundaryInspect source ids: holtzman-2019-nucleus
04Next moveSave one next action
Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays locally in this browser for concept:llm-systems/decoding-sampling.

No local draft saved.
Evidence to inspect
  • Source ids to inspect: holtzman-2019-nucleus
  • Definition, prerequisite, and contrast concept links
  • The equation or code witness that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Object-attached AI handoff

I am working in Continuous Function's research reading room. Object: concept - Decoding & Sampling: Temperature, Top-p & Inference-Time Control Object key: concept:llm-systems/decoding-sampling Context: LLM Systems Anchor id: concept/concept-notebook/llm-systems/decoding-sampling Open question: What is the smallest example that makes Decoding & Sampling: Temperature, Top-p & Inference-Time Control click without losing the math? Evidence to inspect: - Source ids to inspect: holtzman-2019-nucleus - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan Deterministic role lenses for this object: - Boundary: fixed perspectives, not people, community contributions, or independent review - Source-checking summary: Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Teach/transfer move: Turn the mechanism into one sentence that predicts a neighboring concept. - Assumptions: - Source ids holtzman-2019-nucleus must support the exact object, not just the surrounding topic. - The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. - The concept explanation is local atlas prose until checked against its math, code, and source support. - Prerequisite gaps should become a repair route, not a reason to leave the object vague. - Role-lens requests: - Learner: ask for "Ask what would make "Decoding & Sampling: Temperature, Top-p & Inference-Time Control" feel predictable rather than familiar." | assumption: Source ids holtzman-2019-nucleus must support the exact object, not just the surrounding topic. | next action: The learner can state the mechanism in their own words - Researcher: ask for "Source ids to inspect: holtzman-2019-nucleus" | assumption: The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. | next action: The learner can name the prerequisite that would repair confusion - Experimenter: ask for "Choose one variable or condition to perturb before asking for an explanation." | assumption: The concept explanation is local atlas prose until checked against its math, code, and source support. | next action: The learner can predict how the mechanism changes under one perturbation - Professor: ask for "Find the smallest transferable rule a learner could reuse without the AI." | assumption: Prerequisite gaps should become a repair route, not a reason to leave the object vague. | next action: Teach or transfer: Turn the mechanism into one sentence that predicts a neighboring concept. What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action. Current deterministic role lens for this object: - Role lens: Learner - Evidence request: Ask what would make "Decoding & Sampling: Temperature, Top-p & Inference-Time Control" feel predictable rather than familiar. - Assumption to keep visible: Source ids holtzman-2019-nucleus must support the exact object, not just the surrounding topic. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Next action: The learner can state the mechanism in their own words

concept/concept-notebook/llm-systems/decoding-sampling concept:llm-systems/decoding-sampling