LearnCoding

Temperature, top-k and top-p (nucleus) sampling distribution

MediumLLM, Decoding, Sampling

Problem

Return the distribution you would sample the next token from: 1. p = softmax(logits / temperature). 2. Rank tokens by p descending, with ties broken by lower index. 3. If top_k is set, keep only the first top_k tokens. 4. If top_p is set, renormalise over the kept tokens, then keep the shortest ranked prefix whose cumulative probability ≥ top_p. 5. Return a full-length list: zeros for dropped tokens, renormalised to sum to 1.

Signature

def sampling_distribution(logits: list[float], temperature: float = 1.0, top_k: int | None = None, top_p: float | None = None) -> list[float]: ...

Examples

The visible tests, as an interactive Python session would show them: each call and the value it should give.

>>> close(sampling_distribution([0.0, 0.0, 0.0, 0.0]), [0.25, 0.25, 0.25, 0.25])
True

>>> close(sampling_distribution([2.0, 1.0, 0.0], top_k=1), [1.0, 0.0, 0.0])
True

Solve it in your own editor; nothing on this page runs code.

Hints

Compute the softmax over the logits first.

Temperature scaling: p_i proportional to exp(z_i / T); top-k keeps the k largest probabilities (ties -> lower index), top-p walks the descending cumsum.

Renormalise after zeroing; check the reference for exact tie-breaking.

Reference solution

import numpy as np

def sampling_distribution(logits, temperature=1.0, top_k=None, top_p=None):
    z = np.asarray(logits, float) / temperature
    z = z - z.max()
    p = np.exp(z); p = p / p.sum()
    order = sorted(range(len(p)), key=lambda i: (-p[i], i))
    keep = set(order)
    if top_k is not None:
        keep = set(order[:top_k])
        order = order[:top_k]
    if top_p is not None:
        q = np.array([p[i] for i in order]); q = q / q.sum()
        c = 0.0; kept = []
        for i, qi in zip(order, q):
            kept.append(i); c += qi
            if c >= top_p - 1e-12:
                break
        keep = set(kept)
    out = np.array([p[i] if i in keep else 0.0 for i in range(len(p))])
    return (out / out.sum()).tolist()

What a strong solution covers

  • Stable softmax.
  • Correct order of operations (top-k, then nucleus on the renormalised set).
  • Inclusive cumulative threshold.
  • Deterministic tie order.
  • Discusses temperature → 0 (greedy) and why top-p adapts to entropy.

Common mistakes

  • applying top-p on the original rather than the top-k-renormalised probabilities
  • excluding the token that crosses the threshold.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.