Pidoku

Nondeterminism and Batch Invariance

Module 28 Lesson 28.c 1h 15m Difficulty 4/5

Prerequisites 11.f, 11.k, 12.j, 12.m, 28.a


Before you start: words you need#

WordPlain meaning
DeterministicThe same input always produces the same output, bit for bit.
Batch invariantA request’s arithmetic does not depend on which other requests share its batch (11.k).
Split-KVA decode attention kernel that cuts a long context into pieces, works on them in parallel and merges the results (also called flash-decoding, 11.f).
ReductionCombining many numbers into one, such as a sum or a maximum. Its order decides the rounding.
All-reduceSumming partial results across GPUs so each GPU gets the total (9.f, 14.c).
On-policyIn reinforcement learning, training on samples drawn from exactly the model being trained.
SeedA number that fixes the sequence a random number generator produces.

1. What is it?#

11.k established the core fact: a server’s forward pass is usually repeatable for an identical batch, and the main reason the same request gives different results in a busy server is that kernels are not batch invariant. This lesson goes from that fact to an engineering practice:

  • the levels of determinism you can offer, and what each requires;
  • how batch-invariant kernels are built, operation by operation;
  • every other place in a server where order or randomness leaks in (sampling, chunking, prefix caching, preemption, speculative decoding, tensor and expert parallelism);
  • the deterministic modes of vLLM and SGLang as they stand, how to test them, and what they cost.

Facts checked on 13 November 2026.


2. Why does it matter?#

Thinking Machines Lab measured the problem directly (September 2025). They sent the prompt “Tell me about Richard Feynman” to Qwen3-235B-A22B-Instruct-2507 1,000 times at temperature 0 on vLLM. They got 80 different completions. All 1,000 agreed for the first 102 tokens; at token 103, 992 continued “Queens, New York” and 8 “New York City”. With batch-invariant kernels, all 1,000 completions were identical.

Three groups need that second result:

  • Reinforcement learning. The trainer computes the probability of each sampled token and assumes the sampler used the same model. If the inference engine’s numbers differ from the trainer’s, “on-policy” training is silently off-policy. In the same post, an RL run without correction collapsed; with importance weighting the KL divergence between sampler and trainer stayed around 0.001; with bitwise-identical sampler and trainer it stayed at exactly 0 (27.e).
  • Evaluation. A benchmark that changes by a point when re-run cannot measure a one-point change.
  • Debugging. “This prompt gave a bad answer yesterday” is only investigable if you can make the server do it again.

3. Simple analogy#

Counting votes in a big election. Each polling station counts its ballots, then the region adds the stations’ totals. If the stations are reorganized (two small ones merged, one large one split) the grand total is the same in exact arithmetic. But if every subtotal is rounded to the nearest hundred before it is passed up, the grand total depends on how the stations were drawn.

Batch invariance says: draw the stations the same way for this voter’s ballot every time, no matter how many other voters turn up.


4. Tiny example: one request, six batch sizes#

A decode step with a split-KV kernel. Strategy A, the usual heuristic, picks the number of splits so that the whole batch fills the 132 SMs of an H100: a lone request is cut into 132 pieces, a request in a batch of 64 into 2. Strategy B fixes the length of a split at 256 keys, the approach Thinking Machines used. The merge is the standard log-sum-exp rescaling every split-KV kernel uses.

Go
// splitkv.go — one decode request's attention output, computed the way a split-KV
// (flash-decoding) kernel does, while the rest of the batch changes size.
package main

import (
	"fmt"
	"math"
	"math/rand"
)

const sms = 132 // streaming multiprocessors on an H100 SXM

// partial is what one split returns: running max, sum of exponentials, weighted value sum.
type partial struct{ m, l, o float32 }

func attendSplit(s, v []float32) partial {
	p := partial{m: float32(math.Inf(-1))}
	for _, x := range s {
		p.m = max(p.m, x)
	}
	for i, x := range s {
		e := float32(math.Exp(float64(x - p.m)))
		p.l += e
		p.o += e * v[i]
	}
	return p
}

// merge combines partial results with the log-sum-exp rescaling every split-KV kernel uses.
func merge(a, b partial) partial {
	m := max(a.m, b.m)
	ea, eb := float32(math.Exp(float64(a.m-m))), float32(math.Exp(float64(b.m-m)))
	return partial{m, a.l*ea + b.l*eb, a.o*ea + b.o*eb}
}

func attend(s, v []float32, splitLen int) float32 {
	acc := partial{m: float32(math.Inf(-1))}
	for lo := 0; lo < len(s); lo += splitLen {
		hi := min(lo+splitLen, len(s))
		acc = merge(acc, attendSplit(s[lo:hi], v[lo:hi]))
	}
	return acc.o / acc.l
}

