LLM Systems

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.

status: publishedimportance: importantdifficulty 3/5math: undergraduateread: 16mlive demo
Editorial LLM-systems illustration of logit distributions, top-p filtering, temperature shaping, and sampled token paths.

Concept Structure

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

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

2prerequisites
1next concepts
1related links

Learner Contract

What this page should let you do.

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

This LLM Systems concept is the current object: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.

By the end4/4 sections ready | code witness expected | live demo

Explain the mechanism, trace the main notation, and test one prediction in the live demo.

Do this firstIntuition

Read the intuition before the notation; the math should name a mechanism you already felt.

Test the linkManipulate one control and predict the visible change.Then continue to Speculative Decoding: Lossless Multi-Token Generation

Claim/source review status

Substantive review recorded

1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.
Claims1/1 reviewed
Sources1 cited
Codeattached
Demolive
Reviewed2026-05-07
Updatedpage 2026-05-07

First Route Readiness

First route: attention to serving

A new learner should see one concrete path: map or search a claim, inspect the route graph, open Efficient Attention, predict the KV-cache lever, review the claim boundary, and leave a reproduction or repair note attached to the exact object.

QuestionHow does attention become a serving bottleneck?
Next repairEfficient Attention
Lab stateKV prediction lab live
Efficient Attention conceptRead the concept as the route repair, then inspect claim checks.

Use the demo prediction checkpoint and claim review before moving on.

Scope labels requiredPreview/local where applicable; claim review before comparison; reproduction notes stay object-attached.

No benchmark result, hosted compute, automatic expert review, or live runtime-performance claim is made by this v0.

Object flow

4/4 sections readyAsk about thisResearch room
ConceptDecoding & Sampling: Temperature, Top-p & Inference-Time ControlLLM Systems
1 source attachedLocal snapshot ready
concept:llm-systems/decoding-sampling
01

01

Intuition

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

Section prompt

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.

02

02

Math

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

Section prompt

Let ziz_i be the logits for token iVi \in \mathcal V at some step.

Temperature rescales logits

Temperature τ>0\tau > 0 produces:

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

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

Let SpS_p be the smallest set of tokens whose probability mass is at least pp (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)}.

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

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

03

03

Code

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

Section prompt
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))
04

04

Interactive Demo

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

Section prompt

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

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 Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Decoding & Sampling: Temperature, Top-p & Inference-Time Control should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

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.

Prediction 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 readyLive demo 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.

paper · 2019The Curious Case of Neural Text DegenerationHoltzman et al.

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.

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.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources1 reference

holtzman-2019-nucleus

Witnesses4 local objects

Use equation, code, and demo objects to check whether the source support is operational.

Substantively reviewedDecoding 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.Claim metadata: source checked

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. Sec. 3.3 defines temperature softmax over logits. Local math/code/demo are toy distribution-shaping witnesses.

Sources: The Curious Case of Neural Text DegenerationChecks 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 behavior, or production sampler implementations. Demo is toy/local only.A bounded review summary is present; still 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 Loop

Try the idea before it explains itself

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

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Decoding & Sampling: Temperature, Top-p & Inference-Time Control.

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.

Object research drawerClose
ConceptDecoding & Sampling: Temperature, Top-p & Inference-Time ControlLLM Systems

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?

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
Grounded 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 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.

Open source object
concept/concept-notebook/llm-systems/decoding-sampling concept:llm-systems/decoding-sampling