Bit-exact MLX inference on Apple silicon: a technical report on mlx-exact
A technical report on mlx-exact 0.13.1 (MIT). It is not peer-reviewed.
- Our measurements used one Apple M6 with MLX 0.32.4 and mlx-lm 0.32.2, the only environment the package is validated on.
- Each figure below names its model and workload.
- Thresholds and results of other projects are quoted from their sources.
Summary
In stock MLX, a token’s logits depend on how the work was scheduled:
- whether the prompt was prefilled in one go or in chunks;
- whether the token came from prefill or from decode;
- whether the request ran alone or in a batch;
- whether a speculative decoder verified it in a group.
An earlier post, Same prompt, different answer, showed what that does on a benchmark. On the first 300 GSM8K test problems, across four Qwen configurations, 20–60% of the problems got a different greedy final answer under at least one of five ordinary schedules.
mlx-exact’s target is identical logit bits for the same token history, whatever the schedule, on the paths it supports.
- How: for most layers it reproduces the arithmetic MLX already uses for long prefills. A few attention paths use a reduction of mlx-exact’s own (section 2).
- Real checkpoints: seven mlx-community 4-bit models (Llama-3.2-1B, Qwen2.5-1.5B, SmolLM3-3B, Phi-4-mini, Gemma-3-1B, Gemma-3-4B, and Gemma-2-2B for single sequences).
- Token-by-token decode after a 1,400-token prefill matched the one-chunk prefill at 100 of 100 positions, compared bit pattern by bit pattern.
- Stock MLX matched at none.
- Cost: decode ran at 0.93–0.98× of stock speed on the Qwen models measured, and at 0.75–0.81× on Gemma 3 4B and Gemma 2 2B. One-shot prefill was close to stock speed in the measured examples.
This report explains:
- where the differences come from;
- how mlx-exact removes them, and how that was validated;
- what went wrong along the way: two published over-claims, and three bugs that an independent review of this report found before publication.
1. Why the same token gets different logits
MLX picks a GPU kernel for every operation from the shapes involved. For a language model those shapes change with the schedule, because the number of rows in a matmul is the number of tokens processed together.
Quantized matmuls. For typical aligned affine layers (QuantizedLinear), there are four common paths:
| Rows | Kernel | Hardware |
|---|---|---|
| 1 | qmv |
GPU cores |
| 2 up to a shape-dependent limit (13, 25 or 33) | qmv_wide |
GPU cores |
| above the limit, while a split heuristic says so | qmm_t_splitk, with K split into 2 up to K/64 partitions (45 on gpt-oss’s 2,880-wide layers) |
GPU cores, simdgroup matrices |
| otherwise | qmm_t_nax |
the matrix accelerators in the M5/M6 GPU (not the Neural Engine) |
Small inner dimensions have a further branch.
These kernels do not just sum in different orders. They compute different arithmetic:
- Weight rounding: the matrix-matrix kernels round every dequantized weight to bf16/fp16 before multiplying; the vector kernels never do. On one random 4-bit/bf16 setup the two disagreed in 812 of 2,048 outputs.
- Accumulation order: each kernel accumulates in its own order. For the accelerator’s 16×32×16 matrix instruction, I determined the order with crafted inputs.
- A dot product holds +224, −224 and a single 1. In fp32,
2^24 + 1rounds back to2^24, so whether the 1 survives shows which products were added first. - The result: K is processed in chunks of 16. Inside a chunk the products form four quads at offsets {2r, 2r+1, 2r+8, 2r+9}. Each quad is summed as
(p[2r] + p[2r+1]) + (p[2r+8] + p[2r+9]), and the quads go into one fp32 accumulator in order. - On a saved fp16 trial (K = 4,096, a 512-row prefill), a scalar emulation of this order agreed with the hardware on all 2,048 outputs; a rounded exact dot product differed on 8.
- A dot product holds +224, −224 and a single 1. In fp32,
Dense (unquantized) matmuls have the same structure:
gemvfor one row andgemv_widefor a few;- a thin accelerator kernel;
- split-K kernels whose partition count depends on the shape;
- the regular accelerator GEMM.
Attention switches kernels with the number of queries and the head dim (MLX 0.32.4’s dispatch):
- Head dims 64/96/128: vector kernels up to 8 queries, the accelerator’s fused kernel from 9.
- The fused kernel’s key blocks are aligned to key index 0, so left padding in a batch moves a sequence’s keys across block boundaries and changes its result.
- Head dim 192: separate operations (two matmuls with a softmax between them) at every query count.
- Head dim 256: separate operations above 8 queries, and a fused kernel from 1,024 queries with a causal or array mask.
- Head dim 512: its own fused kernel for eligible causal prefills of 1,024 or more queries.
Each of these choices is reasonable for speed. Together they mean that a prompt prefilled at once and the same prompt decoded token by token take different arithmetic paths. So do a sequence alone and the same sequence in a batch.
2. The approach
Two kernel strategies make inference schedule-invariant.
- Define one reduction order and use it for every batch size. This is the batch-invariant approach of Thinking Machines’ batch_invariant_ops and vLLM’s batch invariance. SGLang’s deterministic mode combines such kernels with scheduling changes. On MLX it is taken by mlx-batch-invariant, and by mlx-deterministic, which also offers a Python mode.
- Keep the arithmetic one schedule already uses, and reproduce it in all the others. mlx-exact does this, with MLX’s long-prefill kernels as the reference.
Matmuls:
- Routing: a Python replica of MLX 0.32.4’s dispatch decides, per call, whether stock MLX would run the long-prefill kernel. If not, the call goes to an exact kernel.
- Decode-sized calls (1–3 rows, and 4 rows at 8 bits): kernels that reproduce the accelerator’s order, with each output row split over many lanes. This is what brings decode to 0.93–0.98× of stock on the Qwen models measured.
- Larger calls: MLX’s own accelerator implementation, vendored and run with a 16-row tile. That instantiation keeps the long-prefill kernel’s instruction geometry and K traversal, so each output gets the same arithmetic. This is a property of this kernel, not of tile sizes in general: stock’s 32-row variant of the same kernel follows a different order.
- Covered weight types: dense layers (a 16- or 128-row tile), MoE experts and mxfp4 weights (gpt-oss) have their own variants.
- Raw matmuls (
a @ bin model code: MoE router gates, tied output layers, Gemma 2’s attention) are rerouted the same way since 0.13.0. While exact mode is on, MLX’s Python matmul entry points are replaced process-wide.
Attention:
- Head dims 64/96/128: calls that need rerouting go to MLX’s own fused accelerator kernel, vendored and called with per-sequence key offsets.
- Each sequence reads its keys from its first valid key, taken from mlx-lm’s cache metadata. A row of a left-padded batch then sees the same keys in the same 32-key blocks as when it runs alone.
- An ordinary left-padded KV-cache slice is read in place instead of being copied to realign it.
- Sliding windows (Gemma 3, gpt-oss, Cohere 2): the rotating cache’s window is put back in temporal order and shifted so that each key sits at an index congruent to its absolute position modulo 32. That reproduces the block contents of a full prefill; masked keys contribute exact zeros.
- Head dims 192/256 with several KV heads:
- mlx-exact composes the separate-operations path itself: two accelerator matmuls with at least 16 query rows, and a softmax of its own in between.
- In that softmax, SIMD lane l sums exp(xj − max) over the entries j ≡ l (mod 32), in index order, and the 32 lane sums are combined in a fixed order.
- For a row with at least one valid key, shifting the keys by a multiple of 32 or appending masked keys therefore leaves every probability’s bits unchanged.
- Gemma 2’s attention uses the same softmax.
- Head dims 192/256 with one KV head: a fixed-order fp32 attention, because MLX’s separate-operations path is not shape-consistent there.
- Effect on results: on these attention paths even a one-shot prefill can differ from stock MLX’s bits.
- Effect on speed: a single-KV-head attention layer at 2,048 queries took 11.8 ms against stock’s 0.97 ms (a layer timing).
Gradients: since 0.13.1, every exact route has a backward pass. They are correct gradients computed with stock or fp32 reference arithmetic, not bit-exact ones. With a quantized KV cache, only the queries get a gradient.
- On Qwen3-0.6B-4bit with a rank-8 LoRA adapter, cached decode and the trainer’s forward pass gave equal log-probabilities (untempered) for 64 of 64 sampled tokens on each of two prompts, against 0 of 64 in stock MLX.
- The trainer’s loss was differentiated and an optimizer step taken.
3. Validation
Tests: the release passes 275 tests.
- Most use generated inputs: kernel-level comparisons against MLX’s own kernels, and end-to-end checks with small random-weight models. They run without downloading a checkpoint.
- Since 0.13.1 every exactness check compares bit patterns (
mlx_exact.testing.bits_equal).mx.array_equaltreats +0 and −0 as equal. - The regression tests added for the fixes in sections 4 and 5 were each run on the code before the fix, and failed there.
Real checkpoints: experiments/real_checkpoints.py runs four comparisons with a 1,500-token prompt (GSM8K questions, concatenated):
- one-chunk prefill vs chunks of 512, at 109 checked rows;
- token-by-token decode after a 1,400-token prefill, at 100 positions;
- each sequence of a left-padded batch (1,500 and 1,200 tokens) vs the same sequence alone: the last prefill row and ten forced decode steps, 11 rows each;
- greedy generation of 64 tokens with prefill steps of 2,048 and 512, compared by token ID.
The logit comparisons are on bit patterns. All seven models were rerun with 0.13.1:
| Model (mlx-community, 4-bit) | Attention route | Decode vs prefill, stock | Decode vs prefill, mlx-exact | Other checks, mlx-exact |
|---|---|---|---|---|
| Llama-3.2-1B-Instruct | fused kernel, head dim 64 | 0 / 100 | 100 / 100 | all bit-identical |
| Qwen2.5-1.5B-Instruct | fused kernel, head dim 128 | 0 / 100 | 100 / 100 | all bit-identical |
| SmolLM3-3B | fused kernel, head dim 128 | 0 / 100 | 100 / 100 | all bit-identical |
| Phi-4-mini-instruct | fused kernel, head dim 128 | 0 / 100 | 100 / 100 | all bit-identical |
| gemma-3-1b-it-qat | fixed-order, head dim 256, 1 KV head | 0 / 100 | 100 / 100 | all bit-identical |
| gemma-3-4b-it-qat | composed, head dim 256, 4 KV heads | 0 / 100 | 100 / 100 | all bit-identical |
| gemma-2-2b-it | raw matmuls with softcapping | 0 / 100 | 100 / 100 | single sequences only: batching Gemma 2 fails in mlx-lm itself |
Earlier releases were validated on further models:
- Qwen3-0.6B (4- and 8-bit), Qwen3-1.7B (4-bit) and Qwen3.5-0.8B (4-bit and bf16): decode and chunked prefill vs full prefill, 360 of 360 positions identical. These checks used value equality.
- gpt-oss-20b (MXFP4-Q8), one sequence: a 200-token prompt decoded and prefilled in chunks of 7 matched the full prefill at 200 of 200 positions (stock: 0).
Serving: mlx_lm.server batches concurrent requests. On Qwen3-0.6B-4bit at temperature 0, with up to 200 generated tokens, sending 16 GSM8K requests at once instead of one by one was run twice:
- stock MLX: 7 and 8 of 16 response texts identical;
- mlx-exact: 16 of 16 in both runs.
Speed: historical end-to-end measurements on the same M6, with stock MLX in the same workload as 1×:
| Workload | mlx-exact |
|---|---|
| Decode: Qwen3-0.6B-4bit and Qwen3-1.7B-4bit / Qwen3-0.6B-8bit / Qwen3.5-0.8B-4bit / Qwen3.5-0.8B bf16 | 0.93× / 0.97× / 0.94× / 0.98× |
| Decode at ~1,500 tokens of context: Gemma 3 4B / Gemma 2 2B | 0.75–0.76× (two measurements) / 0.81× |
| Decode: gpt-oss-20b, one sequence | 0.77× (34.8 vs 45.0 tok/s) |
| Batched decode: Qwen3-0.6B-4bit, 8 sequences (measured with 0.8.0) | 0.89× |
| Speculative decoding: Qwen3-1.7B-4bit with a 0.6B-4bit draft, against stock speculative decoding at the same k (2 / 4) | 0.78× / 0.83× |
| Chunked prefill, 512-token input, chunks of 16 / 64 / 128: Qwen3-1.7B-4bit | 1.78× / 1.38× / 1.43× |
| Same, chunks of 16 / 64 / 128 / 512: Qwen3.5-0.8B bf16 | 0.78× / 0.73× / 0.94× / 0.98× |
| One-shot prefill: Qwen3-1.7B-4bit (512 tokens) / Gemma 3 4B and Gemma 2 2B (1,500 tokens) | 1.00× / 0.96× and 0.99× |
Notes on the table:
- Faster chunked prefill: on the 4-bit Qwen3-1.7B run, the vendored 16-row accelerator kernel outperformed the mix of kernels stock MLX selected for those chunk sizes.
- Gemma 3 4B decode: its composed attention materializes the scores, runs two padded matmuls and the lane softmax, and reorders the cache on sliding-window layers.
4. What went wrong along the way
Two claims in the published README turned out to be wrong. Both were caught by checking the next level of realism.
Batched Gemma 3 4B (0.12.0).
- The claim: 0.12.0 announced batched sliding-window attention as bit-exact for head dim 256 with several KV heads. The tests were tiny random models with a 32-key window and short prompts, so their score rows stayed within one 128-key group of MLX’s softmax. They passed.
- The real model:
gemma-3-4b-it-qat(window 1,024) disagreed. Decode after the window had slid matched the full prefill at 0 of 100 positions, and a left-padded sequence in a batch differed from the same sequence alone. - Locating it: recording every layer’s output put the first difference in one attention call of layer 24, by a single bf16 ulp. Replaying that call showed its logical inputs were identical.
-
The mechanism: MLX’s softmax on the separate-operations path sums each row in a tree over 128-key groups. On 1,024-key rows (26,214,400 outputs per shift), shifting the keys gave these mismatch counts:
Shift (keys) 32 64 128 256 512 Mismatching outputs 219 219 172 114 0 - mlx-exact had aligned keys only modulo 32, which is right for the fused kernel’s 32-key blocks but not for this softmax.
- Such a difference can be rounded away later, or it can propagate into later logits. On the real model it did.
- The fix (0.12.1): the lane softmax described in section 2. The real Gemma 3 4B then matched in every comparison.
- A regression test at real sizes passes with it; stock MLX’s attention gives 54 mismatching outputs in the same test.
- Disclosure: the README and the release notes were corrected the same day, before the fix.
Gemma 2 (0.13.0).
- The claim: the README listed gemma2 as bit-exact from a tiny test with head dim 64.
- The real case: a tiny model with Gemma 2’s real head dim (256) matched at only 32 of 70 decode positions, and the real
gemma-2-2b-itat 0 of 100. Gemma 2 computes attention itself, with raw matmuls for its logit softcapping, so none of mlx-exact’s attention routes saw it. - The fix:
- Rerouting raw matmuls fixed contexts up to 4,096 keys.
- Above 4,096 keys MLX’s softmax switches to a different kernel, so Gemma 2’s attention now also uses the lane softmax. A tiny Gemma 2 then decoded past 4,096 keys with 30 of 30 sampled rows bit-identical to its prefill.
- The real
gemma-2-2b-it(1,500-token prompt) matches at 100 of 100.
Before publication of this report. An independent review of a draft by another AI model (OpenAI’s Codex) found three bugs in the published 0.13.0, all fixed in 0.13.1:
- The comparator:
mx.array_equal, used in the tests, treats +0 and −0 as equal, so it could not establish a literal bit claim. All checks now compare bit patterns, and the seven-model table above was rerun that way. - Missing gradients: mxfp4 layers (since 0.9.0) and Gemma 2’s attention (0.13.0) had no backward pass. So did gpt-oss’s full-prefill attention with sinks, whose stock backward pass rejects sinks.
- A rejected argument:
mx.matmul(a, b, stream=...)raised an error while exact mode was on.
Earlier. The same reviewer’s pre-release review of 0.8.0 found bugs in published versions:
- NaN outputs for the padding rows of left-padded batches (head dims 192/256 with one KV head), which reached real rows in the next layer;
- missing backward passes in two attention implementations and in the key-realignment operation;
- unrestricted attention made causal on a fallback path.
Lessons I now apply:
- A tiny-model test can pass over a rare rounding bug. Validate one real checkpoint per architecture class before claiming coverage.
- For rounding questions, run large frequency probes and report the denominator, the input distribution and a model-level check. A probe of 105 outputs can miss a bug that shows up 114 times in 26 million.
- Compare bit patterns when claiming bit identity.
- Check that instrumentation does not bypass the code under test. One of my own probes silently did.
- When a claim turns out wrong, correct the public text first, then fix.
5. Limitations
- Environment: validated on one M6 with MLX 0.32.4 and mlx-lm 0.32.2.
mlx_exact.enable()refuses another MLX version or GPU architecture class unless forced. It does not check the mlx-lm version, and it cannot tell an M6 from other recent chips.- MLX’s development branch has already changed the kernel dispatch, so a port is planned after the next release.
- Not covered:
- DeepSeek-V3-style MLA, whose decode uses a different formulation than its prefill;
- models that call
mx.fast.scaled_dot_product_attentiondirectly (deepseek_v41,plamo2andmuse_sparkin mlx-lm 0.32.2); - unquantized MoE expert layers;
- rotating caches with a kept prefix (
--max-kv-size); - nvfp4 and mxfp8 weights;
- head dim 512 (e.g. Gemma 4’s global layers) for prompts of 1,024 tokens or more, where MLX switches to a fused kernel that mlx-exact does not yet reroute.
- Silent fallbacks: some unsupported layer configurations warn and fall back to stock MLX, but direct stock calls and some operand combinations run silently. For a new architecture, compare the schedules you intend to use.
- Global matmul patch: while exact mode is on, every
a @ bandmx.matmulin the process goes through mlx-exact. Products of two bf16/fp16 arrays take exact routes; other cases go to stock MLX. - Results differ from stock: canonical results are not always stock results (section 2).
- Accuracy: on the measured Qwen3-1.7B-4bit projections, the median relative RMS error against an fp64 dot product of the stored (quantized) weights was about 0.0019–0.0022 for the prefill arithmetic and 0.00166 for stock decode. The canonical arithmetic is the prefill one.
6. Related work
- Thinking Machines (Defeating Nondeterminism in LLM Inference, 2025) traced served-model nondeterminism to batch-dependent reduction orders and introduced batch-invariant kernels.
- Production engines: SGLang’s deterministic inference and vLLM’s batch invariance are production implementations.
- Determinism by scheduling:
- LLM-42 (arXiv 2601.17768) verifies a fast path and rolls back.
- CoRun (arXiv 2608.14376) uses isolated prefill and fixed-shape decode.
- Vosti (arXiv 2609.38981) specifies deterministic inference: for a fixed model, deployment and initial sampler state, bitwise-identical logits across batch composition, chunking, prefill/decode and KV-cache reuse. It then builds an engine verified against that specification.
- Whole-model tests on an H200 found logit mismatches on text-only Gemma3-4B in the tested deterministic configurations of vLLM 0.28.0 and SGLang 0.5.19.
- We independently traced an MLX mismatch on the same architecture to the softmax reduction order (section 4). Vosti’s tests do not localize its mismatches to that mechanism.
- On MLX:
- mlx-batch-invariant (2026) provides batch-invariant matmul, quantized matmul, RMSNorm and attention kernels that are also prefill/decode and chunk invariant, tested on an M4.
- mlx-deterministic (2025) brings batch-invariant operations to MLX.
- mlx-exact differs in reproducing MLX’s own long-prefill arithmetic where it can instead of defining a new order, in targeting the M5/M6 matrix accelerators, and in its tested scope: mlx-lm’s batched serving, sliding windows, attention sinks, mxfp4 and speculative decoding.
7. Reproducing
The scripts live in the source tree:
git clone --branch v0.13.1 --depth 1 https://github.com/audenvenn/mlx-exact.git
cd mlx-exact
python -m pip install -e '.[lm]' 'mlx-lm==0.32.2' pyarrow
Real checkpoints (section 3), with Gemma 2 run separately because batching it fails in mlx-lm itself:
python experiments/real_checkpoints.py mlx-community/Llama-3.2-1B-Instruct-4bit mlx-community/Qwen2.5-1.5B-Instruct-4bit mlx-community/SmolLM3-3B-4bit mlx-community/Phi-4-mini-instruct-4bit mlx-community/gemma-3-1b-it-qat-4bit mlx-community/gemma-3-4b-it-qat-4bit
python experiments/real_checkpoints.py --no-batch mlx-community/gemma-2-2b-it-4bit
Serving, once per mode:
python experiments/server_identity.py
python experiments/server_identity.py --exact
To use exact mode in your own code:
import mlx_exact
mlx_exact.enable() # then use mlx-lm as usual
experiments/ also has the GSM8K schedule study and the architecture sweep. The end-to-end speed figures came from measurement drivers in my research notes that are not part of the release. docs/numerics.md has the full analysis.
This report and the code it describes were developed with AI assistance (Anthropic’s Claude) and checked by the tests and measurements described above. Before publication a draft was reviewed by another AI model (OpenAI’s Codex), whose findings led to version 0.13.1. It is a technical report, not a peer-reviewed paper.