Skip to content

Sampling: temperature, top-p, top-k and repetition penalties through a worked distribution

10 min reading

Calculate temperature, top-k and top-p changes and distinguish repetition control from task validation.

Page details

GenAI · Lesson 8 of 45 · 1 / 1.3

Sources · 10 min reading · 23 min with practice

Published · Last edited:

More
20px

Progress is saved in this browser when storage is available.

View guided paths and progress

Know first: Prompting: few-shot, chain-of-thought and least-to-most; distinguish proposal from verification. Optional help: GenAI foundations.

Hypothetical scenario. Northwind has stabilized its prompt contract. Maya notices that repeated policy summaries still use different wording, while Dev wants varied alternatives for a heading. Priya asks them to distinguish a choice about variation from a check on the policy itself.

Maya: “Could a lower temperature make the policy answer trustworthy?”

Dev: “It changes which next tokens are likely to be selected.”

Priya: “Then calculate that change, and keep the evidence check separate.”

You will calculate temperature, top-k and top-p on a supplied distribution, then distinguish those selection rules from repetition penalties and application acceptance. The preceding lessons supplied token units and a task; this lesson follows the next-token choice.

Why can a stable prompt produce different continuations?

A generative model supplies scores for candidate next tokens. Decoding transforms those scores and chooses a token, then repeats with the enlarged prefix. Greedy decoding selects a highest-scoring eligible token. Sampling draws according to a distribution. Neither procedure checks Northwind's policy documents or decides whether an employee may see them.

Hugging Face's generation-strategy guide distinguishes greedy selection from sampling. These choices can produce different continuations from the same model. They are operating choices for an already learned distribution, not a replacement for task-specific evaluation or an update to the model's weights.

Work one small distribution before changing a setting

Choose four symbolic candidates A, B, C and D with probabilities 0.50, 0.30, 0.15 and 0.05. These are invented teaching values, not output from a named model. They sum to 0.50 + 0.30 + 0.15 + 0.05 = 1. Greedy selection chooses A, while an unrestricted sample can select any of the four. A token's probability is not the probability that the whole answer is correct.

One distribution, different candidate setsThe invented four-token distribution has masses 0.50, 0.30, 0.15 and 0.05. Top-k with k two keeps A and B; a top-p threshold of 0.90 needs A, B and C.ABCD0.500.300.150.05Top-k = 2 keeps A, B; top-p = 0.90 keeps A, B, C.
Bar lengths are proportional to the declared probabilities: 800 drawing units per unit probability.

Record sampling as part of the evaluated configuration

Hypothetical scenario. A candidate changes temperature and top-p together. Its output differences cannot be attributed to one setting without a controlled comparison. Store model revision, generation settings and stop conditions with each evaluation run.

Record sampling as part of the evaluated configuration
ArtifactConcrete evidenceDecision boundary
Generation configtemperature, top-p, top-k, stop rulesVersioned intervention
Run evidencemodel, request, environment, outputReconstruct comparison
Outcomeaccepted, unsupported, failedTask-level evaluation
Declared transform order: Model distribution → Configured filtering.Declared transform order: Model distribution → Configured filtering. Model distribution to Configured filtering: declared transform order; Configured filtering to Sample + task check: draw is not verification.Model distributionConfigured filteringSample + task checkdeclared transform orderdraw is not verification
Declared transform order: Model distribution → Configured filtering. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

Top-k limits candidate count; top-p selects probability mass under the implementation order; temperature rescales relative preference before sampling. These mechanisms do not validate the selected token. A deterministic-looking setting also does not guarantee identical whole-service behavior across changed kernels, providers or model revisions. Separate repeatability of the selected environment from correctness on the task. Evaluate variability with repeated cases when stochastic behavior affects acceptance, retaining refusals and failed generations in the denominator.

Temperature changes relative mass before the draw

For positive temperature T, divide logits by T before applying softmax. If a normalized distribution has strictly positive probabilities p, the same transformation can be written as raising each p to the power 1/T and renormalizing. This equivalent expression lets us calculate without inventing model logits.

Take T = 0.5. The unnormalized masses become 0.50² = 0.25, 0.30² = 0.09, 0.15² = 0.0225 and 0.05² = 0.0025. Their sum is 0.365. Dividing each by that sum gives approximately 0.68493, 0.24658, 0.06164 and 0.00685. Their rounded sum is 1.00000. A becomes more dominant; the procedure still does not establish that A is the appropriate policy response.

T = 1 leaves this distribution unchanged. A larger positive temperature flattens relative differences; a smaller positive temperature sharpens them. Do not literally divide by zero to explain a “temperature zero” API option. An implementation may interpret that setting as a selection mode, and its documented behavior must be checked. Nor should a team infer reproducibility across model versions or serving implementations merely from a small temperature.