// Strategy A (the usual heuristic): choose the NUMBER of splits so the whole batch fills
// the GPU, so the split length for one request depends on how many others share the step.
func fixedCount(s, v []float32, batch int) float32 {
	nSplits := max(1, sms/batch)
	return attend(s, v, (len(s)+nSplits-1)/nSplits)
}

// Strategy B (batch invariant): fix the split LENGTH, whatever the batch.
func fixedSize(s, v []float32, _ int) float32 { return attend(s, v, 256) }

func main() {
	rng := rand.New(rand.NewSource(7))
	const ctx = 1000
	s, v := make([]float32, ctx), make([]float32, ctx)
	for i := range s {
		s[i], v[i] = float32(rng.NormFloat64()*3), float32(rng.NormFloat64())
	}
	seenA, seenB := map[uint32]bool{}, map[uint32]bool{}
	fmt.Println("batch  splits(A)  fixed split count (A)  fixed split size 256 (B)")
	for _, batch := range []int{1, 3, 8, 24, 64, 132} {
		a, b := fixedCount(s, v, batch), fixedSize(s, v, batch)
		seenA[math.Float32bits(a)], seenB[math.Float32bits(b)] = true, true
		fmt.Printf("%5d  %9d  %20.9f  %24.9f\n", batch, max(1, sms/batch), a, b)
	}
	fmt.Printf("distinct bit patterns for the same request: A=%d, B=%d\n", len(seenA), len(seenB))
}

Output:

batch  splits(A)  fixed split count (A)  fixed split size 256 (B)
    1        132           0.169796467               0.169796407
    3         44           0.169796407               0.169796407
    8         16           0.169796363               0.169796407
   24          5           0.169796422               0.169796407
   64          2           0.169796348               0.169796407
  132          1           0.169796348               0.169796407
distinct bit patterns for the same request: A=5, B=1

Strategy A gives five different answers to one request; B gives one. The differences are in the seventh significant digit, far below anything a human would notice, and, as 28.a showed, still enough to flip a near-tie and change the rest of the text. With a 1,000-token context, B uses splits of 256, 256, 256 and 232, the same example as the Thinking Machines post.

Note what B gives up: a lone request uses only 4 splits, so at batch 1 it keeps 4 of the 132 SMs busy for the attention step. That is where batch invariance costs speed.


5. Technical explanation#

Levels of determinism#

LEVEL  NAME                          SAME OUTPUT WHEN...                          WHAT IT TAKES
D1     Run-to-run                    the exact same batch is replayed              no atomics or races in forward kernels
                                                                                   (true for most LLM forward passes)
D2     Batch invariant               other requests, chunking and prefix-cache    batch-invariant kernels + seeded sampling
                                     hits differ                                   + consistent KV layout
D3     Parallelism invariant         tensor-parallel size differs (TP=1 vs TP=8)   TP-invariant reductions (research, see below)
D4     Cross-version / cross-GPU     engine, library or GPU differs               not offered by anyone; pin everything instead

The engines’ “deterministic” modes give D2, and D2 only within one fixed configuration. Always say which level you mean.

How each operation is made batch invariant#

The three reductions in a transformer forward pass, following Thinking Machines:

OPERATION   WHY IT VARIES WITH BATCH                     BATCH-INVARIANT STRATEGY
RMSNorm     small batches split each row's reduction     one row per core (data parallel); accept slower
            across cores to keep the GPU busy            small batches
Matmul      split-K for small M; tile shape and          one kernel configuration for all shapes, no split-K;
            kernel chosen per shape                      Thinking Machines report ~20% below cuBLAS
Attention   split-KV count chosen per batch (section 4); fixed split SIZE, not count; and write the new
            prefill and decode use different kernels;    tokens into the KV cache before attention so
            chunked prefill splits the sequence          prefill, decode and chunked prefill see the same
                                                         layout and the same reduction order

The attention row hides the hardest part. Batch invariance must also hold across time: a token’s KV computed during prefill must equal what decode would have computed, and a prompt processed in chunks (12.k) must give the same result as one processed whole, or prefix caching (12.m) and preemption with recompute become sources of difference. That is what the “same layout before attention” rule buys.

Everything else in the step must be invariant too: the sampler (logits to FP32, a top-k and top-p that do not depend on batch-level sorting), the logits processors, any fused kernel that reduces.

Sources beyond the kernels#

SOURCE                     WHY IT BREAKS D2                                      HANDLING
Sampling randomness        a shared generator advances with every request        per-request seed; position-based
                           in the batch                                          noise (vLLM Model Runner V2, 18.e)
