AI Foundations for Developers COURSE·LESSON 21 OF 410 completed

Logits, Temperature, and Sampling

Vocabulary scores become a choice

Logits are unnormalized scores for possible next tokens. Softmax converts them to probabilities: p_i = exp(z_i)/Σexp(z_j). For numerical stability, subtract the largest logit before exponentiating; this leaves the resulting probabilities unchanged.

Temperature commonly scales logits as z/T for positive T. Lower temperatures concentrate probability on larger logits; higher temperatures flatten the distribution. The API meaning of zero or unsupported values is implementation specific.

python
import math

def probabilities(logits, temperature):
    if temperature <= 0:
        raise ValueError("This example requires positive temperature")
    scaled = [z / temperature for z in logits]
    values = [math.exp(z - max(scaled)) for z in scaled]
    return [v / sum(values) for v in values]

for t in [0.5, 1.0, 2.0]:
    print(t, [round(p, 3) for p in probabilities([2, 1, 0], t)])
# 0.5 [0.867, 0.117, 0.016]
# 1.0 [0.665, 0.245, 0.09]
# 2.0 [0.506, 0.307, 0.186]

Try this in the Python compiler.

Common selection strategies

Greedy decoding selects the highest-scoring next token. Top-k sampling limits candidates to the k highest scores. Top-p, or nucleus sampling, retains a set whose cumulative probability reaches a chosen threshold and samples from the renormalized set. Exact boundary behavior depends on implementation.

For sorted probabilities [0.6,0.25,0.15], a simplified top-p threshold of 0.8 keeps the first two candidates because their cumulative probability is 0.85. It does not mean the model will be correct 80% of the time.

Reproducibility and correctness

Lower randomness can improve consistency but does not verify facts. Repeated calls can differ due to sampling, parallel computation, backend changes, or model revisions. A seed is useful only within the reproducibility guarantees of the particular system.

Max-output settings, stop sequences, end tokens, and tool-call boundaries also affect generation. Always distinguish a normal end from truncation: truncated JSON might be invalid even when the request itself succeeded.

Checkpoint with answers

Does temperature 0 make answers factual? No. Greedy selection can consistently choose a wrong continuation.

Should all sampling controls be changed at once? Usually not during diagnosis. Change one variable and evaluate the effect on your task.

Exercise: Can top-p improve access to documents the model never receives? Answer: no; it changes token selection, not available evidence.

Learn at your own pace0 / 41 lessons complete