Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

Temperature, Top-P and Top-K: how do AI generation parameters work?

Why can a language model answer the same question differently? Temperature, top-p and top-k control how the next token is selected without changing knowledge encoded in model weights. This guide explains their mathematics, differences between services and a measurement-based approach to configuration.

AI
Published Written by Reading time 7 min read
On this page Contents: quick navigation between sections

From logits to the next token

An autoregressive language model produces a vector of scores, called logits, conditioned on the current context. Softmax transforms them into a probability distribution over the vocabulary. A token may be a word fragment, character or other tokenizer unit. Each selected token changes the context for the next step, so a small early difference can lead to a very different answer. [1][2]

Greedy decoding selects the highest-scoring token at each step. Sampling draws from a distribution after the relevant transformations. The locally most probable token need not lead to the globally most probable sequence. The examples use five hypothetical tokens A–E, not measurements from a real model.

Temperature: reshaping the distribution

Hypothetical probability distribution after temperature scaling
Token T = 0.5 T = 1 T = 2
A 53.91% 40.00% 30.83%
B 30.32% 30.00% 26.70%
C 13.48% 20.00% 21.80%
D 2.16% 8.00% 13.79%
E 0.13% 2.00% 6.89%

Percentages are rounded.

For positive temperature T, divide each logit zᵢ by T and apply softmax: pᵢ(T) = exp(zᵢ/T) / Σⱼ exp(zⱼ/T). For numerical stability subtract the largest scaled logit before exponentiation. Given original probabilities pᵢ, equivalently normalize pᵢ^(1/T). T = 1 leaves the distribution unchanged; 0 < T < 1 sharpens it; T > 1 flattens it. [2]

Positive temperature preserves the ordering of distinct logits but changes their relative probabilities. As T → 0, probability concentrates on the maxima (ties need not produce a single winner); do not substitute zero into the formula. An engine may interpret temperature = 0 as greedy decoding or reject it. Transformers requires positive temperature for sampling; for greedy decoding use do_sample=false without special decoding configurations. [1][2][8]

Top-K: a fixed candidate count

Top-k keeps the K highest-scoring tokens, removes the rest from the distribution and renormalizes the retained mass to 1. With K = 2 in our example, A and B remain: 0.40/0.70 ≈ 57.14% and 0.30/0.70 ≈ 42.86%. It does not choose two subsequent words or constrain response length. [1][2]

K = 1 without ties is equivalent to greedy selection at that step. Implementations may retain extra tied candidates or apply a tie-breaking rule. Disabling the filter is engine-specific; do not assume 0 or -1 means the same everywhere. A very small K may exclude a required identifier, symbol or rare term.

Top-P: a dynamic candidate set

Distribution after filtering and renormalization
Token T = 1 Top-K = 2 Top-P = 0.75
A 40.00% 57.14% 44.44%
B 30.00% 42.86% 33.33%
C 20.00% 0.00% 22.22%
D 8.00% 0.00% 0.00%
E 2.00% 0.00% 0.00%

Percentages are rounded.

Top-p, or nucleus sampling, sorts tokens in descending probability and selects the smallest prefix whose cumulative mass reaches at least P. At P = 0.75, A and B sum to 0.70, so C must be retained too; total mass is 0.90. After normalization A, B and C have probabilities 44.44%, 33.33% and 22.22%. The token crossing the threshold is retained. [1][3]

At P = 1 a typical implementation does not restrict the distribution. For (0.90; 0.05; 0.03; 0.01; 0.01), the same P = 0.75 retains only A. Candidate count therefore varies. Nucleus sampling was introduced in research on neural text degeneration; that work does not establish a universally optimal threshold for every task. [3]

Combining parameters and other controls

Illustrative decoding pipeline
  1. Logits
  2. Temperature
  3. Top-K
  4. Top-P
  5. Token sampling
  6. Context update

An illustrative pipeline is logits → temperature → top-k → top-p → normalization and sampling → context update. This is one possible ordering, not a universal API standard. With T = 0.5 in our distribution the first two tokens have about 84.23% cumulative mass, so top-p = 0.75 retains two instead of three. If top-k = 2 is applied first and renormalized, subsequent top-p = 0.75 retains both. [2]

Distinguish length limits, stop sequences, repetition penalties and schema-constrained decoding from these parameters. Top-p is not answer confidence, top-k is not the RAG retrieval count, and temperature is not reasoning effort. Syntax constraints may independently exclude tokens. Managed services may not disclose filter ordering or implementation details.

Ordering can change the outcome: with P = 0.55, top-p alone retains A and B because A has only 40%. After top-k = 2, A has 57.14% of the mass, so subsequent top-p = 0.55 can retain A alone. This illustrates ideal filters with renormalization between stages, not guaranteed behavior of every engine.

Parameter support across APIs

