Forward Deployed EngineeringAI EngineeringLLM Inference

Explain temperature and top-p. When would you run temperature 0 in an enterprise workflow?

Question 17 of 73 · Updated

On this page

Interview-ready answer#

Temperature and top-p are decoding controls that influence how a language model selects its next token. Temperature changes the relative concentration of the probability distribution: lower temperature favors high-scoring tokens, while higher temperature makes alternative tokens more competitive. Top-p, also called nucleus sampling, limits sampling to the smallest set of highest-probability tokens whose cumulative probability reaches a specified threshold.

I would use temperature zero, or the lowest supported setting, for enterprise workflows where consistency matters more than diversity: extracting invoice fields, classifying support tickets, generating structured records, or producing standardized responses from trusted evidence. I would treat it as a baseline to evaluate, not a guarantee of deterministic or factually correct output.

For creative drafting, brainstorming and candidate generation, I might allow more sampling diversity. In either case, I would validate the output against the task's schema and source of truth, pin model and configuration versions where possible, and measure correctness, repeatability, latency and cost on representative customer data.

1. What happens before a token is selected?#

A generative language model produces one score, called a logit, for each candidate token in its vocabulary. Softmax converts these scores into a probability distribution. The decoding algorithm then selects the next token, appends it to the sequence and repeats the process until a stopping condition is met.

Model logits → Temperature scaling → Probability distribution → Top-p filtering → Renormalization → Token selection

This is a representative sampling pipeline. Actual inference engines may combine additional controls, such as top-k, repetition penalties, constrained decoding, token masks and stop conditions, in different orders. Temperature and top-p operate on next-token selection, not directly on the factual reliability of the model's answer.

2. Temperature: how concentrated is the distribution?#

For a positive temperature T, divide each logit by T before softmax:

LaTeX

Here is the logit for token i. Numerically stable implementations subtract the largest logit before exponentiation.

  • T = 1: Use the original softmax distribution, assuming no other transformations.
  • 0 < T < 1: Sharpen the distribution; higher-scoring tokens become relatively more probable.
  • T > 1: Flatten the distribution; lower-scoring alternatives become relatively more competitive.
  • T = 0: Do not literally divide by zero. A common implementation switches to greedy selection, choosing a highest-scoring eligible token.

Consider three hypothetical tokens with logits A = 2, B = 1 and C = 0.

TemperatureP(A)P(B)P(C)
0 (greedy)100%0%0%
0.586.68%11.73%1.59%
1.066.52%24.47%9.00%
2.050.65%30.72%18.63%

These values illustrate the mathematical operation, not probabilities measured from a particular deployed model. Rounding can make displayed percentages sum to slightly less or more than 100%.

Positive temperature does not change the ranking of finite logits, but it changes their probability ratios. Increasing temperature does not make a model more knowledgeable or necessarily improve the quality of its reasoning.

3. Top-p: how many candidates may be sampled?#

Nucleus sampling sorts candidates by descending probability and retains the smallest leading set whose cumulative probability is at least p. The retained probabilities are renormalized to sum to one, then the next token is sampled from that distribution.

For example, suppose the post-temperature probabilities are:

CandidateOriginal probabilityCumulative probabilityProbability after top-p = 0.8
A0.500.500.625
B0.300.800.375
C0.150.950
D0.051.000

A and B together reach the 0.8 threshold. C and D are excluded. Renormalization divides each retained probability by 0.8.

A common convention is that top-p = 1 disables nucleus filtering. Values close to zero usually leave only a small set of leading candidates. Exact boundary behavior and allowed ranges depend on the inference implementation.

Unlike top-k, which keeps a fixed number of candidates, top-p dynamically adapts the candidate count to the shape of the distribution. A highly concentrated distribution may need only one or two candidates, while a flatter distribution may need many.

4. Temperature versus top-p#

DimensionTemperatureTop-p
Primary effectRescales logits and changes concentrationRemoves the low-probability tail
Candidate setDoes not explicitly filter finite logitsRestricts sampling to a cumulative probability mass
Typical neutral setting1, for the mathematical scaling operation1, for nucleus filtering
InteractionChanges probabilities before selectionCandidate count depends on the resulting distribution

If temperature scaling precedes top-p, lowering temperature may make the nucleus smaller even if p remains unchanged. Changing both settings simultaneously makes it harder to attribute changes in output quality to either parameter.

