Sub topic 4
Why the same input can produce different outputs
This chapter assumes you know the classic ML lifecycle of training, validating and deploying a model. It also assumes you can call an LLM through an SDK or HTTP API in Python, and that you know how a service is logged and monitored. The chapter explains where output variation comes from. It also covers which parts you can control and what that means for testing.
Classic inference versus LLM inference
A classic model deployed for serving is usually a pure function. You send the same feature vector to the same model version and get the same score back. Tests can assert exact equality, and a changed output means something upstream changed.
An LLM call breaks this assumption. The model produces text one token at a time. At each step it computes a probability distribution over the vocabulary and then picks a token from it. How the token is picked, and what else can shift the distribution, creates variation at several layers. Some of it is deliberate and some is not.
Sources of variation
The table groups the sources by who controls them.
| Source | Mechanism | Who controls it | Typical mitigation |
|---|---|---|---|
| Sampling | Tokens are drawn randomly from a probability distribution | You | Lower temperature, narrower top_p, a seed where offered |
| Input assembly | Retrieved documents, dates, user history or tool output change the prompt | You | Log the full assembled prompt, snapshot context in tests |
| Infrastructure | Batching and parallel floating-point arithmetic change numeric results slightly | Provider | Accept it and measure it |
| Model changes | A model alias points to a new snapshot, or the provider patches serving | Provider | Pin dated model identifiers, run evaluations on a schedule |
Sampling
The model outputs raw scores called logits, one per candidate token. A softmax function turns them into probabilities. Temperature divides the logits before the softmax. A low temperature sharpens the distribution so the top token dominates. A high temperature flattens it so unlikely tokens get picked more often.
Other settings narrow the candidates before the draw:
- top_k keeps only the k most likely tokens.
- top_p (nucleus sampling) keeps the smallest set of tokens whose probabilities add up to p.
The following script shows the effect. It uses only the standard library and a toy four-token distribution.
import math
import random
from collections import Counter
tokens = ["refund", "credit", "reimbursement", "chargeback"]
logits = [3.0, 2.5, 1.0, 0.2]
def softmax(values, temperature):
scaled = [v / temperature for v in values]
peak = max(scaled)
exps = [math.exp(v - peak) for v in scaled]
total = sum(exps)
return [e / total for e in exps]
def sample(temperature, rng):
probs = softmax(logits, temperature)
return rng.choices(tokens, weights=probs, k=1)[0]
for temperature in (0.2, 1.0, 1.5):
rng = random.Random(7)
counts = Counter(sample(temperature, rng) for _ in range(1000))
print(temperature, dict(counts))At 0.2, almost every draw is "refund". At 1.5, the other tokens appear regularly. A real model repeats this draw for every token, and each choice changes the context for the next one. Small early differences therefore compound into different sentences.
Setting the temperature to 0 usually means greedy decoding. The model always takes the highest-probability token, so there is no random draw. Some providers do not allow a temperature of exactly 0, and some newer models fix or ignore sampling parameters. Check your provider's documentation for the model you use.
Input assembly
Often the "same input" is not the same. A prompt that includes today's date, a retrieved passage, or a tool result changes whenever those parts change. Your application receives a user question, but the model receives the assembled prompt. If you log only the question, you cannot explain why Tuesday's answer differs from Monday's.
Common hidden inputs:
- Current date or time inserted by the template.
- Retrieval results that change when the index is updated or when ranking has ties.
- Conversation history that grows between calls.
- Tool outputs such as database rows or search results.
Infrastructure effects
Even at temperature 0, providers do not always guarantee identical output. Floating-point addition is not associative, so summing the same numbers in a different order can give slightly different results. The order can depend on how your request was batched with others on the GPU. Two candidate tokens that are nearly tied can then swap places, and the text diverges from that point on. Mixture-of-experts routing and server-side changes can add to this.
A seed parameter, where offered, makes the random draw repeatable. Providers generally describe it as best effort, and it does not remove the infrastructure effects. Treat it as a way to reduce variation, not to guarantee it away.
Model changes
A model name without a date, such as a "latest" alias, can move to a new snapshot without any change in your code. Output style, length and refusal behavior can all shift. This is variation across time rather than across calls, and it is the one most likely to hit you as a regression. Pin the dated identifier and record it as part of the prompt version from the earlier chapter on versioned artifacts.
Open-ended outputs
Variation is not always a defect. Many tasks have several correct answers. These two summaries are both fine:
- "The customer was charged twice for one invoice and wants a refund."
- "A duplicate charge appeared on the invoice; the customer requests money back."
The difficulty is that classic test tools assume one right answer. Exact-match assertions fail on good outputs. Loose assertions pass on bad ones. You have to decide which properties of the output matter, such as required facts, length limits, format validity and absence of banned content. You then check those properties instead of the exact string. The next chapter on evaluation builds on this.
Measuring variability instead of guessing
Before you decide how strict a test can be, measure how much your system varies. Run the same input several times and compare. The function below reports how many distinct outputs appeared and how often the most common one occurred. The fake_generate function stands in for a real model call so the script runs as shown.
import random
from collections import Counter
def stability_report(generate, text, runs=10):
outputs = [generate(text).strip() for _ in range(runs)]
counts = Counter(outputs)
modal_share = counts.most_common(1)[0][1] / runs
return {"runs": runs, "distinct": len(counts), "modal_share": modal_share}
def fake_generate(text):
return random.choice([
"Customer reports a duplicate charge.",
"Customer reports a duplicate charge.",
"Customer was billed twice.",
])
print(stability_report(fake_generate, "My invoice shows a duplicate charge."))Two numbers are useful in practice:
- distinct counts how many different strings you saw. One means the setup is effectively deterministic for this input.
- modal_share is the fraction of runs that gave the most common output. A high value means the typical answer is stable even when rare variants appear.
Exact string comparison is a strict measure. For free text you will often want to compare a property instead, such as "mentions the charge" or "is under 60 words". This is why the evaluation harness in this tutorial reports a pass rate over repeated runs and does not report a single pass or fail.
Practical controls
- Pin the model identifier. Use dated snapshots where the provider offers them, and schedule an evaluation run so you notice when a deprecation forces a move.
- Choose sampling settings per task. Extraction, classification and structured output usually want low temperature. Brainstorming and drafting can tolerate more. Record the values in the prompt version.
- Constrain the output format. Use a schema, enumerated labels or a structured-output feature so that variation shows up in content and not in shape. Validate in code and retry or fall back on failure.
- Log the assembled prompt. Store what the model actually received, subject to your data handling rules, so a surprising output can be reproduced or explained.
- Test with repetition. Run each evaluation case several times, as in the harness from the spine, and set thresholds on the rate, not on a single run.
- Do not cache and call it determinism. Caching identical requests gives repeatable answers for those requests, but it hides variation. It does not remove it for new inputs.
Common errors
- Testing once. One passing run says little about a system whose output is drawn from a distribution. A case that passes 6 times in 10 looks fine on a lucky single run.
- Blaming the model for context changes. If retrieval or templating changed, the input differed. Check the logged prompt first.
- Using aliases in production. An unpinned model name turns a provider update into an unannounced release.
- Over-tightening. Forcing temperature to 0 to satisfy a test can reduce quality on tasks that benefit from varied phrasing. Fix the test to check properties instead.
- Ignoring variation in tails. An average pass rate of 95% can hide a case that fails 40% of the time. Report per-case rates.
What carries forward
Variation changes three downstream practices. Evaluation must repeat runs and check properties. Release gates must compare rates with some tolerance, since a small drop may be noise. Tracing must capture the full prompt, settings and model identifier, so that any single odd output can be tied to its cause.
Exercise
Your team's test asserts that a summarization prompt returns exactly the string "Customer reports a duplicate charge." at temperature 0. It passes on most runs but fails about 1 in 20. Name two possible causes and describe a better test.
Show answer
Possible causes: floating-point and batching effects on the provider side can change a near-tied token even at temperature 0, and the assembled prompt or model snapshot may have changed (for example a date in the template or an unpinned model alias). A better test runs the case several times and checks properties of the output, such as mentioning the charge and staying under a word limit, then requires a pass rate above a threshold. Also log the full prompt and the model identifier so failures can be traced.
Exercise
Using the sampling script above, what do you expect to happen to the counts as temperature rises from 0.2 to 1.5, and why?
Show answer
At 0.2 almost all draws are the highest-logit token "refund". As temperature rises, dividing the logits by a larger number flattens the softmax distribution, so lower-ranked tokens such as "credit" and "reimbursement" appear more often and the counts spread out.