Skip to main content
Back to all articles
AI Engineering 16 min readUpdated November 18, 2026

Reproducibility Contracts for LLM Evaluations: Isolating Inference Drift from Agent Drift

Greedy decoding does not make an LLM evaluation reproducible. Build a production reproducibility contract with pinned inference identities, batch-pressure experiments, first-divergence diagnostics, reliability gates, and safe replay.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#llm-inference#reproducibility#batch-invariance#evaluation#vllm#typescript#python#reliability#model-serving
On this page

A test suite for a conventional API normally assumes that identical input and code will produce identical output, unless the contract explicitly allows variation. An LLM-based feature introduces more boundaries: model weights, tokenizer, request assembly, inference runtime, GPU kernels, batch scheduling, external evidence, and the evaluator that judges the answer.

A low sampling temperature changes one of those boundaries. It does not freeze the others.

For production AI systems, I would stop treating the decoding configuration as a promise of reproducibility and instead define a reproducibility contract: what kind of repeatability the product needs, which execution variables are controlled, and what evidence is required when two runs disagree.

This is an original architectural design for a hypothetical engineering-support assistant that summarizes incident tickets and proposes a next investigation step. No benchmark numbers in this article are claimed as measured results. The code is a starting point for a test harness, not a claim that a particular model or provider has been tested.

This topic differs from my previous articles on recording and replaying agent runs, repeated-trial agent reliability, and release gates for model upgrades. Those explain how to reproduce workflows or measure stability. Here the focus is proving which inference-layer conditions changed before interpreting an evaluation failure.

The word reproducible needs a scope

When somebody asks whether an LLM response is deterministic, I ask which contract they mean. These are not interchangeable:

ContractWhat must repeat?What is controlled?
Recorded-boundary replayApplication behavior when given the same recorded model/tool responsesThe harness supplies recorded external results
Fixed-runtime generationGenerated tokens for a fixed request in a pinned execution environmentModel, tokenizer, runtime, hardware, and relevant decoding state
Load-invariant generationGenerated tokens for the same request even when neighboring requests varyExecution kernels and supported scheduler paths must preserve batch invariance
Behavioral stabilityOutput satisfies a task's acceptance criteria over repeated live executionsEvaluated behavior, not necessarily identical bytes

One important implication: a system may meet the fourth contract even if it fails the second. Two answers can use different words yet both satisfy the same factual and authorization requirements. Conversely, a model may produce the same wrong answer every time and pass a strict exact-match consistency check while failing the task.

For safety-critical actions, neither token identity nor semantic similarity replaces authorization, current evidence, and independently verified outcomes.

Identify the source of a changed token

The decoding process has two major stages: model computation produces scores over candidate tokens, then a decoding rule chooses the next token. With typical greedy decoding, the rule chooses the largest score.

A fixed selection rule cannot make different score vectors identical.

Floating-point arithmetic has finite precision. Algebraically equivalent reductions can have different rounded results when additions are grouped in different orders. In high-throughput inference, the operator implementation and reduction schedule may change with tensor shapes, batch composition, execution strategy, or hardware.

That does not mean every GPU operation is randomly timed into a different numerical answer. A particular kernel under the same implementation and inputs can be perfectly repeatable. The harder property is that an individual request retains the same numerical result when the system executes it alongside different requests.

The primary research explanation comes from Thinking Machines Lab's work on batch-sensitive inference. The LLM-42 research paper also analyzes floating-point reduction order and dynamic batching, and describes a verification-based technique for deterministic inference.

The application-level consequence is straightforward: if a small numerical difference changes the selected token near a decision boundary, later tokens are conditioned on a different prefix. A difference at one decoding step can therefore change an entire response, even when the model is configured for greedy selection.

Do not blame the batch until you have eliminated simpler causes

A production diagnosis must first rule out configuration drift:

  • A provider may change the model revision behind an alias.
  • A prompt renderer may reorder messages, tool descriptions, retrieved passages, or whitespace.
  • A tokenizer, runtime, quantization, adapter, or decoding library may change.
  • A request can receive a different tool response or document snapshot.
  • A model-generated tool call may change downstream application state.

Batch-sensitive numerical behavior is an important possibility, not a universal explanation for every different answer.

A four-layer experiment separates the failure domains

I would build the test harness in layers rather than send a prompt to an API ten times and call the resulting variability "model randomness."

~~~text Versioned evaluation case | Canonical request + immutable fingerprint | +------------+-------------+ | | Recorded replay Live inference | | Same recorded output Pinned execution profile | | Does application +--------------------+ behavior match? | | | Quiet / isolated Concurrent load | | | Application-state gate Token-level diff Token-level diff | | | +--------------------------+--------------------+ | First-divergence analysis and semantic task checks | Reproducibility evidence report

