CubeWriting

Defeating Nondeterminism in LLM Inference

MD2,088 words~9 min

# Defeating Nondeterminism in LLM Inference Horace He in collaboration with others at Thinking Machines https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/ Presented by Julius Chandler for BASIS (Berkeley AI Safety Initiative) --- ## Is this useful? Should you care? Some reasons we might want reproducibility: - Replication of results (scientific reproducibility) - Reinforcement Learning Training - Testing (also regulation in financial/medical situations) - Robustness…? - Some understanding of how requests in production are batched on a kernel/hardware level. ## Different outputs… duh and not so duh - Getting a result from a language model involves “sampling”, a process that converts the language model’s output into a probability distribution and probabilistically selects a token. So duh, different results - But even when we adjust the temperature down to 0¹ (thus making the sampling theoretically deterministic), LLM APIs are still not deterministic in practice?? ¹ This means that the LLM always chooses the highest probability token, which is called greedy sampling. ## How now, mad cow? ## The common misconception - Most people blame the **“concurrency + floating point” hypothesis** - GPUs perform calculations in parallel. - The order in which threads finish is nondeterministic. - Floating-point math isn’t associative (e.g., (0.1+1e20)−1e20=0, but 0.1+(1e20−1e20)=0.1). - Therefore, the final result changes slightly with each run. ### Race conditions - This happens but paper authors show this is not the main culprit… Most operations are ‘run to run deterministic’ (running the same matrix multiplication twice will give a bitwise identical result). So not racing…? ## Original Sin: Floating point non associativity (a + b) + c ≠ a + (b + c) ```python (0.1 + 1e20) - 1e20 >>> 0 0.1 + (1e20 - 1e20) >>> 0.1 ``` Therefore, when performing operations (like adding, multiplying) in different orders, information is destroyed. But why do we do this? Why oh why do we use float32 (or… even 16): - If we store as Float64 it costs more memory, and we end up at the same place. - If we store as integer * constants it will either destroy small gradients (0.0001 gets rounded to 0) when keeping as is, or easily overflow if huge constant. Manual scaling sucks to implement. ## Okay… but race conditions aren’t happening? *Figure: run-to-run nondeterminism (a visualisation of what ISN’T happening in most LLMS)* - The run to run determinism shows that it really isn’t the fault of i.e. thread 1, then thread 2, then thread 3 finishing one time, and in another run it being in a different order. That usually has no effect here. - Some kernels on GPUs are **nondeterministic**. It’s true. Such as atomic adds. - However, all the kernels used in a language model’s forward pass are **deterministic**. We reduce with tree reduction then deterministically add those (ie 5 way parallelisation). Atomic adds are negligible boosts. - Moreover, the forward pass of an LLM inference server (like vLLM) can also be claimed to be **deterministic**. - Nevertheless, from the perspective of anybody using the inference server, the results are **nondeterministic**. - So what is going on?? ## Adages past the atomic (add) age - We don’t use atomic adds in the forward pass - So no information loss is happening in the kernels due to race conditions or anything to do with the inference server - In fact, it’s fully fine to say that “from the perspective of the inference server, it is deterministic. Given the exact same user requests, it will always provide the same deterministic output.” - What??? - And I repeat, How now mad cow? ## As Kendrick Lamar once said: Hol’ Up Can you spot some wriggle room for some changing variable? *Figure: user requests and other user requests both go into a deterministic model, which gives the output.* Hint: “Given the exact same user requests, it will always provide the same deterministic output” ## Batches!!!!! (more specifically batch invariance) *Unfortunately, not cookies or scones (shoutout the UK)* - What if our request’s output depended on the parallel user requests (e.g. batch-norm)? Since each individual request has no way of knowing what the parallel requests will be, from their perspective our overall LLM inference is also nondeterministic! - Our request’s output does depend on the parallel user requests. Not because we’re somehow leaking information across batches, instead, it’s because our forward pass lacks “batch invariance”, causing our request’s output to depend on the batch size of our forward pass. ## Translate that pls - Let’s simplify it and just look at matmuls (matrix multiplications), assuming all matmuls are run to run deterministic (they aren’t always but commonly are) - But they are not ‘batch invariant.’ When the batch size changes, each element in the batch can get different results. - Weird math property, this script should be deterministic. But server load changes. Example script for a matmul: ```python import torch torch.set_default_device('cuda') B = 2048 D = 4096 a = torch.linspace(-1000, 1000, B*D).reshape(B, D) b = torch.linspace(-1000, 1000, D*D).reshape(D, D) # Doing a matrix vector multiplication by taking # the first element of the batch out1 = torch.mm(a[:1], b) # Doing a matrix matrix multiplication and then taking # the first element of the batch out2 = torch.mm(a, b)[:1] print((out1 - out2).abs().max()) # tensor(1669.2500, device='cuda:0') ``` ## Continued: Server load, batch variant matmul Example matmul to pick apart: ``` result = A × B for one row of A result = a₁×b₁ + a₂×b₂ + a₃×b₃ + ... + a₁₀₀₀×b₁₀₀₀ ``` Scenario 1. Large batch (1000 rows to compute, kernel assigns one GPU core per row) For this particular row it adds ((a₁×b₁ + a₂×b₂) + a₃×b₃) + ... left to right Scenario 2. Small batch (10 rows to compute, kernel parallelises WITHIN each row to minimise wastage of compute) Splits this row across multiple cores: - Core 1 computes a₁×b₁ + ... + a₅₀₀×b₅₀₀, - Core 2 computes a₅₀₁×b₅₀₁ + ... + a₁₀₀₀×b₁₀₀₀, then combines them Now the addition order is: (a₁×b₁ + ... + a₅₀₀×b₅₀₀) + (a₅₀₁×b₅₀₁ + ... + a₁₀₀₀×b₁₀₀₀) (split-reduce) Remember the original sin: When you add numbers in different orders, you lose precision in different places. With thousands of additions across a neural network, these tiny differences compound into different final outputs. ## The culprit uncovered! - Though technically speaking, the batch size is a variable, which if controlled for would lead to deterministic results, from our point, we don’t know server traffic etc. - From our perspective, batch variant calculations where the kernel tries to be smart, result in losing determinism. - When you send a request to an LLM inference server, your request is batched with other users’ requests to maximize efficiency. - The server’s load is constantly changing, meaning the size of the batch your request is part of is effectively random from your perspective. - Because the kernel’s output depends on the batch size, and the batch size is unpredictable, your final result is nondeterministic. ## Now what? - “Hey doc, I don’t care to have you yelling in my ear about my broken leg unless ya’ planning to fix it.” - Instead of whining about issues, let’s focus on solutions. - Solutions? Let’s pick your brains for ideas on combatting this, build intuition. ## Building batch invariant kernels. - To achieve true determinism, every operation in the transformer must be made batch-invariant. The authors focused on the three key operations involving reductions: - **RMSNorm**, **matrix multiplication**, and **attention**. - The core idea is to force these operations to use a **single, consistent reduction strategy** regardless of the batch size or how a sequence is processed (e.g., prefill vs. decoding). This sometimes means sacrificing the small performance optimizations that kernels use for specific batch sizes (like “Split-K” matmuls, discussed previously or dynamic attention scheduling). - Basically, you get the kernels to reduce the same way every time no matter how big or small the batch is. ## RMSNorm: let’s start simple ### What is RMSNorm? - In layers, if we multiply by a scale of ie 2, over a number of layers that explodes to huge values. One solution to make it smaller is to normalise. - RMSNorm normalizes each sequence by computing the root mean square (square values, find mean/average, root the average, then divide by that sqrt(AverageOfSquaredValues) across the hidden dimension, then only after that scales by learned weights. **Standard strategy:** 1. Assign each batch element to one GPU core 2. Each core does its own reduction independently 3. Works great when batch size ≥ number of cores **Current batch variance problem:** 1. When batch size < number of cores → some cores sit idle 2. "Smart" kernels fix this by splitting each element's reduction across multiple cores (like previously discussed) 3. This changes the reduction order **Fix:** 1. Just accept idle cores for small batches 2. Always use the same "one element per core" strategy 3. Performance hit is small since small batches are fast anyway ## Matrix Multiplication - this is what we trained for ### What is Matrix Multiplication: - C=A x B - Lol **Ignore the fancy words, this is what we discussed previously.** **Standard strategy:** - Split output matrix C into 2D tiles (e.g., 128×128) - Each GPU core computes one tile using tensor cores - "Data parallel" - parallelizes across output dimensions (M, N) **The problem:** - When M or N are small → not enough output tiles to saturate GPU - "Smart" kernels use **Split-K**: parallelize along the reduction dimension K instead - Different batch sizes trigger Split-K differently → different reduction orders - Additional issue: Different tensor core instructions for different tile sizes **The fix:** - Pick one kernel configuration and stick with it for all shapes - No Split-K optimizations (accept slowdown on small batches) - Use consistent tile sizes and tensor core instructions - Fortunately, Split-K is rarely needed in practice since model dimension (N) is usually large ## Paying attention to this is all you need ### Attention is key architecture - Lets a token “look” at other tokens and gather information for context. - Before attention, older models like RNNs had information process sequentially (left to right) - Now every token can attend to every other token - Softmax(QK^T)V where softmax is just normalising the result of a score like scores = Query · Keys^T - Imagine that the dot product measures **how similar two vectors are** - specifically, how much they point in the same direction. - Through the magic of backprop (I <3 calculus) the model learns non-random Q(uery) vectors that ask for information, K(ey) vectors that advertise their content and V(alue) them properly. - We need to compute a bunch of dot products, and a softmax, then a weighted sum over all tokens. Uh oh. **Standard strategy:** 1. Data parallel: Each GPU core processes different query tokens, good 2. Reduces over the key/value sequence dimension, not so good anymore Uses FlashAttention as implementation (minor implementation detail) **The problems (multiple!):** Prefill vs. Decoding: - Prefill: Process many query tokens at once - Decoding: Process 1 query token, but attend to long KV cache - Same token can be computed in either mode → must give same result Split-KV (FlashDecoding): - During decoding: 1 query token, minimal parallelism - Need to split the KV sequence across cores to saturate GPU - Different batch sizes → different split strategies → different reduction orders Dynamic scheduling: - FlashInfer's "balanced scheduling" chooses split size to saturate all cores - Changes based on how many queries you're processing - Breaks batch invariance **The fix:** - **Always update KV cache first** before running attention - Ensures keys/values are consistently laid out - Token 50 sees the same data whether in prefill or decoding - **Use fixed split-size, not fixed split-count:** - Instead of "split into 80 chunks (however big they need to be)" - Use "always make chunks of 128 tokens (however many chunks needed)" - Guarantees same reduction order regardless of batch size - **Consistent tile sizes** (like matmul) ## Paper results **True Determinism:** Using their batch-invariant kernels on top of vLLM, they ran the same prompt 1000 times. - **Standard vLLM:** Produced **80 unique completions**. - **Deterministic vLLM** (Using discussed techniques): Produced **1 unique completion**. Performance: Slightly worse but certainly usable (this is even without much optimisation) | Configuration | Time (seconds) | | --- | ---: | | vLLM default | 26 | | Unoptimized Deterministic vLLM | 55 | | + Improved Attention Kernel | 42 | ### ‘True’ on-policy RL No reward collapse or needing to adjust from bad algorithmic assumptions

‹ Back to the writing archive

JNC WEBSYS© 2026 JNC

let us consider how we may spur one another on toward love and good deeds