Chunked prefill            chunk boundaries depend on load                       invariant attention + KV layout
Prefix caching             KV came from an earlier request's prefill             same; SGLang's radix cache is
                                                                                 supported with FA3 and Triton only
Preemption and recompute   KV recomputed by prefill after being made by decode   same
Speculative decoding       verification runs k+1 tokens at once: a new shape     invariant kernels must cover it; test
MoE routing                expert groups have batch-dependent sizes, so grouped  invariant grouped GEMM; deterministic
                           GEMM shapes change; top-k gating can tie               tie-breaking
Tensor parallelism         all-reduce algorithm and order change with size       fixed-order all-reduce (below)
Atomics                    scatter-add, some split-K and MoE combine kernels     replace with fixed-order reductions

Tensor parallelism#

An all-reduce adds partial sums from several GPUs; ring, tree and one-shot algorithms add in different orders, and libraries pick the algorithm by message size, which depends on batch size. vLLM’s batch-invariant mode (v0.32.0) keeps its custom all-reduce with a fixed reduction order and disables the FlashInfer, AITER and QuickReduce all-reduce paths. Its documentation lists one gap: tensors whose size is not a multiple of 16 bytes can still switch between NCCL and the custom all-reduce with batch size.

Changing the TP degree is a different problem (D3): TP=1 and TP=8 split a matmul’s reduction differently by construction. That matters for RL, where training often runs without tensor parallelism and rollout with it. Zhang et al. (arXiv 2511.17826, Nov 2025, revised May 2026) propose tree-based invariant kernels that align the reduction order inside and across GPUs and report bitwise-identical results across TP sizes and between vLLM and an FSDP trainer. Treat it as research: it is not a default engine mode.

The engines’ modes (checked 13 November 2026)#

vLLM v0.32.0   VLLM_BATCH_INVARIANT=1  (documented as beta)
  hardware     NVIDIA compute capability ≥ 8.0; AMD Instinct gfx90a, gfx942, gfx950;
               Intel XPU with the Triton attention backend
  what it does deterministic attention and other kernels; BF16 unquantized linear layers
               run without torch.compile, using "breakable" CUDA graphs on GPUs with tuned
               matmul tables (opt out: VLLM_USE_BREAKABLE_CUDAGRAPH=0); fixed-order custom
               all-reduce; LoRA shrink split into 8 fixed K chunks instead of atomics
  validated    a listed set of models including DeepSeek-V3/R1, Qwen3 dense and MoE,
               Llama 3.1/3.2, gpt-oss-20b/120b; others "may work but are not validated"
  sampling     pass seed=... per request

SGLang         --enable-deterministic-inference
  backends     --attention-backend fa3 | flashinfer | triton (only these three)
  features     CUDA graphs and chunked prefill with all three; radix (prefix) cache with
               fa3 and triton, not flashinfer; temperature > 0 with a per-request
               sampling_seed in sampling_params (default 42 if omitted)
  self-test    python3 -m sglang.test.test_deterministic --test-mode single --n-trials 50
               (also --test-mode prefix, radix_cache); expect "Unique samples: 1"

Two cautions. The modes are young and their coverage changes release to release: read the current documentation for your version, and treat “validated models” lists as exactly that. And determinism is per configuration: the same model on a different GPU type, engine version or tensor-parallel degree is allowed to give different (but each repeatable) results.

Testing determinism yourself#

Do not trust a flag; test it the way SGLang’s self-test does, under the conditions that break it:

SINGLE   the same prompt N times, sequentially                           → D1
MIXED    the same prompt N times, each in a batch of random other        → D2 for batch composition
         prompts of random lengths
PREFIX   prompts sharing long prefixes, in varied orders, cache warm     → D2 for chunking and prefix caching
         and cold
PRESSURE fill the KV cache until requests are preempted and recomputed   → D2 for preemption
COMPARE  token ids AND returned logprobs, bitwise                        → a matching text can hide differing numbers
PASS     exactly 1 unique output per prompt

Run it on every engine upgrade, in CI, on each GPU type you use.


6. Under the hood: why “temperature 0” is not enough#

Greedy decoding removes sampling randomness, so people expect it to be deterministic. It removes only one source. The logits are still computed by kernels whose reduction order depends on the batch, so near-ties still flip (Feynman’s birthplace above was a temperature-0 run).

Conversely, sampling at temperature 0.7 can be fully deterministic: with a per-request seed and batch-invariant logits, the same seed draws the same uniform numbers at the same positions and applies them to bit-identical probabilities. “Deterministic” is a property of the whole pipeline (logits plus sampler plus seed), not of the temperature.

