Skip to content

Language models, retrieval, prompting, and language adaptation · Reasoning, decoding, and discrete diffusion language · LNG076 · Algorithm

Nucleus / top-p sampling

Samples tokens from the smallest high-probability set whose cumulative mass reaches a threshold, limiting the low-probability tail while allowing the candidate-set size to vary with model uncertainty.

Runs as a notebook Complete calculation CodeSplash's own run

In CodeSplash

No method yet, but the reference's example runs here as a notebook.

Do it in CodeSplash Open the reference's example as a Python or R notebook.

Availability
Runs as a notebook
Code example
Complete calculation
Who ran it
CodeSplash's own run
CodeSplash's run
The reference's example ran here in one language.
The reference's record
Python: The chapter's authors report running it; there is no record for this entry alone. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

Samples tokens from the smallest high-probability set whose cumulative mass reaches a threshold, limiting the low-probability tail while allowing the candidate-set size to vary with model uncertainty.

Question / objective

How can tail truncation balance sampling diversity and coherence?

Architecture / computational structure

A logits-to-probability transformation, descending sort, cumulative threshold, and renormalization define the algorithm. No weights are learned; top-p, temperature, seed, and other logits controls are inference hyperparameters.

Assumptions

The threshold is not a confidence level or guarantee of truth.

Formula / computational definition

k=min⁡{m:∑i=1mp(i)≥p0},p~(i)=p(i)1{i≤k}∑j=1kp(j).k=\min\left\{m:\sum_{i=1}^{m}p_{(i)}\ge p_0\right\},\qquad \widetilde p_{(i)}=\frac{p_{(i)}\mathbf 1\{i\le k\}}{\sum_{j=1}^{k}p_{(j)}}.

Sort p_(1)>=p_(2)>=... and choose minimal k with sum_i<=k p_(i)>=p0. Renormalize probabilities within those k tokens and sample; temperature, if used, changes probabilities before truncation.

Parameters and notation

Learned parameters: identified in the architecture subsection. Hyperparameters, design and inference choices: Probability threshold p0, temperature, minimum-token retention, repetition controls, random seed, and stopping criteria.

Fitting, fine-tuning, and adaptation

No fitting is necessary. Select threshold and temperature on held-out task quality and diversity, then fix them for evaluation. Fine-tuning the generator changes its probability distribution and requires retuning; decoding changes should not be reported as neural parameter learning or calibrated confidence.

How to use and calibrate

Assess diversity, coherence, factuality, repetition, task success, and reproducibility across seeds; compare decoding strategies under equal output budgets. Use development data for settings and an independent test set for the final estimate. Report uncertainty across examples or seeds when the evaluation design supports it; model scores and self-assessments are not automatically calibrated probabilities of correctness.

Example application

Generate varied text while excluding the least probable portion of each token distribution.

Interpretation / pitfalls

Watch out

Low p0 can reduce diversity or trap repetition, while high p0 admits more unlikely errors; interactions with other logits processors matter. The code below isolates one stated component; successful execution does not validate model quality or reproduce the cited experiment.

Python and R code examples

Full implementation route: Transformers generation documents top-p controls; R can bridge that implementation. Native Python and R examples compute the nucleus set and its renormalized distribution directly, providing a complete toy decoding step without a trained language model.

Example scope: Exact nucleus set construction and renormalization for one toy token distribution.

Dependencies: Python 3 standard library; base R; shared setup above. No model downloads or external services.

Validation: Python component executed in the combined example script; R counterpart supplied but not runtime-tested here. All numbers are synthetic.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Complete calculation — Exact nucleus set construction and renormalization for one toy token distribution.

Shared setup for this chapter
import math

def softmax(xs):
    m = max(xs)
    es = [math.exp(x-m) for x in xs]
    return [e/sum(es) for e in es]

def dot(a, b):
    return sum(x*y for x, y in zip(a, b))

def matvec(matrix, vector):
    return [dot(row, vector) for row in matrix]

def meanvec(rows):
    return [sum(row[j] for row in rows)/len(rows) for j in range(len(rows[0]))]

def sigmoid(x):
    return 1/(1+math.exp(-x))

def nll(probabilities):
    return -sum(math.log(p) for p in probabilities)
p,threshold = [0.5,0.25,0.15,0.1],0.8
selected,total = [],0.0
for i in sorted(range(len(p)),key=p.__getitem__,reverse=True):
    selected.append(i); total += p[i]
    if total >= threshold: break
print(selected,[p[i]/total for i in selected])
R

Complete calculation — Exact nucleus set construction and renormalization for one toy token distribution.

Shared setup for this chapter
softmax <- function(x) {
  shifted <- exp(x-max(x))
  shifted/sum(shifted)
}
p <- c(0.5,0.25,0.15,0.1); threshold <- 0.8
idx <- order(p,decreasing=TRUE)
k <- which(cumsum(p[idx])>=threshold)[1]
selected <- idx[seq_len(k)]
print(list(selected=selected,probabilities=p[selected]/sum(p[selected])))

Sources

From the CodeSplash reference, entry LNG076.