Top-k fixes the number of eligible candidates

Now return to the original four probabilities and choose k = 2. Keep A and B and remove C and D. The retained mass is 0.50 + 0.30 = 0.80. Renormalization gives P(A) = 0.50/0.80 = 0.625 and P(B) = 0.30/0.80 = 0.375. A random sample over this set can still choose B.

The chosen k counts candidates rather than retained probability. In a different, much flatter distribution, two candidates might retain very little mass. In a sharply peaked distribution, the second candidate might be implausible for the task. A fixed candidate count does not adapt to either situation by itself. Treat k as a policy to evaluate, not as a statement about how many answers are reasonable.

Top-p fixes a cumulative-mass target

With nucleus sampling, sort candidates by descending probability and keep a sufficiently large leading set to reach the chosen mass threshold, under the implementation's boundary convention. At top-p = 0.90 in our example, A and B provide 0.80, which is insufficient. Adding C reaches 0.95, so the retained set contains three candidates.

After removing D, the new probabilities are 0.50/0.95 = 10/19, 0.30/0.95 = 6/19 and 0.15/0.95 = 3/19. The fractions sum to 19/19 = 1. This differs from top-k = 2 even though both procedures remove some low-probability choices. The nucleus-sampling paper by Holtzman and colleagues motivates adapting the candidate set to the distribution rather than always retaining a fixed number.

These calculations apply each method independently to the declared original distribution. They do not specify the order when several transformations are enabled together. Temperature, penalties and filters can interact. Record the actual generation configuration, inspect the selected implementation's ordering and compare complete-task outcomes before attributing a change to one control.

Repetition penalties change a different condition

A repetition penalty modifies scores based on tokens already present in the sequence. Its exact transformation and the scope of the remembered tokens are implementation details; it is not equivalent to reducing temperature or deleting duplicate sentences. The GenerationConfig reference separates repetition penalties from temperature and candidate filtering.

For Northwind, repeating a case identifier or a safety qualification may be required. Penalizing repeated pieces can interfere with that requirement. Start with an explicit output contract and inspect failures involving names, numbers and quoted evidence. Use an independent check for required fields and prohibited actions. Sampling controls should not become an attempt to probabilistically enforce authorization.

A repeatable mistake is still a mistake

Hypothetical failure scenario. Northwind switches to greedy decoding and sees fewer stylistic differences. The team then stops checking whether answers cite the current policy. An outdated passage now produces the same unsupported answer repeatedly. The sampling change affected variation; it did not repair source selection or freshness.

In the wild, Holtzman and colleagues investigate degeneration in open-ended generation and propose nucleus sampling. Their result motivates examining decoding rather than assuming that the single most probable continuation is always the best text. It does not supply a universal setting for a restricted enterprise workflow. Northwind's acceptance tests must still represent its own tasks.

Use greater sampling variation when the task benefits from genuinely different proposals and a later stage can evaluate them. Prefer simpler selection when variation adds no value, but keep task checks in either case. If comparing settings, hold the model, prompt and evaluation set constant, record several runs when randomness matters, and classify failures rather than reporting only a preferred example.

Test the generation config boundary

The same seed yields a different reply after a provider migration. Is the new reply necessarily incorrect?

Reveal the design reasoning

No. Reproducibility and correctness are different questions. Evaluate the new outcome under the same task contract and investigate configuration and environment changes separately.

Decision: Keep generation settings in release evidence and measure task variability explicitly.

Check the calculation before the recommendation

  1. With the original distribution, does top-p = 0.90 keep only A and B because they are the two most likely candidates?

    Use cumulative mass

    No. Their mass is 0.80. C must also be retained to reach the threshold; the retained mass is 0.95. A mass threshold and a candidate-count threshold answer different questions.

  2. At T = 0.5, is the new probability of A simply 0.50² = 0.25?

    Complete the normalization

    No. The squared values are unnormalized. Divide 0.25 by their sum, 0.365, giving approximately 0.68493. Forgetting this step produces masses that do not sum to one.

  3. Greedy decoding always returns the same wrong policy in a chosen test. Should a team declare the problem solved because the output is consistent?

    Keep the acceptance condition

    No. Consistency is not support or freshness. Inspect retrieval and the task contract. A sampling adjustment cannot establish which policy is authoritative.

Go deeper into distributions and decoding

Record the selection policy

Decision: select decoding settings against a stated task and record their complete configuration.
Reason: variation, probability and correctness are different properties.
Reconsider when: the model, request type or acceptance evidence changes.

Choosing a continuation does not define the object Northwind’s application can accept. Page 09 follows a generated proposal through grammar restrictions, parsing, schema validation and the remaining business checks.