Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Floating point | The way computers store real numbers: a sign, an exponent and a limited number of significant bits (10.k). Every result is rounded. |
| Associative | (a + b) + c equals a + (b + c). True for real numbers, not for floating-point numbers. |
| Reduction order | The order in which many numbers are added up. Different kernels add in different orders. |
| Accumulate | Keep a running sum. Kernels usually accumulate in FP32 even when inputs are BF16. |
| Nondeterminism | Getting different outputs from the same input. |
| Batch invariance | A request’s arithmetic being done in exactly the same order whatever else is in the batch. |
| Logit | The model’s raw score for one vocabulary token, before softmax (12.o). |
| KL divergence | A measure of how different two probability distributions are; 0 means identical. |
1. What is it?#
The practical discipline of keeping an inference system numerically sound while running it in the lowest precision you can get away with, with fused kernels, across many GPUs and at whatever batch size traffic happens to produce.
The uncomfortable fact first: a production inference server gives slightly different numbers from the reference implementation, and slightly different numbers from itself depending on what else it is doing. That is normal. The engineering task is to bound the difference, explain it, and remove it only where you must.
Facts checked on 12 November 2026.
2. Why does it exist?#
Because floating-point addition is not associative:
(0.1 + 0.2) + 0.3 = 0.6000000000000001
0.1 + (0.2 + 0.3) = 0.6And because almost everything in a GPU inference stack changes the order of additions: the batch size (a different kernel or split strategy), chunked prefill (different chunk boundaries), the tensor-parallel degree (partial sums combined across GPUs), fusion (different intermediate rounding), and library versions.
So the same prompt, on the same hardware, can produce different text depending on who else’s request shared its batch. Users notice, and you need to be able to explain it.
3. Simple analogy#
Rounding a long restaurant bill. Add the items in a different order, rounding to the cent at each step, and you can end up a cent apart. On its own that does not matter. But if the cent decides something (“is the total over the free-delivery threshold?”), the outcome flips.
In an LLM, choosing the next token is the threshold. A tiny difference in a logit almost never matters, until two candidate tokens are nearly tied. Then it changes the word, and every word after it.
4. Tiny example: one input, two summation orders#
The program computes 4,096 dot products of length 4,096 (a small “LM head”) twice: once adding left to right with one accumulator, once with eight accumulators combined at the end, the way a kernel that splits its work for a bigger batch would. Then it rounds both to BF16, as a kernel does when it stores its output.
// order.go — the same dot products, summed in two different orders, as a GPU does
// when a request runs alone or inside a bigger batch.
package main
import (
"fmt"
"math"
"math/rand"
)
const d = 4096
// One accumulator, left to right.
func dotSequential(x, w []float32) (s float32) {
for i := range x {
s += x[i] * w[i]
}
return s
}
// Eight accumulators combined at the end, like a kernel that splits the work.
func dotLanes(x, w []float32) float32 {
var lane [8]float32
for i := range x {
lane[i%8] += x[i] * w[i]
}
return ((lane[0] + lane[1]) + (lane[2] + lane[3])) + ((lane[4] + lane[5]) + (lane[6] + lane[7]))
}
// bf16 rounds to the nearest BF16 value, as a kernel does when it writes its BF16 output.
func bf16(x float32) float32 {
b := math.Float32bits(x)
b += 0x7FFF + (b>>16)&1
return math.Float32frombits(b &^ 0xFFFF)
}
func main() {
rng := rand.New(rand.NewSource(0))
x := make([]float32, d)
for i := range x {
x[i] = float32(rng.NormFloat64())
}
alone, batched := make([]float32, d), make([]float32, d) // d output values ("logits")
var maxDiff float32
differ, differBF16 := 0, 0
for row := 0; row < d; row++ {
w := make([]float32, d)
for i := range w {
w[i] = float32(rng.NormFloat64())
}
alone[row], batched[row] = dotSequential(x, w), dotLanes(x, w)
diff := alone[row] - batched[row]
maxDiff = max(maxDiff, diff, -diff)
if diff != 0 {
differ++
}
if bf16(alone[row]) != bf16(batched[row]) {
differBF16++
}
}
fmt.Printf("outputs that differ in FP32 : %d of %d (max diff %.1e)\n", differ, d, maxDiff)
fmt.Printf("outputs that differ after BF16 store: %d of %d\n", differBF16, d)
top2 := func(v []float32) (best int, gap float32) {
first, second := float32(math.Inf(-1)), float32(math.Inf(-1))
for i, f := range v {
if f > first {
first, second, best = f, first, i
} else if f > second {
second = f
}
}
return best, first - second
}
a, gap := top2(alone)
b, _ := top2(batched)
fmt.Printf("argmax alone %d, batched %d; gap between the top two outputs %.2f\n", a, b, gap)
}Output:
outputs that differ in FP32 : 4000 of 4096 (max diff 5.0e-04)
outputs that differ after BF16 store: 2 of 4096
argmax alone 2816, batched 2816; gap between the top two outputs 3.59Three things to read from it:
- Almost every FP32 result differs, by up to 5e-4. Nothing changed but the order of the additions.
- After rounding to BF16 almost all of them agree again, because the differences are smaller than one BF16 step. But 2 of 4,096 land on opposite sides of a rounding boundary and now differ by a whole BF16 step, about 0.4% of their value. Those differences enter the next layer, and the next, and grow.
- The chosen token is the same here because the top two outputs are 3.6 apart. When they are within the accumulated error of each other, it is not.
5. Technical explanation#
Where nondeterminism comes from#
Source What changes When
Batch composition split strategy of GEMMs, attention, norms every step in a busy server
Chunked prefill, prefix caching where a prompt is split, or whether its depends on load and cache state
KV was computed now or earlier
Tensor-parallel degree how partial sums are combined (14.c) per deployment
Kernel, library, driver, GPU the kernels themselves per upgrade
Compiler and fusion settings intermediate rounding (11.h, 11.i) per configuration
Atomic adds in some kernels order of updates between thread blocks run to run (rare in forward passes)
Sampling the random draw (12.o) by design; fixed by a seedA 2025 study by Thinking Machines Lab made an important correction to the usual explanation. Run-to-run nondeterminism is often blamed on GPU atomics and thread scheduling, but the forward pass of a typical LLM uses no atomic adds and, given the exact same batch, is deterministic run to run. The dominant cause in a real server is the first row: kernels are not batch invariant. A matmul, attention or norm kernel chooses a different way to split its reduction for 3 tokens than for 300, so the same request gets a different summation order depending on what else is in the step.
Batch-invariant serving, when you need it#
Batch-invariant kernels fix one reduction strategy (for example a fixed split size in attention) regardless of batch size. Both major open engines ship a mode for it:
vLLM VLLM_BATCH_INVARIANT=1 validated on H100/H200 and Blackwell for listed models
SGLang --enable-deterministic-inference with the FlashInfer, FA3 or Triton attention backendAdd a per-request seed for sampling and the same request gives the same output however the server is loaded. The cost is throughput, because the fixed strategies are slower than the adaptive ones; reports range from modest to more than 50% depending on the model and kernels. Use it where reproducibility is the product: evaluations, debugging a user report, and reinforcement learning, where the sampler must match the trainer bit for bit (12.o).
The stability checklist#
✓ Softmax with the maximum subtracted first, computed in FP32 (10.g)
✓ Attention scores accumulated in FP32
✓ RMSNorm and LayerNorm reductions in FP32 (11.e)
✓ GEMMs accumulating in FP32, whatever the input format
✓ Logits converted to FP32 before temperature and sampling
✓ Masks applied by the kernel, not with large finite negatives (11.f)
✓ eps values and norm details matching the reference (11.e)
✓ RoPE sin/cos tables computed in FP32
✓ Quantization scales stored in sufficient precision (13.b)Every line is a bug someone has shipped.
Why BF16 replaced FP16#
FP16 has more precision than BF16 but a far smaller range: its largest value is 65,504 (10.k). Transformer activations are not tame. The residual stream grows with depth, and a few hidden channels carry “massive activations” hundreds or thousands of times larger than the rest. Inside the MLP, the product of the gate and up projections can be larger still. In FP16, an unlucky input at a late layer overflows to infinity and the output becomes NaN. BF16 has the same range as FP32, so it does not have this failure. That is why nearly every open model since 2023 ships in BF16, and why running such a model in FP16 is a risk unless it was validated that way.
Validating a precision change#
LEVEL 1 Numerical
max and mean difference of logits against a BF16 reference
KL divergence between output distributions; top-1 token agreement
LEVEL 2 Task
perplexity on held-out text (necessary, far from sufficient)
benchmarks that match YOUR workload
LEVEL 3 Behaviour
long generations (hundreds to thousands of tokens), where errors compound
reasoning traces, instruction following, tool calls
structured output validity (JSON schema)
refusal and safety behaviour, which quantization can shift
LEVEL 4 Production
A/B test on real traffic with human or model-graded evaluationLevel 1 alone is not enough, and it is where many teams stop. A model can show tiny logit differences and still be measurably worse at multi-step reasoning, because small errors compound over thousands of generated tokens. 13.b applies this ladder to quantization decisions.
6. Under the hood: why the order changes with batch size#
At M = 1 a GEMM may run as a GEMV-style or split-K kernel (11.c) in which several thread blocks each sum part of the K dimension and the partial sums are added at the end. At M = 64 a tiled kernel gives each output tile to one block, which walks the whole K dimension itself. Different tree of additions, different rounding.
Attention does the same along the key dimension: a decode kernel splits long contexts into pieces (split-KV, 11.f) and the number of pieces depends on how many requests are in the step and how many SMs are free. Norm kernels may switch strategy with the number of rows.
None of these choices is wrong. Each is the fastest for its shape. Batch invariance means giving up that per-shape choice.
7. Performance implications#
- FP32 reductions and softmax cost almost nothing next to the GEMMs and buy correctness. Always do them.
- Batch invariance costs throughput. Pay it only where reproducibility is required.
- Lower precision is the biggest single lever on decode speed (fewer bytes per weight, 13.b), which is exactly why the validation ladder matters.
8. Production implications#
- Record the exact numerical configuration with every deployment: weight and KV formats, quantization method, tensor-parallel degree, attention backend, compile settings, library and driver versions.
- Do not change precision without Level 3 validation.
- Have a written answer ready for “why did the same prompt give a different answer?” before someone files it as a bug.
- Keep a reproducibility mode for investigations: batch-invariant kernels, a fixed seed, a fixed tensor-parallel degree, prefix caching off if needed.
- Watch for NaN and infinity in production. A cheap check on logits catches numerical failure before users do.
- Evaluate the serving configuration, not the reference. Run quality checks in CI against the same engine, kernels and precision you deploy.
9. Common mistakes#
- Running a BF16-trained model in FP16 without validation. Overflow at depth.
- Validating with perplexity only. It is insensitive to what users notice.
- Testing only short generations. Compounding errors show up late.
- Trusting a general benchmark for a quantized model on your specific task.
- Promising determinism without batch-invariant kernels behind it.
- Accumulating in BF16 or FP16 in a custom kernel.
- Blaming atomics for every difference, when batch composition is the usual cause.
10. Hands-on exercise#
- Run
order.go. Change the second order to 32 lanes, then to a pairwise tree. Which order is closest to a float64 reference? - Send the same prompt with temperature 0 to a server 20 times, once alone and once while a load generator keeps it busy. How often does the output differ? Repeat with batch invariance on.
- Build a validation harness that, for two configurations, reports maximum logit difference, KL divergence, top-1 agreement, perplexity on held-out text and side-by-side generations for 20 prompts. Keep it: you will use it for every precision decision.
- Run a model in FP16 and in BF16 on long inputs and record the largest absolute activation per layer. How close does FP16 get to 65,504?
- Generate 1,000 tokens in two configurations from the same prompt and seed, for 50 prompts. Plot a histogram of the position where they first differ.
11. Interview questions#
- Why can the same prompt produce different outputs on the same hardware?
- What is batch invariance, and why do most kernels lack it?
- Is GPU atomics the main source of nondeterminism in LLM inference? Explain.
- Why did BF16 replace FP16 for transformer weights and activations?
- How would you validate a precision or quantization change before deploying it?
- Why is perplexity insufficient on its own?
- When is it worth paying for deterministic inference?
12. Further reading#
Checked on 12 November 2026.
- He and Thinking Machines Lab, “Defeating Nondeterminism in LLM Inference” (2025)
- vLLM batch invariance (v0.32.0 docs)
- SGLang deterministic inference and the LMSYS blog post (September 2025)
- Sun et al., “Massive Activations in Large Language Models” (arXiv 2402.17762)
- Goldberg, “What Every Computer Scientist Should Know About Floating-Point Arithmetic”
- Micikevicius et al., “Mixed Precision Training” (arXiv 1710.03740)
- PyTorch reproducibility notes