Different comparisons answer different questions. ~~~

Layer A — Recorded replay. Feed the exact prior model and tool outputs to the application. If it diverges here, investigate application state, event ordering, code, and harness fidelity before blaming inference numerics.

Layer B — Pinned isolated inference. Send the same tokenized request to an unchanged deployment under low contention. If it diverges, inspect runtime settings, unsupported deterministic operations, hidden provider changes, and output processing.

Layer C — Pinned inference under varied concurrency. Keep the target request and decoding configuration fixed while varying unrelated background traffic. A divergence appearing only in this layer is evidence consistent with scheduling or batch-sensitive behavior, not by itself proof of a particular kernel defect.

Layer D — End-to-end workflow. Re-enable retrieval, tools, and multi-step reasoning. Measure whether the user's required outcome remains valid. This is where exact token equivalence often matters less than evidence, safe actions, and task completion.

These layers form a diagnostic ladder. Do not start at Layer D and assume the difference was caused by Layer C.

Give each evaluation a reproducibility manifest

An evaluation result without its execution identity is difficult to interpret later. The manifest should bind the exact request to the exact environment being compared.

For a self-hosted inference route, capture:

  • canonical request hash and the *token IDs* actually sent to the model, if available;
  • model weight identity, tokenizer revision, adapter and quantization configuration;
  • inference engine version, container/image identity, and numerical precision;
  • GPU family and the execution topology relevant to the selected engine;
  • decoding parameters, seed if relevant, stop conditions, maximum generation length;
  • batching mode and deterministic-kernel settings;
  • application prompt-template and tool-schema revisions;
  • corpus snapshot and tool-response references when testing an agent rather than a raw model.

For an external API, you may not be given the weight digest, precise backend hardware, batch membership, or kernel selection. Record what the provider actually exposes, including model identifiers and any response-level revision metadata. Mark unavailable details as unknown. Do not label a hosted endpoint "fully pinned" merely because a user-facing model string stayed constant.

The manifest should be immutable for each test run and linked to the generated artifact. Keep secrets, personally identifiable request content, and raw access tokens out of general observability exports.

TypeScript: compare the first divergence, not only the final text

A final-string mismatch tells you that two runs differ. It does not tell you where the divergence began or whether the inputs were actually equivalent.

Here is a small comparison layer. It assumes a trusted adapter has recorded token IDs; it does not attempt to reconstruct token IDs by retokenizing rendered response text.

~~~typescript type InferenceEvidence = Readonly<{ caseId: string; requestSha256: string; runtimeProfileId: string; modelRevision: string; tokenIds: readonly number[]; taskPassed: boolean; }>;

type Comparison = | { kind: "incomparable"; reason: string } | { kind: "comparable"; tokensEqual: boolean; firstDifferentToken: number | null; lengthA: number; lengthB: number; taskPassChanged: boolean; };

export function compareInference( a: InferenceEvidence, b: InferenceEvidence, ): Comparison { if (a.caseId !== b.caseId) { return { kind: "incomparable", reason: "different_case" }; } if (!a.requestSha256 || a.requestSha256 !== b.requestSha256) { return { kind: "incomparable", reason: "request_changed" }; } if (!a.modelRevision || a.modelRevision !== b.modelRevision) { return { kind: "incomparable", reason: "model_revision_changed" }; } if (!a.runtimeProfileId || a.runtimeProfileId !== b.runtimeProfileId) { return { kind: "incomparable", reason: "runtime_profile_changed" }; }

const common = Math.min(a.tokenIds.length, b.tokenIds.length); let firstDifferentToken: number | null = null;

for (let index = 0; index < common; index++) { if (a.tokenIds[index] !== b.tokenIds[index]) { firstDifferentToken = index; break; } } if (firstDifferentToken === null && a.tokenIds.length !== b.tokenIds.length) { firstDifferentToken = common; }

return { kind: "comparable", tokensEqual: firstDifferentToken === null, firstDifferentToken, lengthA: a.tokenIds.length, lengthB: b.tokenIds.length, taskPassChanged: a.taskPassed !== b.taskPassed, }; } ~~~

The first-divergence index is a diagnostic tool, not a numerical root-cause proof. Token IDs can differ because of a changed request, tokenizer, stop condition, or runtime. This function requires callers to compare only records that belong to the same declared profile; the surrounding harness must verify that the profile really binds the same tokenizer, decoding configuration, model, and environment.

There is a critical limitation: even a matching profile *name* is insufficient unless the identity is backed by a versioned deployment manifest. Do not let test clients choose arbitrary trusted profile IDs.

