Sampling and factual limits
A distribution is not an answer
At each generation step a decoder produces scores called logits for vocabulary tokens. Softmax converts those scores into a probability distribution. In a fictional stock report, “available” might have probability 0.5, “delayed” 0.3 and “unknown” 0.2. These are probabilities of next-token choices in the toy distribution, not verified probabilities of the actual stock state. The earlier attention lesson explains how context affects logits. Greedy decoding takes a highest-scoring token; sampling draws from a distribution. Beam search retains several candidate sequences and compares sequence scores, which need not select a factually correct answer.
Temperature changes the distribution
For finite logits z and temperature T > 0, compute softmax(z/T). Lower positive T increases the relative preference for larger logits; higher T flattens the distribution. Equal logits remain equal. Subtract the largest logit before exponentiation to avoid overflow for ordinary finite inputs. T = 0 is not valid in this mathematical formula. Some APIs interpret a zero setting as a greedy-like mode, others reject it or use different controls. Even a greedy request is not a cross-run reproducibility guarantee: model updates, numerical ties, implementation and other settings matter.
from math import exp, isfinite
def probabilities(logits, temperature): if not logits or not isfinite(temperature) or temperature <= 0: raise ValueError("need logits and positive finite temperature") if not all(isfinite(x) for x in logits): raise ValueError("logits must be finite") largest = max(logits) weights = [exp((x - largest) / temperature) for x in logits] total = sum(weights) return [w / total for w in weights]
for t in [0.5, 1, 2]: print([round(p, 3) for p in probabilities([2, 1, 0], t)])Expected rounded outputs: [0.867, 0.117, 0.016], [0.665, 0.245, 0.09], and [0.506, 0.307, 0.186]. Rounded entries may not sum to exactly one. The example uses small finite logits and standard-library math; no model is called. Extremely small temperatures and extreme floating-point inputs can underflow to zero, which this illustration does not treat as calibrated certainty.
Top-p and the eligible token set
Nucleus sampling, or top-p, sorts tokens by probability, retains the shortest prefix whose accumulated mass reaches p, then renormalizes and samples among those tokens. Top-k instead retains a fixed number of highest-scoring candidates. With probabilities [0.50, 0.30, 0.20], p = 0.80 retains two tokens with conditional probabilities 0.625 and 0.375; p = 0.81 retains all three. Temperature may be applied before filtering, but order, tie policy, minimum retained tokens and supported combinations are implementation-specific. Verify actual generation configuration. Here we use exact integer weights and integer percentages, breaking ties by original index. Zero-weight trailing tokens need not be kept.
def nucleus(weights, percent): if (not weights or any(type(w) is not int or w < 0 for w in weights) or sum(weights) == 0 or type(percent) is not int or not 1 <= percent <= 100): raise ValueError("need positive total and percent from 1 to 100") order = sorted(range(len(weights)), key=lambda i: (-weights[i], i)) total = sum(weights) mass = 0 kept = [] for i in order: kept.append(i) mass += weights[i] if 100 * mass >= percent * total: break return kept
print(nucleus([50, 30, 20], 80))print(nucleus([50, 30, 20], 81))print(nucleus([1, 1, 0], 50))Expected lines: [0, 1], [0, 1, 2], [0]. This function selects eligible indices; it does not draw a sample. To sample exactly in the first case, a uniform integer from 0 to 79 would map 0–49 to token 0 and 50–79 to token 1. In a real model the distribution is recomputed for the new prefix at every step.
Fluency, instruction following and factual support
A model can follow the requested style yet invent an inventory number, or supply valid JSON that contains a false claim. A hallucination or confabulation is plausible-looking but unsupported or erroneous output. Low temperature can repeatedly produce the same wrong claim. High token probability is not the same as calibrated factual confidence. Reasoning behavior can improve some tasks but a model-provided explanation is not proof of its internal computation or factual accuracy. Evaluate externally checkable answers, evidence and actions; do not require hidden reasoning as an artifact.
Audit a recorded mock response
Synthetic record R1 says: item A has 12 units; item B has no recorded quantity. Mock answer: “A has 12 units and B has 8 units.” The first assertion is supported by R1, the second is unsupported, not necessarily false. A grounded answer would state A has 12 units and B is unknown from the available record. If the record instead explicitly says B has 0 units, the claim of 8 is contradicted. Track support, contradiction and missing evidence separately; validate citations against actual passages rather than trusting a citation-shaped string. For high-consequence tasks require review or abstention. Do not equate retrieval with truth: sources can be stale or wrong.
Practice and next steps
For weights [40, 35, 25], determine the nucleus at 75% and 76%. Then write a response to a fictional product query when no approved warranty is recorded; state the missing evidence rather than inventing a warranty. Record decoding configuration, model revision, context and expected outcome when conducting future experiments. Next: prompt engineering and task contracts.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Sampling and factual limits quiz
Apply the chapter concepts to synthetic model requests and recorded responses.
For fixed unequal finite logits, what happens when positive temperature is reduced?
For weights [50, 30, 20], what is the toy nucleus at 80%?
How do top-k and top-p filtering differ before sampling?
A record does not list the quantity of item B. A model says it has eight units. How should the claim be classified?
Which claim about greedy decoding is defensible?