The Batch Changed. The Answer Shouldn't.
How Trainium and bfloat16 make kernel outputs reproducible (and why float32 can't always keep the same promise)
The Industry Problem
Have you ever sent an identical message, back to back to your favorite AI agent or LLM API and received different outputs each time? If so, you have experienced 1 of 2 scenarios, most likely both.
1. Temperature / top_p sampling
Due to the stochastic nature of sampling, temperature / top_p settings greater than 0 / 1 respectively, influence the log probabilities of logits taken from the last layer of the model's forward pass. These settings can change the likelihood that a next token will be selected and therefore affect run to run output
2. Batch Variance
When you send an inference request, a serving engine is most certainly batching it along with a random number of others. This changes the shape of input given to the LLM. This isn't inherently an issue in and of itself, however as we will discuss, when kernel design is dependent on input shape (eg splitK GEMM etc), the reduction strategy changes within the kernel, thus causing accumulation orders to potentially change and finally the result across runs to vary when input shapes differ.
Batch variance compounds in ways that aren't obvious until you measure them. Thinking Machines ran 1000 completions of the same prompt at temperature 0 and got 80 unique outputs; same model, same prompt, same temperature, different batch load each time.
The training implications are just as real. When the sampling policy and training policy produce different logprobs for the same input, on-policy RL silently becomes off-policy. Without correction it can cause reward collapse; with correction you're burning compute to paper over a problem that shouldn't exist. True on-policy training, where KL divergence between sampler and trainer stays flat at zero, requires the numerics to match exactly at the kernel level.
Push the precision down to FP8 and the stakes get higher. The vLLM team found that at long contexts, imprecise accumulation in the Tensor Cores caused attention accuracy to drop severely on a needle-in-a-haystack task, fixed only by flushing partial results into a true FP32 register. At lower mantissa precision, accumulation order sensitivity stops causing subtle drift and starts causing catastrophic failure (more on why later).
DeepSeek-V4 lists batch-invariant and deterministic kernel libraries as first-class infrastructure alongside model architecture changes, noting that standard libraries cannot achieve batch invariance and that common small-batch optimizations break it outright.
The pattern is consistent: as models scale, as precision decreases, and as serving systems grow more dynamic, batch variance stops being a theoretical concern and starts being a measurable regression.
In this blog I'll be discussing batch variance specifically, and how AWS Trainium Accelerator Chips and Neuron Kernel Interface (NKI) can eliminate it at the kernel level.
Scope & Disclaimer
This work focuses on the bottom of the stack, NKI kernels, the smallest measurable unit of model computation. Not the serving engine, not collectives, not the scheduler, not sampling. Kernels.
It doesn't claim to solve every edge case of non-determinism in LLM serving. It is a starting point, three NKI ISA kernels (MatMul, RMSNorm, Attention) that are batch-invariant by design on Trainium hardware. Fixed reduction tile sizes (pmax, fmax) mean the accumulation strategy never varies with input shape. bfloat16 adds an additional layer: even under artificial tile variation, the coarse grid absorbs the difference.
The goal is to demonstrate that invariant kernel design is achievable on NeuronCore without performance regression, and that it can be the default rather than an afterthought.
Background
Now that we've established some cognitive reasoning on what batch variance is, and why it's proper handling matters, I'll begin unpacking my testing and implementation with a few definitions.
- Floating point non-associativity:
(a+b)+c != a+(b+c)
- Run-to-run invariance: same inputs, same tile config == bitwise identical output
- Tile invariance: same inputs, different tile size == bitwise identical output
- Batch invariance: output for row i is identical regardless of batch size, neighbor values, or row position
- Continuous batching: a serving engine technique where requests of varying lengths are dynamically packed into a single forward pass as slots open up, rather than waiting to fill a fixed batch. This is the mechanism by which batch size becomes a runtime variable and the trigger for the non-determinism described above.
The Kernels and the Hardware
When I began this experiment, my intention was to follow the Thinking Machines blog linked above as closely as possible. That meant I needed three separate kernels:
- RMSNorm
- Matmul
- Attention
The reason for these three is because the first two perform some sort of reduction (matmul reduces over the K dimension), and the third makes use of them both. The first two are designed to accept a deterministic flag as a parameter. When this is false, the K_TILE size is changed, so that the two calls produce different results for float32 inputs. This is great for showcasing the mechanism of invariant kernel design, but I wanted to use something production ready for the attention testing, specifically the attention_cte kernel from the official NKI Library maintained by AWS Neuron.
As for the hardware specifics, Trainium makes use of its tensor engine to perform matrix multiplications. Each tiled matrix multiplication accumulates onto a float32 partial sum (PSUM) buffer, overwriting the previous sum. RMSNorm uses the Vector Engine for its element-wise operations, but its sum-of-squares reduction similarly accumulates into the PSUM.
The Mechanism
When I first began testing, I compared run-to-run outputs to ensure they would never change. In the Thinking Machines blog referenced earlier, they called out how PyTorch's dispatcher can change the order of operations and cause non-determinism. Taking direct control over the hardware with NKI, I did not have this issue.
Next, I began to run two separate matmuls, using the same input, only varying tile sizes via the deterministic flag. Starting in float32, I immediately saw the difference I expected. Floating point non-associativity was rearing its head.
The surprising part, which took me some time to understand: when I switched the inputs to bfloat16, the output was invariant to the tile size change. It wasn't until I found this article on quantization by Sam Rose, with incredible visuals, that I began to understand why.
I'll use a couple of those visuals to explain. Below, various precisions approximate a sine wave. As precision decreases, the representation becomes coarser, less like a wave, more like a Mayan temple.

Now, focusing in at 200x, we can see what happened exactly with my linspace populated input tensors, were matmul'd, sent to PSUM where accumulation happens in float32, and then they are moved back to SBUF as bfloat16.
Zooming in at 200x, we can see what happened with my linspace inputs. Once the bfloat16 multiplication was performed, the result was already rounded to a coarser precision before entering the float32 PSUM. With linspace values, the products never left the flat top of the yellow line. They collapsed into the same bucket regardless of tiling strategy, giving diff=0.0 every time. Had the input values been larger, the likelihood of crossing a bfloat16 quantization bucket boundary would increase, producing exactly the non-determinism I expected to see in the first place.

Now for the proof.
Empirical Evidence
All comparisons performed viaview(int16)— no tolerances, no atol, no rtol. Bitwise identical or it fails.
Run-to-Run Determinism
Before testing tile invariance, I first confirmed that the kernels are deterministic across repeated calls with the same inputs and tile configuration. 1000 runs, same kernel, same inputs, same tile size. diff=0.0 across all runs for both bfloat16 and float32.
MatMul: Tile Invariance
Same inputs, two calls — K_TILE=128 vs K_TILE=64.
- bfloat16: same tile, same result ✓ / different tile, same result ✓
- float32: same tile, same result ✓ / different tile, 1.14e-04 ✗
The bfloat16 result is the finding. The float32 result is the control, it confirms that the two tile strategies genuinely produce different accumulation orders, and that bfloat16 is absorbing that difference, not hiding it. The image below, created by inspecting the PSUM values using the new NKI simulator, should make this easily observable.
The green rows are checkpoints where both tile strategies have processed the same total number of K elements, and the PSUM value is bitwise identical at every one of them. The orange rows are intermediate steps unique to the smaller tile size, where it is still working its way through K elements that the larger tile already processed in one shot. By the time K_TILE=64 catches up to each K_TILE=128 checkpoint, the running sum has landed in exactly the same place, because the individual products were already rounded to the same bfloat16 values before they ever entered the accumulator.

The float32 PSUM value at every shared K checkpoint is bitwise identical between K_TILE=128 and K_TILE=64 for bfloat16 (top). For float32 (bottom), divergence appears at the first shared checkpoint and carries forward unchanged: 1.14e-04 at K=128, still 1.14e-04 at K=512.
RMSNorm: Tile Invariance
RMSNorm reduces over the hidden dimension rather than K, but the accumulation path is the same — products enter a float32 PSUM via the Vector Engine. Same test, same flag, same result.
- bfloat16: same tile, same result ✓ / different tile, same result ✓
- float32: same tile, same result ✓ / different tile, 2.4e-07 ✗
The float32 diff is smaller here than in matmul — the hidden dimension reduction is shorter, less accumulated error. The bfloat16 result is the same: zero.
Attention: Row Independence
For attention I used attention_cte from the official NKI Library rather than the toy kernel. The test is different here, instead of comparing tile sizes, I'm testing row independence directly:
attention_cte(Q, K, V)[i] == attention_cte(Q[i:i+1], K, V)[0]The same query row processed alone versus co-packed with other sequences should produce bitwise identical output. Tested across 3 random seeds with causal masking on both TRN hardware and the NKI CPU simulator. All of which were bitwise identical
This holds through the full flash attention implementation, sectioning, causal masking, softmax numerics, and all. Not a toy kernel result.
Continuous Batching: Batch Position Independence
The previous test held the KV context fixed and varied only which query rows were present. This test is harder, the full KV context changes too, simulating what actually happens when a serving engine packs multiple requests into one forward pass. Request A is run alone, then co-packed alongside random neighbor sequences under a block-diagonal attention mask. The output for Request A must be bitwise identical regardless of what else is in the batch.
attn_cte(Q_only, K_only, V_only) = attn_cte(Q_packed, K_packed, V_packed)[:len(Q_only)]Tested across 3 random neighbor seeds, bfloat16, causal mask with sequence packing bounds.
The neighbors are random; different shape, different values, different position in the batch every time. The output for Request A does not move. This is the serving guarantee: what the model computes for your request is independent of who else is in the batch.
The Broader Picture
Earlier I mentioned that Thinking Machines, vLLM, and DeepSeek-V4 were all wrestling with variations of the same problem. Now that the mechanism is clear, it's worth revisiting why.
Thinking Machines framed this as a GPU dispatch problem; when batch size changes, a shape-dependent dispatcher selects a different kernel (Split-K vs data-parallel), changing the reduction order. Their fix is a batch-invariant kernel library that accepts a ~20% performance cost to hold the tile strategy fixed. That cost exists because on GPU, fixing the tile strategy is a choice you have to make explicitly and defend with performance tradeoffs. On NeuronCore, pmax and fmax are hardware constants, the tile strategy was never variable to begin with. ( source )
The vLLM FP8 work shows where this leads at lower precision. FP8 has a 3-bit mantissa, roughly 8 values per power-of-2 interval. At 128k context the accumulation error crossed bucket boundaries catastrophically, the same cliff edge described in the staircase section, but at a scale where it wiped out 78 percentage points of accuracy. Their fix, flushing partial results into a true FP32 register, is in software what NeuronCore's PSUM buffer does in hardware. Blackwell fixes it in silicon on the next generation. ( source )
DeepSeek-V4 ships batch-invariant and deterministic kernel libraries as first-class infrastructure listed alongside MoE kernel fusion, TileLang, and FP4 QAT. The fact that a frontier lab treats this as a core infrastructure problem rather than an edge case signals where the industry is heading. The precision reduction trend makes it harder going forward, not easier. FP4 QAT means even fewer mantissa bits, even more potential for bucket-crossing. ( source )
The common thread: everyone is patching in software or hardware what bfloat16 on NeuronCore gets structurally for free within the right input distribution.
Let's put a bow on it
In conclusion, invariance for the scope of my testing comes down to kernel design. Tile sizes cannot vary dynamically if you want a determinism guarantee. Even with bfloat16 collapsing accumulation differences into the same quantization bucket, that still carries the constraint that input values stay within a distribution low enough to avoid crossing a bucket boundary. The only hard guarantee is fixed tile sizing.
The encouraging part is that NKI and Trainium hardware seem to push you toward that by default. Dynamic tiling doesn't appear to be present in the advised kernel design patterns, nor in the nki-library samples maintained by the AWS Neuron team. Invariant kernel design appears to be an implied way of doing business, not a special case you have to opt into.
References
- Thinking Machines — Defeating Nondeterminism in LLM Inference: https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/
- vLLM — FP8 KV-Cache and Attention Quantization: https://vllm.ai/blog/2026-04-22-fp8-kvcache
- DeepSeek-V4 Technical Report: https://huggingface.co/deepseek-ai/DeepSeek-V4-Pro/blob/main/DeepSeek\_V4.pdf
- ngrok — Quantization from the Ground Up: https://ngrok.com/blog/quantization
- jlonge4/nki-batch-invariance: https://github.com/jlonge4/nki-batch-invariance
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article