Python: organize repeated cases into an experiment matrix

The harness should vary one important execution dimension at a time. A Python runner can enforce input consistency and collect enough trials to compare *within-condition* instability to *between-condition* changes.

The following example is deliberately adapter-neutral. A real provider adapter should implement the call, return token IDs only when genuinely available, and attach a verified deployment profile. It should not invent internal token traces from visible strings.

~~~python from dataclasses import dataclass from typing import Callable, Sequence

@dataclass(frozen=True) class Sample: case_id: str profile: str condition: str tokens: tuple[int, ...] task_passed: bool

def summarize(samples: Sequence[Sample]) -> dict: if not samples: raise ValueError("at least one sample is required")

case_ids = {x.case_id for x in samples} profiles = {x.profile for x in samples} conditions = {x.condition for x in samples}

if len(case_ids) != 1 or len(profiles) != 1 or len(conditions) != 1: raise ValueError("summarize one case/profile/condition at a time")

# Compare against the first captured result for this condition. # This counts differing outputs, not the probability of every # possible alternative. Report number of trials alongside it. baseline = samples[0].tokens changed = sum(x.tokens != baseline for x in samples[1:]) return { "case_id": samples[0].case_id, "condition": samples[0].condition, "trials": len(samples), "distinct_token_sequences": len({x.tokens for x in samples}), "changed_from_first": changed, "task_failures": sum(not x.task_passed for x in samples), }

def run_condition( case_id: str, profile: str, condition: str, trials: int, invoke: Callable[[str], tuple[tuple[int, ...], bool]], ) -> list[Sample]: if trials < 2: raise ValueError("repeat the case at least twice")

results: list[Sample] = [] for _ in range(trials): # The implementation of invoke owns scheduling/background load. # It must not change the target request across repetitions. tokens, passed = invoke(condition) results.append(Sample(case_id, profile, condition, tokens, passed)) return results ~~~

The caller runs the same case in an isolated condition, then under a controlled concurrent workload. The harness needs a separate *load controller* for the latter; invoking unrelated traffic should not mutate the target prompt or tool evidence. A load test should vary concurrency over a documented range and observe whether the engine actually changed the batch shape; otherwise "concurrent" is merely a label.

For public APIs, you generally cannot force a particular batching arrangement. A cross-load comparison is then observational rather than a controlled batch-invariance experiment. That limits what causal claim the report can support.

Self-hosting: what batch invariance can buy

There are two separate ways to reduce execution variability:

  1. Keep the scheduler and execution order stable, when the runtime and workload permit it.
  2. Make the underlying operators invariant to batch changes, so a request remains numerically consistent even as other requests arrive.

The vLLM reproducibility documentation explains that the default configuration prioritizes performance over reproducibility. It documents two options for offline workloads: controlling multiprocessing/scheduling or enabling batch invariance. For online serving, the documented option is batch invariance.

The vLLM batch-invariance documentation describes the environment variable below for supported deployments:

~~~bash VLLM_BATCH_INVARIANT=1 vllm serve <approved-model> ~~~

The placeholder is not an executable model identifier. Before adopting that configuration, check the documented hardware and model support and pin the tested vLLM version. The docs describe deterministic kernel choices and altered optimizations, along with possible performance costs. They also limit their reproducibility claim to the same hardware and vLLM version.

Batch invariance is not a universal cross-GPU bitwise-output contract. Nor does enabling the flag make network APIs, tool calls, retrieval, prompt assembly, or agent state deterministic. Its assurance applies to the supported inference configuration, under the conditions stated by the engine maintainers.

Research on verified speculative determinism proposes a different performance approach: generate candidate tokens on a fast path, then verify consistency before committing them. That is a research strategy, not a capability you should assume every provider exposes.

Protect the release pipeline from false confidence

If a test suite expects exact bytes from a model response, it should explicitly declare a bitwise reproducibility requirement and run only where the serving stack claims and demonstrates that capability. A normal hosted model API may not offer enough control to make such a promise.

For product behavior tests, use a different contract:

  • deterministic assertions for schema validity, authorization, tool permissions, and prohibited side effects;
  • evidence-based checks for required factual support;
  • repeated trials for variable, semantic outputs;
  • explicit minimum success criteria and uncertainty reporting;
  • separate tests for controlled inference conditions and full agent workflows.

My article on LLM evaluation in CI covers release gating; the additional rule here is that a failed test should carry an explanation of which reproducibility contract it was trying to enforce.

If an evaluator scores a different but correct answer as a failure, the harness may be testing exact wording rather than the product requirement. If two runs take different tool paths but cause identical valid outcomes, inspect whether tool ordering is constrained for safety before treating the difference as a defect.