Parameter support across environments
Environment Support and limitations
OpenAI Responses Model and mode dependent; no general top_k
Anthropic Messages Removed from API 2026-10-21
Google Cloud / Gemini Custom values ignored from Gemini 3.6 Flash
Transformers / vLLM All three, with implementation-specific rules and defaults

Do not transfer configurations between providers unchanged. OpenAI Responses documents temperature (0–2) and top_p (0–1) for supporting models, but has no general top_k parameter; check reasoning.effort compatibility and omit prohibited fields when reasoning is active. Anthropic removed all three parameters in API version 2026-10-21; earlier versions reject non-default values on newer models. [4][5][6]

Google Cloud documents that Gemini 3.6 Flash and later models ignore custom temperature, topP and topK values. Older models vary by model and service. Transformers and vLLM expose all three mechanisms but have their own defaults and disabling rules. Maintain a capability registry keyed by model, API version and mode; reject unsupported settings rather than silently pretending they worked. [1][7][8]

Selecting settings by task

Begin with the vendor configuration. For classification and extraction, compare it with greedy decoding or lower temperature where supported. Enforce an output schema, validate values and measure errors. In retrieval-augmented generation (RAG), test grounding, accurate citations and abstention when evidence is missing. For creative tasks compare increased diversity with adherence to constraints and usefulness. There is no universal table of best values.

For code generation evaluate compilation and tests, not prose fluency. An agent proposing an order change must pass independent authorization, validation and side-effect checks regardless of temperature. If sampling parameters are unsupported, optimize instructions, context, schema and model choice. Low temperature cannot correct false source data or prevent prompt injection.

For instruction and context design, see the related POLPROG guide to prompt engineering and context engineering. [11]

Reproducibility, evaluation and cost

Hypothetical cost per accepted result
Configuration Tasks Accepted results Cost (USD) Cost per result (USD)
A 1000 900 20 0.0222
B 1000 960 24 0.0250

Fix model and version, instructions, data, schema, limits and execution mode. Vary one parameter while holding others fixed, then test selected combinations on held-out cases. Repeat trials and report task count, acceptance rate, variability, p95 latency and cost across all attempts. A seed can improve reproducibility in a given environment, but hardware, implementation, concurrency or version changes can alter results. [9][10]

Hypothetically configuration A costs USD 20 for 1,000 tasks and 900 accepted results; B costs USD 24 for 960 accepted results. Cost per accepted result is USD 0.0222 and USD 0.0250 respectively. The additional 60 results cost USD 4, or approximately USD 0.0667 each. Also evaluate consequences of errors; this is not a temperature benchmark. Cost depends on actual token usage, retries, tools and billing, not directly on T, P or K.

Deployment and diagnosis

Before deployment verify support and ranges, defaults, termination behavior and output validation. Record the model version and effective configuration when exposed, without logging sensitive content by default. Test unsupported values, omitted parameters, extremes and API version changes; on incompatibility return a clear error or use an explicitly approved fallback configuration.

Separate causes of failures: missing knowledge requires evidence, invalid format requires schema and validation, bad decisions require model evaluation, and unauthorized effects require application controls. Sampling changes help only when the problem actually involves token selection. Maintain regression tests and a configuration rollback procedure after model changes.

Start with the model's recommended settings. Change one supported parameter at a time, measure outcomes, then evaluate interactions. If answers are false, evidence is missing or operations are unauthorized, changing sampling is not a remedy. Improve knowledge sources, instructions, validation and execution controls.

Tools for this topic

LLM AI Temperature Top-P Top-K Token Sampling Nucleus Sampling Greedy Decoding AI Evals AI Costs Context Window Prompt Engineering

Frequently asked questions

Does temperature = 0 guarantee identical output?

No. Greedy selection does not guarantee reproducibility of the entire service, especially after model or environment changes.

Does top-p = 0.9 mean 90% confidence?

No. It is a cumulative candidate probability threshold at a step, not the probability that an answer is correct.

Does top-k = 10 mean ten words?

No. It limits next-token candidates; a token need not be a word.

Should all parameters be changed together?

Not initially. Change one supported parameter and test combinations after establishing a baseline.

Does lower temperature eliminate hallucinations?

No. Reliable sources, claim validation and appropriate abstention are needed.

Does every model support these settings?

No. Check the model, API version, reasoning mode and provider documentation.

Sources and references

  1. Hugging Face Transformers, Generation↩1↩2↩3↩4↩5
  2. Hugging Face Transformers, Utilities for generation↩1↩2↩3↩4↩5
  3. Holtzman et al., The Curious Case of Neural Text Degeneration↩1↩2
  4. OpenAI, Responses API reference↩
  5. OpenAI, API deployment checklist↩
  6. Anthropic, Using the Messages API↩
  7. Google Cloud, Content generation parameters↩
  8. vLLM, SamplingParams↩1↩2
  9. vLLM, Reproducibility↩
  10. OpenAI, Evaluation best practices↩
  11. POLPROG, Prompt Engineering vs Context Engineering↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning