20.13 Batch invariance and numerical reproducibility
An inference service often changes batch composition from one step to the next. A request that produces one answer alone may produce another beside a longer request, even with greedy decoding and the same weights. Understanding this behavior is necessary for reproducible evaluation, caching, regression tests, and RL rollouts.
Concepts from other sections (16)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- greedy decoding: taking the single most likely token at every step; a beam of size 1. Read more: 10.4 Beam search, generic over a step function
- split-K: parallelizing a matmul by splitting the reduction dimension across threads, which breaks bitwise reproducibility. Read more: 22.3 Cache-blocked, packed, batch-invariant matmul in C
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- chunked prefill: prefilling a prompt over several steps in pieces of at most
prefill_chunktokens, mixed with decodes. Read more: 23.4 Chunked prefill (mixed prefill + decode batches) - Mixture of experts (MoE): a layer of many expert MLPs of which a router picks per token. Read more: 13.8 Mixture of Experts
- mixed batch: one forward step containing both decode sequences and prefill chunks. Read more: 23.4 Chunked prefill (mixed prefill + decode batches)
- Dropout: randomly zeroing activations during training to approximate an ensemble of subnetworks. Read more: Chapter 2: Deep Learning
- token budget: the maximum number of tokens, prompt and generated, the scheduler puts into one step. Read more: 20.6 Inside an Inference Engine: How vLLM and SGLang Run a Model
- speculative decoding: drafting several tokens cheaply and verifying them in one target-model pass, preserving the output distribution. Read more: Chapter 20: Inference Engines and GPU Deployment
- PPO: a policy gradient method that clips the new-to-old probability ratio to keep updates small. Read more: 4.4 World models, multiple agents, and RLHF
- GRPO: a PPO-style RL method that replaces the critic with the group-normalized reward of several samples of the same prompt. Read more: 19.7 The training step and validation
- inference engine: software that loads weights, schedules requests, manages the KV cache, and generates tokens (vLLM, SGLang, TensorRT-LLM, llama.cpp). Read more: 20.5 LLM Serving Platforms: How They Work and When to Use Them
- KV cache: the stored keys and values of all processed tokens, per layer, that let each new token attend without recomputation. Read more: Chapter 20: Inference Engines and GPU Deployment
- LoRA adapter: a low-rank update stored separately from the base model. Read more: 20.3.4 Portability and load triage
- Top-p (nucleus): the smallest set of most likely tokens whose mass reaches , including the crossing token. Read more: 21.1 Sampling and logit processors
- KL divergence: , the excess cost of predicting with ; nonnegative and asymmetric. Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator in Mathematics
Learning objectives
- Distinguish mathematical equivalence, numerical agreement, deterministic execution, and batch invariance.
- Explain how reduction order, routing, and random-number assignment affect results.
- Design an invariance test with an explicit acceptance contract.
Four different contracts
Section titled “Four different contracts”| Contract | Question | Example check |
|---|---|---|
| Mathematical equivalence | Do algorithms represent the same function in exact arithmetic? | Cached attention equals full causal attention with matching positions and masks |
| Numerical agreement | Are finite-precision results within a stated tolerance? | Maximum absolute logit error and per-token log-probability error |
| Determinism | Does repeating the same supported execution produce the same result? | Repeated run with the same hardware, shapes, inputs, and runtime |
| Batch invariance | Does a request’s result stay the same when batch size, neighbors, or slot changes? | The same tokenized request alone, permuted, and amid mixed-length requests |
A deterministic kernel for each shape can choose different reduction trees for different batch shapes. It can therefore be deterministic without being batch-invariant. A result can be numerically close but select a different greedy token. Cross-device and cross-release bitwise equality requires a much stronger contract than repeatability on one fixed stack. PyTorch’s reproducibility documentation explicitly scopes its guarantees.
Why a seed and temperature zero are insufficient
Section titled “Why a seed and temperature zero are insufficient”Floating-point addition is not associative. In binary64 arithmetic,
a, b, c = 1e16, -1e16, 1.0assert (a + b) + c == 1.0assert a + (b + c) == 0.0Tiling, split-K matrix multiplication, attention split counts, and collective reduction trees can regroup sums. Different batch or sequence lengths can select a different kernel. Atomics can add an execution-order effect as well. Casting to a wider format in one stage does not restore precision already lost in another.
For greedy decoding, suppose two leading logits are and . Perturbations bounded by can reverse their order. If the gap between the best and second-best logits is larger than , a uniform absolute perturbation bound of preserves that step’s winner. If the gap is smaller, a flip is possible, not inevitable. Once a token changes, later prefixes differ and small initial numerical changes can become entirely different completions.
The kernel-level analysis in Thinking Machines Lab’s batch-invariance study separates fixed execution from fixed per-request computation across batch shapes. Its implementation and measurements illustrate one supported stack; they are not a universal performance guarantee.
Audit every source of dependence
Section titled “Audit every source of dependence”| Source | Why neighbors or scheduling may matter | Check or control |
|---|---|---|
| Matrix multiplication and normalization | Shape-dependent tiling or reduction order | Supported kernels with fixed per-request reduction semantics |
| Attention and chunked prefill | Different partitions, padding, positions, or cache paths | Full versus chunked versus cached logit comparison |
| Tensor/expert parallel collectives | Changed reduction order or rank layout | Fix topology; test all supported layouts separately |
| MoE routing | Capacity limits or batch-level balancing can change selected work | Inspect the actual router, overflow/drop policy, and expert outputs |
| Quantization | Dynamic activation scales may depend on a tensor or batch | Record scale granularity and compare alone versus mixed batches |
| Random numbers | A global RNG stream assigns draws by execution order | Request-local streams or counter-based indexing by request, step, and draw |
| Cache reuse | Wrong namespace, stale weights, or position handling | Include model, adapter, tokenizer, position, and relevant request semantics in cache identity |
| Model mode | Dropout or other training-mode behavior remains enabled | Evaluation mode and explicit handling of stateful layers |
Ordinary dense language-model inference should not mathematically attend across requests. If padding or packing lets it do so, that is a correctness bug, not a tolerance decision. Some model components can intentionally depend on batch statistics or capacity; their intended semantics must be documented before asserting invariance.
Define the test before measuring
Section titled “Define the test before measuring”Freeze the artifact revision, tokenizer and rendered token IDs, device topology, runtime and kernel versions, precision, sampler, and acceptance criterion. Then run the same probe in these conditions:
- Alone, repeatedly, with cold and warm caches.
- At several slots in batches of equal-length and mixed-length neighbors.
- With different arrival orders and continuously changing neighbors.
- With chunked prefill on/off and several token budgets.
- With prefix caching, speculative decoding, quantization, and supported parallel layouts changed one at a time.
First compare teacher-forced logits or token log probabilities on an identical fixed prefix. Then compare greedy token IDs and complete outputs. Record the first differing position, maximum and mean numerical errors, top-two logit margins, and context length. A forced-prefix comparison locates numerical drift; a free-generation comparison measures its behavioral consequence.
For sampling, use request-local random streams when testing exact replay. Equal seeds do not promise equal draws if engines consume RNG differently. An exact speculative algorithm targets the same distribution but need not emit the same sampled sequence under the same seed. If the contract is distributional, compare categorical frequencies on a small enumerable problem with uncertainty bounds and separately evaluate task quality. A finite test cannot prove equality for all outputs.
Report pass/fail against the chosen criterion. “Same text” is insufficient when log probabilities feed an RL learner. “Close logits” is insufficient when the application requires exact greedy replay. Do not call a tolerance pass bitwise invariance.
Controls are implementation-specific
Section titled “Controls are implementation-specific”A runtime may expose deterministic-algorithm selection, batch-invariant kernels, fixed attention splits, fixed graph shapes, deterministic collectives, or disabled autotuning. Each has a support matrix and a performance cost to measure. Some combinations of model, quantization, device, and parallelism remain unsupported.
As a concrete mapping, the vLLM batch-invariance documentation describes VLLM_BATCH_INVARIANT=1. This is a version-dependent runtime feature, not a portable flag or a guarantee across all models and hardware. Record the installed release and read its support restrictions before testing. The generic requirement remains the same regardless of provider: a request’s supported computation must be independent of irrelevant batch context.
SGLang documents --enable-deterministic-inference in its deterministic-inference guide. Apply the same model/backend/topology qualification and measurements. These rolling-documentation examples are separate from the archived vLLM 0.11.0 option table in the control guide.
Why training and RL care
Section titled “Why training and RL care”In ordinary training, changing the global batch intentionally changes the gradient estimate. Accumulation equivalence requires the same examples, masks, token weighting, optimizer schedule, and stochastic operations; bitwise equality may still fail through reductions. Batch normalization, dropout, or batch-level objectives add further dependencies. That is different from an inference request unintentionally changing because another customer arrived.
In PPO/GRPO, even identical weights can produce different probabilities in the rollout and learner paths if kernels, precision, or batching differ. Record actual behavior log probabilities and compare both paths on fixed tokens. Quantify the mismatch separately from policy-update KL. Batch-invariant inference can remove one source of mismatch; it does not remove stale weights, filtered sampling, or a tokenizer mismatch.
Trainer and inference engine drift
Section titled “Trainer and inference engine drift”An RL loop computes each token’s probability twice. The inference engine computes it while sampling: one token at a time, through a KV cache, in a batch shaped by whatever else is running. The trainer computes it again while scoring: one teacher-forced pass over the whole sequence, in a batch of its own choosing, often on different kernels or at a different precision. Trainer and inference engine drift is the gap between those two numbers for the same weights and the same tokens.
The PPO and GRPO ratio shows the cost. It divides the trainer’s probability by the sampler’s:
Before any update the two should be equal and should be . Suppose the sampler recorded for a token and the trainer computes from the same weights. Then before the model has changed at all. The update corrects against a number that describes another computation, so the loop is no longer strictly on-policy.
| Source of drift | Sampler side | Trainer side |
|---|---|---|
| Batch shape | Changes with load | Fixed by the data loader |
| Attention path | Incremental, through a KV cache | Full sequence in one pass |
| Precision and quantization | Often reduced for throughput | Often higher, with autocast |
| LoRA adapter | Often unmerged, for hot swapping | Merged or unmerged |
| Kernels and library versions | The serving runtime’s | The training framework’s |
| Sampling transforms | Temperature, top-p, constraints | Raw log probabilities unless the trainer reapplies them |
To measure it, score one fixed set of token IDs in both engines before training starts. Report the largest per-token log-probability difference and the KL divergence between the two distributions. That number is the floor of the mismatch, and it is separate from the policy-update KL that grows as the learner moves.
Key terms
Section titled “Key terms”- Batch invariance: independence of a request’s result from irrelevant co-batched requests and slot placement under a specified execution contract.
- Reduction tree: the grouping and order used to combine partial sums.
- Trainer and inference engine drift: the difference between the probabilities the sampling engine and the trainer compute for the same weights and tokens.
- Replay contract: the inputs, environment, and equality criterion promised for reproducing an execution.
Summary
Section titled “Summary”Specify the desired equality, isolate numerical differences on fixed prefixes, then test their effect on generation and learning. Treat reproducibility settings as measured controls with scoped guarantees.
Review questions
Section titled “Review questions”-
Every fixed batch repeats exactly, but the probe changes when a neighbor is added. Which contract failed?
Answer
Batch invariance. Determinism of each fixed execution can still hold. -
Can a top-two gap of be reversed if every logit changes by at most ?
Answer
No at that step: the worst gap reduction is $0.002$, smaller than $0.01$. This does not establish a bound for later steps unless their prefixes and error bounds also match. -
The sampler recorded a probability of for a token. The trainer, with the same weights, computes . What is the PPO ratio before any update, and what does it show?
Answer
$0.303 / 0.300 = 1.01$. The ratio should be $1$ at that point. The gap is trainer and inference engine drift, not a policy update, so the two engines are computing slightly different policies. -
Why can the engine and the trainer disagree on one sequence even when both are deterministic?
Answer
Each can repeat its own result exactly and still differ from the other. The engine decodes incrementally through a cache in a load-dependent batch, and the trainer scores the full sequence in one pass, so the reductions are grouped differently. -
How do you measure this drift before training starts?
Answer
Score the same fixed token IDs in both engines, then report the largest per-token log-probability difference and the KL divergence between the two distributions.
Further reading
Section titled “Further reading”- Horace He and Thinking Machines Lab, Defeating Nondeterminism in LLM Inference: the kernel-level account of batch-dependent results.
- Henderson et al., Deep Reinforcement Learning that Matters, and Engstrom et al., Implementation Matters in Deep Policy Gradients: evidence that seeds and implementation details change RL results.
- Espeholt et al., IMPALA: an estimator designed for a learner that runs ahead of its actors.
- Kwon et al., PagedAttention: the serving design whose batching makes a request’s neighbors change.
Checks
Section titled “Checks”The float-association and margin examples run in learning checks. They demonstrate a mechanism; the engine matrix above must be run on the actual serving stack before making an invariance claim.