I would normally establish a baseline and vary one sampling control at a time, unless a task-specific experiment deliberately evaluates their interaction. Provider defaults, supported values and processing order should be checked for the exact model and endpoint.

5. Tested Python implementations#

The examples below implement a finite-logit temperature distribution and nucleus filtering. They are educational, CPU-based implementations of the mathematical operations, not replacements for an optimized inference engine.

Temperature scaling with stable softmax#

PYTHON
import math def temperature_probs(logits, temperature): if not logits or any(not math.isfinite(x) for x in logits): raise ValueError('Expected nonempty finite logits') if not math.isfinite(temperature) or temperature < 0: raise ValueError('Invalid temperature') best = max(range(len(logits)), key=logits.__getitem__) if temperature == 0: return [float(i == best) for i in range(len(logits))] weights = [ math.exp((x - logits[best]) / temperature) for x in logits ] total = math.fsum(weights) return [w / total for w in weights]

Subtracting the largest logit avoids positive exponent overflow for ordinary finite logits. The zero-temperature branch chooses the first maximum when there is a tie. Other engines may have different tie-breaking behavior. This helper deliberately excludes infinite logits and token masks; production decoding must handle masked tokens according to the inference framework.

Nucleus filtering and renormalization#

PYTHON
def nucleus_probs(probs, p): if not 0 < p <= 1 or not probs or any( not math.isfinite(x) or x < 0 for x in probs ): raise ValueError('Invalid probabilities or top-p') total = math.fsum(probs) if not math.isclose(total, 1.0, rel_tol=0, abs_tol=1e-9): raise ValueError('Probabilities must sum to one') normalized = [x / total for x in probs] if p == 1: return normalized order = sorted( range(len(probs)), key=lambda i: (-normalized[i], i) ) kept = [] mass = 0.0 for i in order: kept.append(i) mass += normalized[i] if mass >= p: break selected_mass = math.fsum(normalized[i] for i in kept) selected = set(kept) return [ x / selected_mass if i in selected else 0.0 for i, x in enumerate(normalized) ]

For a distribution [0.5, 0.3, 0.15, 0.05] and p = 0.8, the result is approximately [0.625, 0.375, 0, 0]. Floating-point arithmetic may affect candidate inclusion extremely close to a cumulative threshold. Once a distribution is constructed, a sampling routine can draw a token from it using a random number generator.

Temperature scaling requires O(V) time and O(V) output space for vocabulary size V. This nucleus implementation sorts the vocabulary and requires O(V log V) time and O(V) auxiliary space. Optimized engines may use more efficient GPU algorithms.

Local verification: 5,051 Python test cases passed. The tests covered 720 temperature-distribution cases and 4,320 combinations of those distributions with six top-p thresholds, ten invalid-input cases and one explicit nucleus example. Checks included normalization, nonnegative probabilities, agreement with a reference softmax, greedy selection, cumulative mass, candidate ordering and renormalization. Boundary comparisons used floating-point tolerances. These are mathematical implementation tests, not live-model inference or API determinism tests.

6. When would an FDE choose temperature zero?#

Enterprise workflowStarting approachAdditional controls
Invoice or contract field extractionGreedy or low temperature, if supportedSchema validation, source spans, missing-field handling
Support ticket classificationGreedy or low temperatureApproved label set, confusion matrix, confidence calibration
Standardized policy Q&ALow-diversity baselineAuthorized retrieval, citations, applicability checks, abstention
Tool argument generationLow-diversity baselineTyped schemas, permission checks, business-rule validation
Marketing draft alternativesEvaluate moderate sampling diversityBrand policy, factual review and human approval
Multiple candidate solutionsEvaluate sampling with diversityScore candidates with tests or trusted evaluation criteria

These are reasonable starting configurations, not universal recommendations. Some specialized or reasoning models do not expose temperature or top-p controls. Their default decoding behavior may be the correct baseline.

For extraction, classification or rules that can be implemented reliably with deterministic software, consider whether an LLM is needed at all. For example, derive invoice totals using validated arithmetic rather than ask a model to invent a numerical answer.

7. Why temperature zero does not guarantee determinism#

Greedy decoding is deterministic in an idealized implementation with identical logits, fixed constraints and stable tie-breaking. A hosted inference system, however, may not reproduce those exact conditions on every request.