A stable pass rate is not enough either: two versions could have identical average success rates while failing different high-risk cases. Use per-case repeated trials and inspect failures by risk class, as discussed in agent pass-k consistency tests.

A failure matrix to run before enabling deterministic mode

I would test these scenarios in an isolated preproduction system. They are proposed experiments, not claimed findings.

VariationWhat should stay fixed?What to inspect
Same prompt, same pinned runtime, quiet loadRequest token IDs, model and runtime versionsIdentical token output under a documented reproducibility profile
Same request, different concurrencyEverything except background workBatch sensitivity and first divergence
Same prompt text, changed tokenizerNothing should be assumed equalTokenization changes before inference
Same request, new inference engine buildModel weights may matchKernel, scheduler, and output changes
Same inference result, different tool snapshotsModel boundary recorded separatelyAgent behavior attributable to evidence
Same model, changed prompt-template orderModel weights and decodingInput fingerprint mismatch
Same test case, two evaluator revisionsCandidate answer retainedScoring drift rather than inference drift
Recorded model and tool replies, new app codeExternal boundaries frozenApplication-state regression

Do not automatically turn every mismatch into a production incident. A formatting difference in a brainstorming tool is unlike an altered payment authorization recommendation. The severity of divergence belongs in the evaluation contract, not in a universal token-diff alarm.

Observe the cause, without exposing the prompts

For each experiment, I would store:

  • a trusted case ID and salted or scoped fingerprint of the canonical request;
  • environment and execution profile IDs;
  • number of repetitions and the controlled load condition;
  • distinct token sequences, first-divergence positions, and available token-level statistics;
  • semantic pass/fail results with evaluator version;
  • latency, throughput, and resource cost of any deterministic serving mode;
  • configuration differences and unknown metadata that limit causal attribution.

Avoid raw prompts and completion text in ordinary metric labels. In many systems the full input or model output is sensitive. Keep the content in access-controlled evaluation artifacts only when necessary, encrypt it, set retention limits, and allow deletion as required. Hashes themselves can reveal common prompts if they are unsalted and globally comparable; scope or protect them accordingly.

One more security consideration: a user or adversary should not be able to submit arbitrary request fingerprints or runtime manifests that the evaluation service treats as authoritative. Derive identity from the gateway and controlled deployment system, not from model-generated metadata.

A useful dashboard answers *which layer is unstable* rather than presenting a single "LLM nondeterminism rate" that mixes changing documents, model deployments, concurrent inference, and evaluator disagreements.

When determinism is worth paying for

A bitwise-stable inference route can make debugging, numerical experiments, and reinforcement-learning comparisons significantly easier. It is especially valuable when the product truly requires repeatable tokens under documented conditions.

But enforcing deterministic kernels or restrictive scheduling can cost throughput, latency, or supported model flexibility. The correct overhead is workload-specific and must be measured on your deployment; I would not copy a performance number from someone else's hardware into a capacity plan.

For a customer-facing research assistant, semantic correctness with trustworthy citations may matter more than exact token identity. For an offline scientific benchmark, a reproducible fixed-runtime output may be central to the experiment. For an agent authorized to affect production resources, deterministic output is not enough: tool authorization, state checks, and outcome verification still decide whether an action is safe.

The operating rule is to choose the narrowest contract that addresses the actual failure mode. You can make a workflow replayable without making the model numerically deterministic. You can make inference reproducible within a pinned environment without guaranteeing the rest of the agent. You can require stable business outcomes without requiring identical sentences.

A release checklist I would approve

Before claiming an inference configuration is reproducible, I would require an explicit statement covering:

  1. The target contract: recorded replay, fixed-runtime tokens, load-invariant tokens, or behavioral acceptance.
  2. What is pinned: exact request tokens, model, tokenizer, runtime, hardware, adapters, and decoding settings where available.
  3. What cannot be verified: hidden provider revisions and batch scheduling must be labeled unknown.
  4. The experiment design: isolated repetitions, controlled concurrency, and a documented trial count.
  5. The evaluation rules: token mismatch and task failure are reported separately.
  6. The performance trade-off: latency and throughput are measured for the proposed deterministic mode.
  7. The security boundary: traces, prompt data, and model/provider credentials are protected.
  8. The rollback plan: an incompatible engine upgrade cannot silently change the reproducibility profile.

My conclusion is not that every LLM system should force identical tokens. It is that teams should stop using a decoding parameter as an explanation for behavior they have not measured. Reproducibility is a contract between the request, the runtime, and the evaluator. When any of those changes, the evidence needs to show it.

Primary technical sources

KEEP READING

Related engineering notes