The same reasoning explains why bitwise-identical RL needs more than an inference flag. The trainer must compute the same numbers as the sampler, so its forward pass must use the same batch-invariant kernels and the same reduction order (and, for different parallelism, D3 kernels). The SGLang team reported reproducible GRPO training in the slime framework only after also fixing the trainer side: FlashAttention 2 instead of 3, Megatron’s deterministic mode, specific NCCL, cuBLAS and Transformer Engine settings, and torch.use_deterministic_algorithms(True).


7. Performance implications#

Batch invariance removes per-shape choices, so it is slowest exactly where those choices helped most: small batches (few splits, idle SMs) and decode.

SOURCE                                  WORKLOAD                         RESULT
Thinking Machines (Sep 2025)            Qwen3-8B, 1 GPU, 1,000 seqs      default vLLM 26 s; first deterministic
                                        of 90–110 tokens                 version 55 s; with better attention 42 s
LMSYS / SGLang (Sep 2025)               Qwen3-8B, H200, RL-style         average slowdown 34% (FlashInfer, FA3);
                                        workloads                        individual cases 24–55%

Both are the projects’ own measurements on their own workloads, and both predate a year of optimization work; measure your model on your engine version before deciding. Two practical consequences:

  • Do not turn it on fleet-wide by default. Run a separate deterministic pool or deployment for the traffic that needs it (evaluation, RL rollouts, reproduction of reported issues).
  • Measure the cost at your batch sizes. The slowdown at batch 1 and at batch 256 are different numbers.

8. Production implications#

  • Offer determinism as a mode, with a contract. “Same model, same configuration, same seed → same output” (D2). Say explicitly that it does not hold across versions, GPU types or TP degrees.
  • Record everything that defines the configuration with each deterministic run: engine version, GPU type, TP/EP degree, attention backend, kernel library versions, model and tokenizer revisions, seed. Without it, a result cannot be reproduced later even in D2 mode.
  • RL teams: test the sampler–trainer match, not just the sampler. Log the per-token log-probability difference between rollout and trainer; if you cannot get it to zero, keep an importance-sampling correction (27.e).
  • Evaluation teams: use the deterministic pool and fixed seeds so re-runs measure the model, not the batch it landed in. Report results with the configuration.
  • Support teams: the reproduction recipe for a customer report is the deterministic pool, the original request (including all sampling parameters and the seed, if any), and the same model revision. Without the seed, a sampled request cannot be reproduced; say so up front.

9. Common mistakes#

  1. Believing temperature 0 is deterministic. It removes the sampler’s randomness, not the kernels’ batch dependence.
  2. Believing a deterministic mode covers TP-degree or GPU changes. It gives D2 within one configuration.
  3. Testing determinism with sequential identical requests only. That tests D1, which you already had. Test under mixed load, prefix sharing and preemption.
  4. Comparing text only. Compare logprobs bitwise too.
  5. Enabling the mode fleet-wide and paying 25–55% for traffic that does not need it.
  6. Fixing the sampler but not the trainer in RL and calling it on-policy.
  7. Assuming an unlisted model is covered. Kernels the mode does not cover (an unusual attention variant, a quantization scheme) can quietly break invariance.

10. Hands-on exercise#

  1. Run splitkv.go. Change strategy A to choose splits from sms/batch rounded to a power of two. How many distinct outputs now? Is that batch invariant?
  2. Change the context to 1,024 and then 1,025. Does strategy B stay invariant? Does it still produce the same output as a single split of the whole context? Should it?
  3. With vLLM or SGLang, implement the four test modes of section 5 against a small model: 50 trials each, default mode and deterministic mode. Report unique outputs and whether logprobs match bitwise.
  4. Measure throughput of both modes at concurrency 1, 16 and 128. Plot the slowdown against concurrency.
  5. Serve the same model at TP=1 and TP=2, both in deterministic mode. Are their outputs identical to each other? Explain the result using the levels in section 5.

11. Interview questions#

  1. Why does the same temperature-0 request give different outputs in a busy server, and why is “GPU atomics” usually the wrong answer?
  2. Explain how to make RMSNorm, matmul and attention batch invariant. What does each cost?
  3. Why must prefill and decode attention agree for batch invariance to survive prefix caching and chunked prefill?
  4. A user wants “deterministic outputs”. What exactly can you promise, and what can you not?
  5. Why does bitwise-identical RL need changes on the trainer side as well as the sampler?
  6. How would you test that a deterministic mode really is deterministic?
  7. Why would you run a separate deterministic pool rather than enabling the mode everywhere?

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in