Sources of variation include:

  • Model checkpoint or backend revisions.
  • Floating-point rounding, hardware and kernel behavior.
  • Dynamic batching and parallel execution.
  • Near-ties between token scores.
  • Changes in retrieval results, conversation state or tool responses.
  • Different prompts, decoding constraints, routing and stopping conditions.

Small numerical differences can alter the selected token when candidates are close in score. Once a token differs, subsequent autoregressive predictions can diverge as well.

Seeds can improve reproducibility for sampled generation when supported, but should not be treated as a cross-model or cross-backend guarantee. Setting a seed also does not fix variations in retrieved documents or external tools.

Where consistency is a business requirement, record the model version, prompt template version, decoding settings, retrieved evidence identifiers and relevant tool state. If exact replay is required, consider a validated response cache keyed on appropriate authorized, versioned inputs, or a deterministic business-rule engine. Enforce cache isolation, data retention and freshness requirements.

8. Why low temperature is not a factuality or security control#

Temperature zero chooses the highest-scoring eligible token. If that token is incorrect, greedy decoding can produce the same incorrect answer repeatedly. A valid JSON object can still contain invented values.

For an enterprise policy assistant, retrieve applicable documents, require citations to support important claims and allow abstention when evidence is insufficient. For financial or transactional workflows, rely on authorized systems of record and deterministic business logic.

Tool calls require independent authorization, argument validation and confirmation where appropriate. A model-generated success message does not prove a real transaction occurred. Sampling configuration cannot substitute for those controls.

9. Practical FDE scenario: invoice extraction#

Suppose a customer wants invoice PDFs converted into structured records containing invoice number, date, currency and line items.

I would establish an extraction schema with explicit missing-value handling, then benchmark a greedy or low-temperature configuration using representative invoices. Preserve the source text and document locations so extracted fields can be audited. Validate the schema, reconcile totals using decimal arithmetic and flag inconsistent or ambiguous records for review.

Compare the baseline with an alternative sampling configuration on a fixed, labeled evaluation dataset. Measure exact field accuracy, missing-field behavior, schema validity, repeatability across repeated runs, manual review rate, latency and cost per correctly processed invoice.

If higher temperature generates more varied but incorrect field values, it provides no useful benefit for this workflow. If a different configuration improves task accuracy, use the measured result rather than assuming temperature zero must always win.

This is a hypothetical deployment scenario, not a reported customer outcome.

10. Production configuration and evaluation#

  • Define a task-specific baseline with explicit decoding settings and output limits. Record the model's documented supported controls.
  • Version prompts, model identifiers, generation settings, schemas and retrieval configuration.
  • Use a representative held-out dataset that includes ambiguous inputs, rare categories, multilingual records, missing information and malformed source data.
  • Measure both accuracy and consistency. Repeatedly producing an identical wrong answer is not success.
  • Compare latency, token usage and cost per successful task; sampling settings can affect output length and stopping behavior, but do not imply a universal speed or cost improvement.
  • Use controlled rollout, monitoring and rollback if a model or decoding change degrades customer outcomes.

For probabilistic workflows, evaluate repeated runs rather than selecting a configuration from one favorable example. If using multiple candidate generations, include the extra inference cost and the reliability of the candidate-selection method.

Likely interviewer follow-ups#

What is the difference between top-k and top-p? Top-k restricts sampling to a fixed count of highest-scoring candidates. Top-p restricts it to a variable-size nucleus based on cumulative probability.

Is top-p = 0.9 equivalent to temperature = 0.9? No. One sets a cumulative probability threshold; the other rescales logits.

Should I tune both simultaneously? Usually start by varying one control at a time to understand its effect. Evaluate combinations deliberately if the task requires it.

Is temperature zero always best for enterprise AI? No. It is a useful baseline for consistency-oriented workflows, but quality must be measured. Creative tasks, exploration and candidate generation may benefit from diversity.

Can a fixed seed guarantee identical responses? Not generally. Seed support and reproducibility guarantees depend on the inference service and execution conditions.

How do you guarantee valid output? Use constrained generation or structured output where supported, validate the schema and business rules, and verify important values against authoritative data. Temperature alone cannot guarantee either syntax or correctness.

Related questions

Explore other topics:AI AgentsAI System DesignLarge Language Models