<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://audenvenn.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://audenvenn.github.io/" rel="alternate" type="text/html" /><updated>2026-11-23T05:42:37+00:00</updated><id>https://audenvenn.github.io/feed.xml</id><title type="html">Auden Venn</title><subtitle>Notes on local AI on Apple silicon, measured honestly.</subtitle><author><name>Auden Venn</name></author><entry><title type="html">Bit-exact MLX inference on Apple silicon: a technical report on mlx-exact</title><link href="https://audenvenn.github.io/2026/11/23/mlx-exact-technical-report.html" rel="alternate" type="text/html" title="Bit-exact MLX inference on Apple silicon: a technical report on mlx-exact" /><published>2026-11-23T05:41:00+00:00</published><updated>2026-11-23T05:41:00+00:00</updated><id>https://audenvenn.github.io/2026/11/23/mlx-exact-technical-report</id><content type="html" xml:base="https://audenvenn.github.io/2026/11/23/mlx-exact-technical-report.html"><![CDATA[<p><em>A technical report on <a href="https://github.com/audenvenn/mlx-exact/tree/v0.13.1">mlx-exact</a> 0.13.1 (MIT). It is not peer-reviewed.</em></p>
<ul>
  <li><em>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.</em></li>
  <li><em>Each figure below names its model and workload.</em></li>
  <li><em>Thresholds and results of other projects are quoted from their sources.</em></li>
</ul>

<h2 id="summary">Summary</h2>

<p>In stock MLX, a token’s logits depend on how the work was scheduled:</p>
<ul>
  <li>whether the prompt was prefilled in one go or in chunks;</li>
  <li>whether the token came from prefill or from decode;</li>
  <li>whether the request ran alone or in a batch;</li>
  <li>whether a speculative decoder verified it in a group.</li>
</ul>

<p>An earlier post, <a href="https://audenvenn.github.io/2026/11/20/mlx-output-depends-on-schedule.html">Same prompt, different answer</a>, 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.</p>

<p>mlx-exact’s target is identical logit bits for the same token history, whatever the schedule, on the paths it supports.</p>
<ul>
  <li><strong>How:</strong> 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).</li>
  <li><strong>Real checkpoints:</strong> 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).
    <ul>
      <li>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.</li>
      <li>Stock MLX matched at none.</li>
    </ul>
  </li>
  <li><strong>Cost:</strong> 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.</li>
</ul>

<p>This report explains:</p>
<ul>
  <li>where the differences come from;</li>
  <li>how mlx-exact removes them, and how that was validated;</li>
  <li>what went wrong along the way: two published over-claims, and three bugs that an independent review of this report found before publication.</li>
</ul>

<h2 id="1-why-the-same-token-gets-different-logits">1. Why the same token gets different logits</h2>

<p>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.</p>

<p><strong>Quantized matmuls.</strong> For typical aligned affine layers (<code class="language-plaintext highlighter-rouge">QuantizedLinear</code>), there are four common paths:</p>

<table>
  <thead>
    <tr>
      <th>Rows</th>
      <th>Kernel</th>
      <th>Hardware</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td><code class="language-plaintext highlighter-rouge">qmv</code></td>
      <td>GPU cores</td>
    </tr>
    <tr>
      <td>2 up to a shape-dependent limit (13, 25 or 33)</td>
      <td><code class="language-plaintext highlighter-rouge">qmv_wide</code></td>
      <td>GPU cores</td>
    </tr>
    <tr>
      <td>above the limit, while a split heuristic says so</td>
      <td><code class="language-plaintext highlighter-rouge">qmm_t_splitk</code>, with K split into 2 up to K/64 partitions (45 on gpt-oss’s 2,880-wide layers)</td>
      <td>GPU cores, simdgroup matrices</td>
    </tr>
    <tr>
      <td>otherwise</td>
      <td><code class="language-plaintext highlighter-rouge">qmm_t_nax</code></td>
      <td>the matrix accelerators in the M5/M6 GPU (not the Neural Engine)</td>
    </tr>
  </tbody>
</table>

<p>Small inner dimensions have a further branch.</p>

<p>These kernels do not just sum in different orders. They compute different arithmetic:</p>
<ul>
  <li><strong>Weight rounding:</strong> 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.</li>
  <li><strong>Accumulation order:</strong> each kernel accumulates in its own order. For the accelerator’s 16×32×16 matrix instruction, I determined the order with crafted inputs.
    <ul>
      <li>A dot product holds +2<sup>24</sup>, −2<sup>24</sup> and a single 1. In fp32, <code class="language-plaintext highlighter-rouge">2^24 + 1</code> rounds back to <code class="language-plaintext highlighter-rouge">2^24</code>, so whether the 1 survives shows which products were added first.</li>
      <li>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 <code class="language-plaintext highlighter-rouge">(p[2r] + p[2r+1]) + (p[2r+8] + p[2r+9])</code>, and the quads go into one fp32 accumulator in order.</li>
      <li>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.</li>
    </ul>
  </li>
</ul>

<p><strong>Dense (unquantized) matmuls</strong> have the same structure:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">gemv</code> for one row and <code class="language-plaintext highlighter-rouge">gemv_wide</code> for a few;</li>
  <li>a thin accelerator kernel;</li>
  <li>split-K kernels whose partition count depends on the shape;</li>
  <li>the regular accelerator GEMM.</li>
</ul>

<p><strong>Attention</strong> switches kernels with the number of queries and the head dim (MLX 0.32.4’s dispatch):</p>
<ul>
  <li><strong>Head dims 64/96/128:</strong> vector kernels up to 8 queries, the accelerator’s fused kernel from 9.
    <ul>
      <li>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.</li>
    </ul>
  </li>
  <li><strong>Head dim 192:</strong> separate operations (two matmuls with a softmax between them) at every query count.</li>
  <li><strong>Head dim 256:</strong> separate operations above 8 queries, and a fused kernel from 1,024 queries with a causal or array mask.</li>
  <li><strong>Head dim 512:</strong> its own fused kernel for eligible causal prefills of 1,024 or more queries.</li>
</ul>

<p>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.</p>

<h2 id="2-the-approach">2. The approach</h2>

<p>Two kernel strategies make inference schedule-invariant.</p>
<ol>
  <li><strong>Define one reduction order and use it for every batch size.</strong> This is the batch-invariant approach of Thinking Machines’ <a href="https://github.com/thinking-machines-lab/batch_invariant_ops">batch_invariant_ops</a> and vLLM’s batch invariance. SGLang’s deterministic mode combines such kernels with scheduling changes. On MLX it is taken by <a href="https://github.com/waseemh/mlx-batch-invariant">mlx-batch-invariant</a>, and by <a href="https://github.com/ProbioticFarmer/mlx-deterministic">mlx-deterministic</a>, which also offers a Python mode.</li>
  <li><strong>Keep the arithmetic one schedule already uses, and reproduce it in all the others.</strong> mlx-exact does this, with MLX’s long-prefill kernels as the reference.</li>
</ol>

<p><strong>Matmuls:</strong></p>
<ul>
  <li><strong>Routing:</strong> 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.</li>
  <li><strong>Decode-sized calls</strong> (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.</li>
  <li><strong>Larger calls:</strong> 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.</li>
  <li><strong>Covered weight types:</strong> dense layers (a 16- or 128-row tile), MoE experts and mxfp4 weights (gpt-oss) have their own variants.</li>
  <li><strong>Raw matmuls</strong> (<code class="language-plaintext highlighter-rouge">a @ b</code> in 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.</li>
</ul>

<p><strong>Attention:</strong></p>
<ul>
  <li><strong>Head dims 64/96/128:</strong> calls that need rerouting go to MLX’s own fused accelerator kernel, vendored and called with per-sequence key offsets.
    <ul>
      <li>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.</li>
      <li>An ordinary left-padded KV-cache slice is read in place instead of being copied to realign it.</li>
    </ul>
  </li>
  <li><strong>Sliding windows</strong> (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.</li>
  <li><strong>Head dims 192/256 with several KV heads:</strong>
    <ul>
      <li>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.</li>
      <li>In that softmax, SIMD lane l sums exp(x<sub>j</sub> − max) over the entries j ≡ l (mod 32), in index order, and the 32 lane sums are combined in a fixed order.</li>
      <li>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.</li>
      <li>Gemma 2’s attention uses the same softmax.</li>
    </ul>
  </li>
  <li><strong>Head dims 192/256 with one KV head:</strong> a fixed-order fp32 attention, because MLX’s separate-operations path is not shape-consistent there.</li>
  <li><strong>Effect on results:</strong> on these attention paths even a one-shot prefill can differ from stock MLX’s bits.</li>
  <li><strong>Effect on speed:</strong> a single-KV-head attention layer at 2,048 queries took 11.8 ms against stock’s 0.97 ms (a layer timing).</li>
</ul>

<p><strong>Gradients:</strong> 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.</p>
<ul>
  <li>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.</li>
  <li>The trainer’s loss was differentiated and an optimizer step taken.</li>
</ul>

<h2 id="3-validation">3. Validation</h2>

<p><strong>Tests:</strong> the release passes 275 tests.</p>
<ul>
  <li>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.</li>
  <li>Since 0.13.1 every exactness check compares bit patterns (<code class="language-plaintext highlighter-rouge">mlx_exact.testing.bits_equal</code>). <code class="language-plaintext highlighter-rouge">mx.array_equal</code> treats +0 and −0 as equal.</li>
  <li>The regression tests added for the fixes in sections 4 and 5 were each run on the code before the fix, and failed there.</li>
</ul>

<p><strong>Real checkpoints:</strong> <code class="language-plaintext highlighter-rouge">experiments/real_checkpoints.py</code> runs four comparisons with a 1,500-token prompt (GSM8K questions, concatenated):</p>
<ul>
  <li>one-chunk prefill vs chunks of 512, at 109 checked rows;</li>
  <li>token-by-token decode after a 1,400-token prefill, at 100 positions;</li>
  <li>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;</li>
  <li>greedy generation of 64 tokens with prefill steps of 2,048 and 512, compared by token ID.</li>
</ul>

<p>The logit comparisons are on bit patterns. All seven models were rerun with 0.13.1:</p>

<table>
  <thead>
    <tr>
      <th>Model (mlx-community, 4-bit)</th>
      <th>Attention route</th>
      <th>Decode vs prefill, stock</th>
      <th>Decode vs prefill, mlx-exact</th>
      <th>Other checks, mlx-exact</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Llama-3.2-1B-Instruct</td>
      <td>fused kernel, head dim 64</td>
      <td>0 / 100</td>
      <td>100 / 100</td>
      <td>all bit-identical</td>
    </tr>
    <tr>
      <td>Qwen2.5-1.5B-Instruct</td>
      <td>fused kernel, head dim 128</td>
      <td>0 / 100</td>
      <td>100 / 100</td>
      <td>all bit-identical</td>
    </tr>
    <tr>
      <td>SmolLM3-3B</td>
      <td>fused kernel, head dim 128</td>
      <td>0 / 100</td>
      <td>100 / 100</td>
      <td>all bit-identical</td>
    </tr>
    <tr>
      <td>Phi-4-mini-instruct</td>
      <td>fused kernel, head dim 128</td>
      <td>0 / 100</td>
      <td>100 / 100</td>
      <td>all bit-identical</td>
    </tr>
    <tr>
      <td>gemma-3-1b-it-qat</td>
      <td>fixed-order, head dim 256, 1 KV head</td>
      <td>0 / 100</td>
      <td>100 / 100</td>
      <td>all bit-identical</td>
    </tr>
    <tr>
      <td>gemma-3-4b-it-qat</td>
      <td>composed, head dim 256, 4 KV heads</td>
      <td>0 / 100</td>
      <td>100 / 100</td>
      <td>all bit-identical</td>
    </tr>
    <tr>
      <td>gemma-2-2b-it</td>
      <td>raw matmuls with softcapping</td>
      <td>0 / 100</td>
      <td>100 / 100</td>
      <td>single sequences only: batching Gemma 2 fails in mlx-lm itself</td>
    </tr>
  </tbody>
</table>

<p>Earlier releases were validated on further models:</p>
<ul>
  <li>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.</li>
  <li>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).</li>
</ul>

<p><strong>Serving:</strong> <code class="language-plaintext highlighter-rouge">mlx_lm.server</code> 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:</p>
<ul>
  <li>stock MLX: 7 and 8 of 16 response texts identical;</li>
  <li>mlx-exact: 16 of 16 in both runs.</li>
</ul>

<p><strong>Speed:</strong> historical end-to-end measurements on the same M6, with stock MLX in the same workload as 1×:</p>

<table>
  <thead>
    <tr>
      <th>Workload</th>
      <th>mlx-exact</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Decode: Qwen3-0.6B-4bit and Qwen3-1.7B-4bit / Qwen3-0.6B-8bit / Qwen3.5-0.8B-4bit / Qwen3.5-0.8B bf16</td>
      <td>0.93× / 0.97× / 0.94× / 0.98×</td>
    </tr>
    <tr>
      <td>Decode at ~1,500 tokens of context: Gemma 3 4B / Gemma 2 2B</td>
      <td>0.75–0.76× (two measurements) / 0.81×</td>
    </tr>
    <tr>
      <td>Decode: gpt-oss-20b, one sequence</td>
      <td>0.77× (34.8 vs 45.0 tok/s)</td>
    </tr>
    <tr>
      <td>Batched decode: Qwen3-0.6B-4bit, 8 sequences (measured with 0.8.0)</td>
      <td>0.89×</td>
    </tr>
    <tr>
      <td>Speculative decoding: Qwen3-1.7B-4bit with a 0.6B-4bit draft, against stock speculative decoding at the same k (2 / 4)</td>
      <td>0.78× / 0.83×</td>
    </tr>
    <tr>
      <td>Chunked prefill, 512-token input, chunks of 16 / 64 / 128: Qwen3-1.7B-4bit</td>
      <td>1.78× / 1.38× / 1.43×</td>
    </tr>
    <tr>
      <td>Same, chunks of 16 / 64 / 128 / 512: Qwen3.5-0.8B bf16</td>
      <td>0.78× / 0.73× / 0.94× / 0.98×</td>
    </tr>
    <tr>
      <td>One-shot prefill: Qwen3-1.7B-4bit (512 tokens) / Gemma 3 4B and Gemma 2 2B (1,500 tokens)</td>
      <td>1.00× / 0.96× and 0.99×</td>
    </tr>
  </tbody>
</table>

<p>Notes on the table:</p>
<ul>
  <li><strong>Faster chunked prefill:</strong> 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.</li>
  <li><strong>Gemma 3 4B decode:</strong> its composed attention materializes the scores, runs two padded matmuls and the lane softmax, and reorders the cache on sliding-window layers.</li>
</ul>

<h2 id="4-what-went-wrong-along-the-way">4. What went wrong along the way</h2>

<p>Two claims in the published README turned out to be wrong. Both were caught by checking the next level of realism.</p>

<p><strong>Batched Gemma 3 4B (0.12.0).</strong></p>
<ul>
  <li><strong>The claim:</strong> 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.</li>
  <li><strong>The real model:</strong> <code class="language-plaintext highlighter-rouge">gemma-3-4b-it-qat</code> (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.</li>
  <li><strong>Locating it:</strong> 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.</li>
  <li>
    <p><strong>The mechanism:</strong> 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:</p>

    <table>
      <thead>
        <tr>
          <th>Shift (keys)</th>
          <th>32</th>
          <th>64</th>
          <th>128</th>
          <th>256</th>
          <th>512</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Mismatching outputs</td>
          <td>219</td>
          <td>219</td>
          <td>172</td>
          <td>114</td>
          <td>0</td>
        </tr>
      </tbody>
    </table>

    <ul>
      <li>mlx-exact had aligned keys only modulo 32, which is right for the fused kernel’s 32-key blocks but not for this softmax.</li>
      <li>Such a difference can be rounded away later, or it can propagate into later logits. On the real model it did.</li>
    </ul>
  </li>
  <li><strong>The fix (0.12.1):</strong> the lane softmax described in section 2. The real Gemma 3 4B then matched in every comparison.
    <ul>
      <li>A regression test at real sizes passes with it; stock MLX’s attention gives 54 mismatching outputs in the same test.</li>
    </ul>
  </li>
  <li><strong>Disclosure:</strong> the README and the release notes were corrected the same day, before the fix.</li>
</ul>

<p><strong>Gemma 2 (0.13.0).</strong></p>
<ul>
  <li><strong>The claim:</strong> the README listed gemma2 as bit-exact from a tiny test with head dim 64.</li>
  <li><strong>The real case:</strong> a tiny model with Gemma 2’s real head dim (256) matched at only 32 of 70 decode positions, and the real <code class="language-plaintext highlighter-rouge">gemma-2-2b-it</code> at 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.</li>
  <li><strong>The fix:</strong>
    <ul>
      <li>Rerouting raw matmuls fixed contexts up to 4,096 keys.</li>
      <li>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.</li>
      <li>The real <code class="language-plaintext highlighter-rouge">gemma-2-2b-it</code> (1,500-token prompt) matches at 100 of 100.</li>
    </ul>
  </li>
</ul>

<p><strong>Before publication of this report.</strong> 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:</p>
<ul>
  <li><strong>The comparator:</strong> <code class="language-plaintext highlighter-rouge">mx.array_equal</code>, 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.</li>
  <li><strong>Missing gradients:</strong> 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.</li>
  <li><strong>A rejected argument:</strong> <code class="language-plaintext highlighter-rouge">mx.matmul(a, b, stream=...)</code> raised an error while exact mode was on.</li>
</ul>

<p><strong>Earlier.</strong> The same reviewer’s pre-release review of 0.8.0 found bugs in published versions:</p>
<ul>
  <li>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;</li>
  <li>missing backward passes in two attention implementations and in the key-realignment operation;</li>
  <li>unrestricted attention made causal on a fallback path.</li>
</ul>

<p><strong>Lessons I now apply:</strong></p>
<ul>
  <li>A tiny-model test can pass over a rare rounding bug. Validate one real checkpoint per architecture class before claiming coverage.</li>
  <li>For rounding questions, run large frequency probes and report the denominator, the input distribution and a model-level check. A probe of 10<sup>5</sup> outputs can miss a bug that shows up 114 times in 26 million.</li>
  <li>Compare bit patterns when claiming bit identity.</li>
  <li>Check that instrumentation does not bypass the code under test. One of my own probes silently did.</li>
  <li>When a claim turns out wrong, correct the public text first, then fix.</li>
</ul>

<h2 id="5-limitations">5. Limitations</h2>

<ul>
  <li><strong>Environment:</strong> validated on one M6 with MLX 0.32.4 and mlx-lm 0.32.2.
    <ul>
      <li><code class="language-plaintext highlighter-rouge">mlx_exact.enable()</code> 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.</li>
      <li>MLX’s development branch has already changed the kernel dispatch, so a port is planned after the next release.</li>
    </ul>
  </li>
  <li><strong>Not covered:</strong>
    <ul>
      <li>DeepSeek-V3-style MLA, whose decode uses a different formulation than its prefill;</li>
      <li>models that call <code class="language-plaintext highlighter-rouge">mx.fast.scaled_dot_product_attention</code> directly (<code class="language-plaintext highlighter-rouge">deepseek_v41</code>, <code class="language-plaintext highlighter-rouge">plamo2</code> and <code class="language-plaintext highlighter-rouge">muse_spark</code> in mlx-lm 0.32.2);</li>
      <li>unquantized MoE expert layers;</li>
      <li>rotating caches with a kept prefix (<code class="language-plaintext highlighter-rouge">--max-kv-size</code>);</li>
      <li>nvfp4 and mxfp8 weights;</li>
      <li>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.</li>
    </ul>
  </li>
  <li><strong>Silent fallbacks:</strong> 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.</li>
  <li><strong>Global matmul patch:</strong> while exact mode is on, every <code class="language-plaintext highlighter-rouge">a @ b</code> and <code class="language-plaintext highlighter-rouge">mx.matmul</code> in the process goes through mlx-exact. Products of two bf16/fp16 arrays take exact routes; other cases go to stock MLX.</li>
  <li><strong>Results differ from stock:</strong> canonical results are not always stock results (section 2).</li>
  <li><strong>Accuracy:</strong> 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.</li>
</ul>

<h2 id="6-related-work">6. Related work</h2>

<ul>
  <li><strong>Thinking Machines</strong> (<a href="https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/">Defeating Nondeterminism in LLM Inference</a>, 2025) traced served-model nondeterminism to batch-dependent reduction orders and introduced batch-invariant kernels.</li>
  <li><strong>Production engines:</strong> <a href="https://lmsys.org/blog/2025-09-22-sglang-deterministic/">SGLang’s deterministic inference</a> and <a href="https://docs.vllm.ai/en/latest/features/batch_invariance/">vLLM’s batch invariance</a> are production implementations.</li>
  <li><strong>Determinism by scheduling:</strong>
    <ul>
      <li>LLM-42 (<a href="https://arxiv.org/abs/2601.17768">arXiv 2601.17768</a>) verifies a fast path and rolls back.</li>
      <li>CoRun (<a href="https://arxiv.org/abs/2608.14376">arXiv 2608.14376</a>) uses isolated prefill and fixed-shape decode.</li>
    </ul>
  </li>
  <li><strong>Vosti</strong> (<a href="https://arxiv.org/abs/2609.38981">arXiv 2609.38981</a>) 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.
    <ul>
      <li>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.</li>
      <li>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.</li>
    </ul>
  </li>
  <li><strong>On MLX:</strong>
    <ul>
      <li><a href="https://github.com/waseemh/mlx-batch-invariant">mlx-batch-invariant</a> (2026) provides batch-invariant matmul, quantized matmul, RMSNorm and attention kernels that are also prefill/decode and chunk invariant, tested on an M4.</li>
      <li><a href="https://github.com/ProbioticFarmer/mlx-deterministic">mlx-deterministic</a> (2025) brings batch-invariant operations to MLX.</li>
      <li>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.</li>
    </ul>
  </li>
</ul>

<h2 id="7-reproducing">7. Reproducing</h2>

<p>The scripts live in the source tree:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>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
</code></pre></div></div>

<p>Real checkpoints (section 3), with Gemma 2 run separately because batching it fails in mlx-lm itself:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>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
</code></pre></div></div>

<p>Serving, once per mode:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>python experiments/server_identity.py
python experiments/server_identity.py --exact
</code></pre></div></div>

<p>To use exact mode in your own code:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">mlx_exact</span>
<span class="n">mlx_exact</span><span class="p">.</span><span class="n">enable</span><span class="p">()</span>      <span class="c1"># then use mlx-lm as usual
</span></code></pre></div></div>

<p><a href="https://github.com/audenvenn/mlx-exact/tree/v0.13.1/experiments"><code class="language-plaintext highlighter-rouge">experiments/</code></a> 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. <a href="https://github.com/audenvenn/mlx-exact/blob/v0.13.1/docs/numerics.md"><code class="language-plaintext highlighter-rouge">docs/numerics.md</code></a> has the full analysis.</p>

<hr />

<p><em>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.</em></p>]]></content><author><name>Auden Venn</name></author><summary type="html"><![CDATA[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></entry><entry><title type="html">A CuTe layout is additive up to carries</title><link href="https://audenvenn.github.io/2026/11/21/layouts-and-carries.html" rel="alternate" type="text/html" title="A CuTe layout is additive up to carries" /><published>2026-11-21T06:00:00+00:00</published><updated>2026-11-21T06:00:00+00:00</updated><id>https://audenvenn.github.io/2026/11/21/layouts-and-carries</id><content type="html" xml:base="https://audenvenn.github.io/2026/11/21/layouts-and-carries.html"><![CDATA[<p><em>About the preprint <a href="https://github.com/audenvenn/layouts-and-carries">Layouts and Carries: A Mathematical Foundation for the CuTe Layout Algebra</a> (Auden Venn, 2026), which has not been peer-reviewed. The repository has the paper, a Lean 4 formalisation of its core results, and the programs that check the theory and compare it with three CuTe implementations.</em></p>

<h2 id="short-version">Short version</h2>

<p>CuTe, the core of NVIDIA’s CUTLASS, describes how tensors, threads and hardware instructions index memory with <em>layouts</em>, nested (shape, stride) pairs. It manipulates them with an algebra of partial operations: coalesce, composition, complement, logical division and product. The operations are specified by post-conditions and guarded by divisibility checks. The paper shows that the algebra is governed by one identity: a layout is additive up to carries, and each carry is charged a jump.</p>

<p><img src="/assets/cute-carries.png" alt="Left: the padded layout (4,8):(1,5), whose function is x + ⌊x/4⌋, sends the indices 0 to 11 to the offsets 0 to 13 and skips the offsets 4 and 9, one for each carry into the second digit. Right: A = (3,4):(1,5) composed with B = (2,2):(1,2). The true offsets are 0, 1, 2, 5; the mode-by-mode result gives 0, 1, 2, 3, and offset 3 is padding." /></p>

<h2 id="the-identity">The identity</h2>

<p>A flat layout (s<sub>0</sub>, …, s<sub>m−1</sub>) : (d<sub>0</sub>, …, d<sub>m−1</sub>) is a function on 0 ≤ x &lt; N, where N = s<sub>0</sub>⋯s<sub>m−1</sub>. To evaluate it, write x in the mixed radix given by the shape, and take the inner product of its digits with the strides. Two quantities describe it:</p>
<ul>
  <li>the prefix products P<sub>i</sub> = s<sub>0</sub>⋯s<sub>i−1</sub>, the weights of the digits;</li>
  <li>the <em>jumps</em> γ<sub>i</sub> = d<sub>i</sub> − s<sub>i−1</sub>·d<sub>i−1</sub>, how far the stride of digit i departs from continuing the previous digit linearly.</li>
</ul>

<p>Then</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>f(x)     = x·d0 + Σ_i ⌊x / P_i⌋·γ_i
f(x + y) = f(x) + f(y) + Σ_i c_i(x, y)·γ_i
</code></pre></div></div>

<p>where c<sub>i</sub>(x, y), 0 or 1, is the carry into digit i when x and y are added in that radix. Here are three layouts of shape (4, 8), for 0 ≤ x &lt; 32:</p>
<ul>
  <li>row-major (4,8):(8,1) is 8x − 31⌊x/4⌋;</li>
  <li>padded (4,8):(1,5) is x + ⌊x/4⌋: every carry into the second digit skips one offset;</li>
  <li>column-major (4,8):(1,4) has no jump, and is just x.</li>
</ul>

<h2 id="what-follows-from-it">What follows from it</h2>

<p><strong>Which functions are layouts.</strong> Every function that vanishes at 0 has a unique expansion Σ<sub>Q</sub> γ<sub>Q</sub>⌊x/Q⌋. It is a layout function exactly when the scales Q ≥ 2 that occur form a divisibility chain and divide N. Coalescing drops the zero jumps. That gives the normal form, and an algorithm that recognises layouts.</p>

<p><strong>Composition.</strong> If A∘B exists, nothing is left to choose: its strides are A evaluated at the strides of B. Whether that <em>naive composite</em> is right is decided by a <em>carry defect</em>. Write B’s value at the coordinate (k<sub>0</sub>, k<sub>1</sub>, …) as Σ<sub>j</sub> k<sub>j</sub>·r<sub>j</sub> and add it up in A’s radix by the schoolbook method; the defect counts the carries that occur, each weighted by A’s jump at that scale. A∘B exists exactly when the defect vanishes for some subdivision of B’s modes.</p>

<p>For some A this becomes a simple inequality. Take B = (t<sub>0</sub>, …):(r<sub>0</sub>, …), and suppose A’s non-zero jumps all have the same sign, as for row-major, column-major and padded layouts. Then the test is one inequality per scale P of A that carries a non-zero jump, possibly after B’s modes are subdivided:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Σ_j (t_j − 1)·(r_j mod P) &lt; P
</code></pre></div></div>

<p>CuTe’s stride and shape divisibility conditions cover a special case: strides with a single non-zero digit that divides the size of its mode.</p>

<p><strong>Complements and division.</strong> A layout and its complement form a direct-sum decomposition of an interval, a classical subject (Krasner factorisations). The paper uses Long’s 1967 formulation; de Bruijn (1956) treated the analogous question for all natural numbers. So the divisibility condition for a complement is not a limitation of the layout form: any set has to meet it. Logical division has an exact criterion as well. Dividing A by a tile B means composing A with B and B’s complement, which together form a compact layout: a bijection onto A’s index range. Provided B has such a complement, the composite exists exactly when every scale at which A has a non-zero jump is comparable, under divisibility, with every scale of this tiling.</p>

<p><strong>Other codomains.</strong> The results on normal forms and composition hold for strides in any abelian group. That covers negative strides, coordinate-valued layouts, and XOR-based layouts like Triton’s linear layouts. Triton’s composition is always defined, because intermediate values are combined by XOR, which has no carries. CuTe adds integers, which do carry.</p>

<p><strong>Swizzles.</strong> Offsets have two additions, integer + and XOR, and they differ exactly by the carries of the binary radix. A swizzle, such as CuTe’s Swizzle&lt;B,M,S&gt; that XORs one bit field into another, is a layout for XOR. The paper does three things here:</p>
<ul>
  <li>it characterises when a swizzled layout with offset 0 is XOR-linear;</li>
  <li>it gives a closed-form criterion for a slice of a swizzled layout whose inner layout is bit-disjoint to decay to an ordinary layout;</li>
  <li>it states conditions under which CuTe’s operations on swizzled layouts are valid.</li>
</ul>

<p>For example, take Swizzle&lt;1,1,1&gt; ∘ (4,2):(1,4) and fix the second coordinate to 1. The offsets are 6, 7, 4, 5: the ordinary layout (2,2):(1,−2) plus 6. C++ CuTe returns exactly that.</p>

<h2 id="two-small-examples">Two small examples</h2>

<p>Both were checked against the implementations.</p>
<ul>
  <li><strong>A composite that comes out silently wrong.</strong>
    <ul>
      <li>A = (3,4):(1,5) is a 3×4 column-major matrix with two padding slots after each column: f(x) = x + 2⌊x/3⌋.</li>
      <li>B = (2,2):(1,2) views its first four elements as 2×2. The true offsets are 0, 1, 2, 5.</li>
      <li>C++ CuTe (with static integers) and PyCuTe return (2,2):(1,2), whose offsets are 0, 1, 2, 3. CUTLASS’s pycute rejects the call.</li>
      <li>At the last element, 1 + 2 = 3 crosses A’s scale 3, a carry that the mode-by-mode rule does not see. The true offset is 5; the returned one, 3, is a padding slot.</li>
    </ul>
  </li>
  <li><strong>A composable pair that is rejected.</strong>
    <ul>
      <li>A = (10,10,10):(d<sub>0</sub>, d<sub>1</sub>, d<sub>2</sub>) composed with B = 10:11 is 10:(d<sub>0</sub> + d<sub>1</sub>), whatever the strides. 11 has the base-10 digits (1, 1), and no multiple of it up to 9·11 = 99 carries.</li>
      <li>Since 11 and 10 do not divide each other, the three implementations reject the call. This was checked with the strides (3,50,700), where the answer is 10:53.</li>
      <li>With the strides (1,10,100), A coalesces to 1000:1 and the call is accepted.</li>
    </ul>
  </li>
</ul>

<h2 id="what-the-tests-say-about-implementations">What the tests say about implementations</h2>

<p>The repository compares the theory, on small synthetic layouts, with three implementations: C++ CuTe, CUTLASS’s Python implementation pycute, and the PyCuTe reference implementation. The criteria explain two kinds of discrepancy:</p>
<ul>
  <li>composites that come out silently wrong. This happens when modes of the inner layout interfere. In the C++ headers it also happens for some single-mode inner layouts, because the static stride check there is weaker than documented.</li>
  <li>composable pairs that are rejected.</li>
</ul>

<p>These tests show that the behaviours exist. They say nothing about how often the behaviours occur in real kernels.</p>

<h2 id="what-is-machine-checked">What is machine-checked</h2>

<p>About 1,500 lines of Lean 4 with Mathlib, with no <code class="language-plaintext highlighter-rouge">sorry</code>, check the core results:</p>
<ul>
  <li>the floor-sum form;</li>
  <li>the carry identity;</li>
  <li>layouts as the carry-free additive maps;</li>
  <li>the existence and uniqueness of the ⌊x/Q⌋ expansion;</li>
  <li>the divisibility-chain criterion;</li>
  <li>the composition formula with its defect;</li>
  <li>the carry-free inequality for a fixed shape, in both directions;</li>
  <li>that a swizzle (one bit field, right shift) is an involution and XOR-linear.</li>
</ul>

<p>Everything else, including the exact composition theorem, complements, division and the rest of the swizzle section, has paper proofs, validated by exhaustive and randomised programs. Section 9 of the paper lists which statement rests on what.</p>

<h2 id="what-is-new">What is new</h2>

<p>The normal-form theorem for coalesce and the existence of complements were known and are cited in the paper. New are the carry identity as an organising principle, the chain criterion, the exact criteria for composition and division, and the treatment of swizzles.</p>

<hr />

<p><em>Disclosure, from the paper’s acknowledgments: This work was carried out with substantial assistance from an AI system (Claude, developed by Anthropic), which, under the author’s direction, surveyed the literature, proposed and developed the framework, wrote the proofs, the Lean formalisation and the test programs, and drafted the manuscript. Drafts were independently reviewed by a second AI system (Codex, developed by OpenAI), which found a number of errors that have been corrected and contributed several examples and counterexamples. The author takes responsibility for the content. The AI systems are not authors.</em></p>

<p><em>This post was also written with an AI assistant.</em></p>]]></content><author><name>Auden Venn</name></author><summary type="html"><![CDATA[About the preprint Layouts and Carries: A Mathematical Foundation for the CuTe Layout Algebra (Auden Venn, 2026), which has not been peer-reviewed. The repository has the paper, a Lean 4 formalisation of its core results, and the programs that check the theory and compare it with three CuTe implementations.]]></summary></entry><entry><title type="html">Same prompt, different answer: MLX’s output depends on how the work is scheduled</title><link href="https://audenvenn.github.io/2026/11/20/mlx-output-depends-on-schedule.html" rel="alternate" type="text/html" title="Same prompt, different answer: MLX’s output depends on how the work is scheduled" /><published>2026-11-20T01:00:00+00:00</published><updated>2026-11-20T01:00:00+00:00</updated><id>https://audenvenn.github.io/2026/11/20/mlx-output-depends-on-schedule</id><content type="html" xml:base="https://audenvenn.github.io/2026/11/20/mlx-output-depends-on-schedule.html"><![CDATA[<p><em>About <a href="https://github.com/audenvenn/mlx-exact/releases/tag/v0.8.0">mlx-exact 0.8.0</a> (MIT), a drop-in patch for MLX and mlx-lm on Apple silicon. Everything below was measured on an Apple M6, the only chip it is validated on, and every number comes from its README and <code class="language-plaintext highlighter-rouge">docs/numerics.md</code>.</em></p>

<h2 id="short-version">Short version</h2>

<p>In stock MLX 0.32.4 on an Apple M6, a token’s logits depend on how the computation was scheduled. The prompt can be prefilled in one go or in chunks; a token can come from prefill or from decode; a request can run alone or batched with others; speculative decoding verifies drafts in groups. Each of these picks different GPU kernels, and the kernels round differently. Under greedy decoding, that is enough to change final answers. Five common ways of running the same GSM8K prompts disagree on the final answer for 20–60% of the first 300 test problems, depending on the model:</p>

<p><img src="/assets/mlx-exact-gsm8k.png" alt="Share of the first 300 GSM8K problems whose greedy answer changes under five MLX schedules: 60% for Qwen3.5-0.8B-4bit, 51% for Qwen3-0.6B-4bit, 30% for Qwen3-0.6B-8bit, 20% for Qwen3-1.7B-4bit; with mlx-exact, none." /></p>

<table>
  <thead>
    <tr>
      <th>Model</th>
      <th>Stock accuracy across the 5 schedules</th>
      <th>Problems where at least two schedules disagree</th>
      <th>With mlx-exact</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Qwen3-0.6B-4bit</td>
      <td>45.7–48.7%</td>
      <td>154 / 300 (51%)</td>
      <td>same answer under every schedule</td>
    </tr>
    <tr>
      <td>Qwen3-0.6B-8bit</td>
      <td>62.3–65.3%</td>
      <td>90 / 300 (30%)</td>
      <td>same answer under every schedule</td>
    </tr>
    <tr>
      <td>Qwen3-1.7B-4bit</td>
      <td>77.7–80.0%</td>
      <td>59 / 300 (20%)</td>
      <td>same answer under every schedule</td>
    </tr>
    <tr>
      <td>Qwen3.5-0.8B-4bit</td>
      <td>41.0–43.7%</td>
      <td>179 / 300 (60%)</td>
      <td>same answer under every schedule</td>
    </tr>
  </tbody>
</table>

<p>The five schedules are the whole prompt prefilled at once, in chunks of 64 or of 16 tokens, and batches of 4 or of 8. Aggregate accuracy moves by at most 3 points, which is not significant, because the flips go both ways. Per problem, though, the answer depends on the schedule, and that noise lands on any paired comparison run on the same problems.</p>

<p>This isn’t run-to-run randomness. MLX gives the same output for the same schedule every time; what changes the output is the schedule.</p>

<h2 id="why-it-happens">Why it happens</h2>

<p>MLX picks the kernel for a 4-bit matmul from the matrix shape:</p>
<ul>
  <li>one row goes to <code class="language-plaintext highlighter-rouge">qmv</code>;</li>
  <li>small batches go to <code class="language-plaintext highlighter-rouge">qmv_wide</code>;</li>
  <li>medium sizes go to split-K kernels with 2–16 partitions;</li>
  <li>large sizes go to the GPU’s matrix-accelerator kernel.</li>
</ul>

<p>These kernels differ in two ways. Matrix-matrix kernels round each dequantized weight to bf16/fp16 before multiplying, and vector kernels don’t. And each kernel sums in its own order. Attention also switches kernels with the number of queries, and its fixed key blocks mean that left padding in a batch changes the summation order too.</p>

<h2 id="where-it-shows-up">Where it shows up</h2>

<p>Measured on the same M6 with MLX 0.32.4 and mlx-lm 0.32.2:</p>
<ul>
  <li><strong>Recomputation.</strong> Greedy decoding with a KV cache diverges from recomputing the sequence at token 30 (Qwen3) or token 2 (Qwen3.5).</li>
  <li><strong>Speculative decoding.</strong> Greedy speculative decoding (Qwen3-1.7B with a 0.6B draft) matches plain decoding on 1 of 5 prompts.</li>
  <li><strong>Batching.</strong> A batched prompt matches the same prompt run alone on 1 of 4 prompts.</li>
  <li><strong>On-policy RL.</strong> The sampler and the trainer compute different log-probabilities, so “on-policy” training runs slightly off-policy: 0 of 64 sampled tokens had identical log-probs, with a mean difference of about 0.05 nats per token (LoRA, Qwen3-0.6B-4bit).</li>
</ul>

<p>With mlx-exact, all of these are identical: 5 / 5, 4 / 4 and 64 / 64.</p>

<h2 id="what-mlx-exact-does">What mlx-exact does</h2>

<p>It takes the arithmetic MLX already uses for long prefills as canonical, and makes every other schedule compute that same function, bit for bit:</p>
<ul>
  <li><strong>Accumulation order.</strong> The accelerator’s order was reconstructed with crafted inputs and validated against the hardware.</li>
  <li><strong>Rerouting.</strong> Every matmul that MLX would send to a different kernel goes to one that reproduces the canonical result. Where possible, that is MLX’s own kernel (vendored, MIT) run with a smaller tile.</li>
  <li><strong>Attention.</strong> Since 0.8.0, exact attention for head dims 64, 96 and 128 calls MLX’s own fused attention kernel directly. Each sequence’s keys are read from its first valid key, so a row of a left-padded batch sees the same keys, in the same blocks, as the sequence alone.</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">mlx_exact</span>
<span class="kn">from</span> <span class="nn">mlx_lm</span> <span class="kn">import</span> <span class="n">load</span><span class="p">,</span> <span class="n">generate</span>

<span class="n">mlx_exact</span><span class="p">.</span><span class="n">enable</span><span class="p">()</span>                     <span class="c1"># before or after load()
</span><span class="n">model</span><span class="p">,</span> <span class="n">tokenizer</span> <span class="o">=</span> <span class="n">load</span><span class="p">(</span><span class="s">"mlx-community/Qwen3-1.7B-4bit"</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">generate</span><span class="p">(</span><span class="n">model</span><span class="p">,</span> <span class="n">tokenizer</span><span class="p">,</span> <span class="s">"Hello"</span><span class="p">,</span> <span class="n">max_tokens</span><span class="o">=</span><span class="mi">50</span><span class="p">))</span>
</code></pre></div></div>

<p>Install with <code class="language-plaintext highlighter-rouge">pip install "mlx-exact[lm] @ git+https://github.com/audenvenn/mlx-exact@v0.8.0"</code> (not on PyPI).</p>

<h2 id="what-it-costs">What it costs</h2>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>mlx-exact vs stock MLX (Apple M6)</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Single-sequence decode</td>
      <td>0.93–0.98× across the tested models (0.95× for Qwen3-0.6B-4bit in 0.8.0)</td>
    </tr>
    <tr>
      <td>Batched decode (Qwen3-0.6B-4bit, 8 sequences)</td>
      <td>0.89× (0.35–0.45× before 0.8.0)</td>
    </tr>
    <tr>
      <td>Speculative decoding</td>
      <td>0.78–0.83×</td>
    </tr>
    <tr>
      <td>Chunked prefill, 4-bit, chunks of 16–128 tokens</td>
      <td>1.4–1.8× (faster: MLX’s own accelerator kernel with a 16-row tile beats the kernels stock MLX picks at those sizes)</td>
    </tr>
    <tr>
      <td>Chunked prefill, unquantized bf16, chunks of 16–512</td>
      <td>0.73–0.98×</td>
    </tr>
    <tr>
      <td>One-shot prefill</td>
      <td>1.00×</td>
    </tr>
  </tbody>
</table>

<h2 id="limits">Limits</h2>

<ul>
  <li><strong>Validated environment:</strong> MLX 0.32.4 and mlx-lm 0.32.2 on an Apple M6 only. <code class="language-plaintext highlighter-rouge">enable()</code> refuses other environments unless forced, because the kernel-dispatch replica is version- and chip-specific.</li>
  <li><strong>Formats:</strong> bf16/fp16, and 4- and 8-bit affine quantization with group size 64. fp32, and mxfp4 (the released gpt-oss checkpoints), fall back to stock MLX with a warning.</li>
  <li><strong>Architectures:</strong> 17 mlx-lm architectures pass a tiny random-weight sweep, plus Qwen3, Qwen3.5 and Qwen3-MoE. Not exact: DeepSeek-V3-style MLA, some MoE router gates that use raw matmuls, and batched sliding-window attention.</li>
</ul>

<p>Not claimed here: other chips or MLX versions, large MoE models end to end (only kernel timings at Qwen3-30B-A3B shapes), better accuracy (exact mode’s per-matmul error is slightly higher than stock decode’s, negligible next to 4-bit quantization), or speed beyond the table above. The README lists the remaining limits in full.</p>

<h2 id="reproduce-it">Reproduce it</h2>

<p><code class="language-plaintext highlighter-rouge">experiments/gsm8k_schedule_noise.py</code> reruns the GSM8K comparison, stock MLX against mlx-exact, in the same run. <code class="language-plaintext highlighter-rouge">pytest tests/</code> checks the kernels, attention and end-to-end decode against prefill.</p>

<hr />

<p><em>Disclosure: I maintain mlx-exact. It was developed with AI assistance (Anthropic’s Claude), and 0.8.0 had an independent pre-release review by another AI model (OpenAI’s Codex). This post was also written with an AI assistant; every number comes from the project’s README.</em></p>]]></content><author><name>Auden Venn</name></author><summary type="html"><![CDATA[About mlx-exact 0.8.0 (MIT), a drop-in patch for MLX and mlx-lm on Apple silicon. Everything below was measured on an Apple M6, the only chip it is validated on, and every number comes from its README and docs/numerics.md.]]></summary></entry><entry><title type="html">On a 24 GB Mac, ~2-bit Qwen3.6-35B drops its tool-call tag</title><link href="https://audenvenn.github.io/2026/11/17/qwen36-35b-2bit-drops-tool-call-tag.html" rel="alternate" type="text/html" title="On a 24 GB Mac, ~2-bit Qwen3.6-35B drops its tool-call tag" /><published>2026-11-17T01:10:00+00:00</published><updated>2026-11-17T01:10:00+00:00</updated><id>https://audenvenn.github.io/2026/11/17/qwen36-35b-2bit-drops-tool-call-tag</id><content type="html" xml:base="https://audenvenn.github.io/2026/11/17/qwen36-35b-2bit-drops-tool-call-tag.html"><![CDATA[<p><em>Measured with <a href="https://github.com/audenvenn/solvetime">solvetime</a>, an open benchmark that scores local LLM setups by coding-agent tasks solved and time to solution, not tokens per second.</em></p>

<h2 id="short-version">Short version</h2>

<p>On a Mac with 24 GB, the builds of Qwen3.6-35B-A3B that fit in memory are about 2-bit. At 2 bits the model often writes a tool call without its opening <code class="language-plaintext highlighter-rouge">&lt;tool_call&gt;</code> token, and a server that parses strictly hands the agent plain text instead of a command. Over 32 coding-agent attempts per build:</p>

<table>
  <thead>
    <tr>
      <th>Build</th>
      <th>Bits</th>
      <th>Tasks solved (95% CI)</th>
      <th>Attempts lost to malformed replies</th>
      <th>Core set, 16 attempts</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>kapitsa 0.2.36 (release)</td>
      <td>2.48</td>
      <td>19/32 (42-74%)</td>
      <td>13/32</td>
      <td>6.6 min (failures end early)</td>
    </tr>
    <tr>
      <td>kapitsa main 7445a6c, with a parser fallback</td>
      <td>2.48</td>
      <td>28/32 (72-95%)</td>
      <td>0/32</td>
      <td>13.5 min</td>
    </tr>
    <tr>
      <td>llama.cpp 0.9.0, unsloth UD-IQ2_XXS</td>
      <td>2.42</td>
      <td>23/32 (55-84%)</td>
      <td>5/32</td>
      <td>12.7 min</td>
    </tr>
    <tr>
      <td>raceline, 4-bit, experts read from the SSD (the author’s engine)</td>
      <td>4.06</td>
      <td>30/32 (80-98%)</td>
      <td>0/32</td>
      <td>19.6 min</td>
    </tr>
  </tbody>
</table>

<h2 id="what-the-failure-looks-like">What the failure looks like</h2>

<p>After its thinking, the model writes the call without the opener:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&lt;function=bash&gt;
&lt;parameter=command&gt;
find / -name "main.py" 2&gt;/dev/null | head -20
&lt;/parameter&gt;
&lt;/function&gt;
&lt;/tool_call&gt;
</code></pre></div></div>

<p>The server finds no tool call and returns this as <code class="language-plaintext highlighter-rouge">content</code> with <code class="language-plaintext highlighter-rouge">finish_reason: "stop"</code>. The agent (mini-swe-agent 2.4.6 here) tells the model its reply had no command and gives up after three such replies in a row. It comes from the weights, not from one server. With a seeded request, llama.cpp drops the opener on 8 of 10 seeds, deterministically for a given seed. kapitsa’s developers logged every token the model sampled on these replies, and <code class="language-plaintext highlighter-rouge">&lt;tool_call&gt;</code> was never among them.</p>

<h2 id="the-fix-is-on-the-parsing-side">The fix is on the parsing side</h2>

<p>The model’s intent is unambiguous: the function name, its parameters and the closing tag are all there. A server can accept a reply that is one well-formed <code class="language-plaintext highlighter-rouge">&lt;function=…&gt;…&lt;/function&gt;&lt;/tool_call&gt;</code> call to a tool the request declared, and leave everything else as text. We reported it to kapitsa with a repro (<a href="https://github.com/nace-ai/kapitsa/issues/1277">nace-ai/kapitsa#1277</a>), and they merged such a fallback the same day. On the same weights, tasks solved went from 19 to 28 of 32 (p = 0.022), with no attempt lost to the missing tag. For llama.cpp the related issue is <a href="https://github.com/ggml-org/llama.cpp/issues/30118">ggml-org/llama.cpp#30118</a>.</p>

<h2 id="a-synthetic-speed-test-pointed-the-wrong-way">A synthetic speed test pointed the wrong way</h2>

<p>raceline keeps the model at 4 bits on 24 GB by keeping some of its experts on the SSD. In a synthetic test (a 4K-token prompt, then 512 tokens of code) it read prompts faster than the 2-bit builds (1268-1333 vs 1091 tok/s) and wrote faster too. In the agent it solved about as many tasks as the fixed kapitsa build (30 vs 28 of 32, which this sample can’t tell apart), but it took 1.45 times as long end to end.</p>

<p>The likely reason: each tool output adds a few hundred new tokens, and those route to most of the model’s 256 experts, so the 29% of experts raceline keeps on the SSD are read again for every such chunk. Its prompt reading during the runs was 420 tok/s (306 with a smaller expert cache) against kapitsa’s 925. The synthetic prompt spread that cost over 4,000 tokens. Measure the workload you will actually run.</p>

<p><em>Update, 17 November: a defect in solvetime, since fixed, held about 3.5 GB of memory during every run. raceline reads the experts it doesn’t cache through macOS’s file cache, which that memory squeezed, so the 1.45x gap may be smaller than measured; it wasn’t remeasured. A second finding pulls the other way: agents’ whole-disk <code class="language-plaintext highlighter-rouge">find /</code> scans, also removed since, cost both engines about the same time, and without them the gap is 1.58x. Details are on the <a href="https://github.com/audenvenn/solvetime/blob/main/published/2026-11-qwen3.6-35b-a3b-m6-24gb/README.md">results page</a>.</em></p>

<h2 id="how-it-was-measured">How it was measured</h2>

<ul>
  <li>16 small coding tasks (8 single-file, 8 closer to a working day), each with a hidden check the agent never sees; 2 attempts each, round-robin.</li>
  <li>mini-swe-agent 2.4.6 with one bash tool, the model card’s sampling, thinking on; 50 steps and 15 minutes per attempt.</li>
  <li>Each engine runs the build it picks for 24 GB with its default settings. llama.cpp, which picks none, gets the GGUF that kapitsa picks, as a control.</li>
  <li>The agent runs in a sandbox: it writes only in its task directory and has no network.</li>
  <li>All 128 attempts were replayed from their recorded commands and re-scored. All match.</li>
</ul>

<h2 id="limits">Limits</h2>

<p>One Mac (an M6 Mac mini), 32 attempts per build, one model so far. MTPLX’s 35B packs don’t fit 24 GB by its own catalog, and mlx-lm’s 4-bit weights exceed the memory Metal gives the GPU, so neither ran.</p>

<h2 id="results-from-your-mac">Results from your Mac</h2>

<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>pip <span class="nb">install </span>git+https://github.com/audenvenn/solvetime
solvetime doctor
solvetime run <span class="nt">--engine</span> kapitsa <span class="nt">--model</span> qwen3.6-35b-a3b <span class="nt">--set</span> core <span class="nt">--attempts</span> 2
solvetime submit results/
</code></pre></div></div>

<p>Results from M1 to M5 Macs and other memory sizes are what would make this useful. Every table, build hash, excluded run and raw trajectory is on the <a href="https://github.com/audenvenn/solvetime/blob/main/published/2026-11-qwen3.6-35b-a3b-m6-24gb/README.md">results page</a>.</p>

<hr />

<p><em>Disclosure: I maintain raceline, one of the engines measured. This article was written with an AI assistant (Claude); every number comes from the linked results page.</em></p>]]></content><author><name>Auden Venn</name></author><summary type="html"><![CDATA[Measured with solvetime, an open benchmark that scores local LLM setups by coding-agent tasks solved and time to solution, not tokens per second.]]></summary></entry><entry><title type="html">A Mac’s GPU slows down while it waits for the CPU</title><link href="https://audenvenn.github.io/2026/11/17/gpu-slows-down-while-it-waits.html" rel="alternate" type="text/html" title="A Mac’s GPU slows down while it waits for the CPU" /><published>2026-11-17T01:00:00+00:00</published><updated>2026-11-17T01:00:00+00:00</updated><id>https://audenvenn.github.io/2026/11/17/gpu-slows-down-while-it-waits</id><content type="html" xml:base="https://audenvenn.github.io/2026/11/17/gpu-slows-down-while-it-waits.html"><![CDATA[<p><em>Every number below is from one Mac mini (Apple M6, 12-core GPU, 24 GB, macOS 27.2), measured back to
back with the setting under test alternated. Sources: raceline issue #47, pull request #50,
<code class="language-plaintext highlighter-rouge">bench/hw/gpu_wait.mm</code>, <code class="language-plaintext highlighter-rouge">bench/results/gpu_keepalive_m6.txt</code>.</em></p>

<p><strong>Short version.</strong> When a GPU command buffer pauses to wait for the CPU, the GPU’s power management takes
the pause for idleness and lowers the GPU’s performance, so the work after each wait runs slower. An engine
that waits on the CPU many times per pass pays this every time. On the M6, a light kernel running on a
second command queue keeps the GPU up. In raceline it made single-token decoding of Qwen3.6-35B-A3B with its
experts on the SSD 27% faster (44.3 to 56.4 tokens/s). A 181-line program reproduces the effect without a
model: <code class="language-plaintext highlighter-rouge">bench/hw/gpu_wait.mm</code>.</p>

<p><strong>Who this may affect.</strong> Metal code that makes the GPU wait for the CPU, inside a command buffer (on an <code class="language-plaintext highlighter-rouge">MTLSharedEvent</code> the CPU signals) or between command buffers: engines that load mixture-of-experts weights on demand, samplers that run on the CPU between passes, and anything that hands work back and forth within a frame. We measured the first; the others follow the same pattern but were not measured.</p>

<h2 id="the-symptom-the-same-work-32-to-53-tokenss">The symptom: the same work, 32 to 53 tokens/s</h2>

<p>raceline runs Qwen3.6-35B-A3B and Qwen3.5-35B-A3B, mixtures of experts too large for a 24 GB Mac’s GPU
memory, by keeping most experts in memory and reading the rest from the SSD as each layer needs them. In
every mixture-of-experts layer, the GPU signals a shared event, a CPU thread reads the missing experts, and
the GPU waits for the CPU’s answer before it goes on. A decoding pass waits 40 times.</p>

<p>Single-token decoding, without drafts, varied from one session to the next on the same Mac, build and
settings. On a quiet evening Qwen3.5-35B-A3B decoded at 52.9 tokens/s (18.9 ms a pass); the next morning at
31.7 to 40.3 (25 to 31 ms). Several things were ruled out:</p>

<ul>
  <li><strong>The SSD.</strong> Random reads of an expert’s size (1.6 MB) ran at 4.2 GB/s one at a time and 7.4 to 7.8 GB/s
eight at a time, as on the first day.</li>
  <li><strong>The amount of work.</strong> The engine loaded exactly as many experts on both days (15,745).</li>
  <li><strong>The file cache.</strong> After the model’s pages were evicted (30 GB of other files read), four runs in a row
were equally slow, and the disk delivered every expert load each time.</li>
</ul>

<p>The cost appeared per pass, not per byte. Passes with several rows cost the same on both days, while
single-row passes cost 12 ms more.</p>

<h2 id="narrowing-it-down">Narrowing it down</h2>

<p>On a tiny test model, one handoff cost about 600 µs per layer inside the engine, against 52 µs for the bare
<code class="language-plaintext highlighter-rouge">MTLSharedEvent</code> round trip in a standalone program. Timestamps in the expert-cache thread put its own work
at about 5 µs. The time went into the GPU resuming after each wait, and most of all into the gaps between
passes: 2.5 ms of gap where a whole pass, with every expert in memory, takes 1.0 ms. Keeping the CPU thread
spinning instead of sleeping changed nothing. What changed everything was giving the GPU something to do
during the waits:</p>

<table>
  <thead>
    <tr>
      <th>Qwen3.6-35B-A3B, experts on disk, no drafts</th>
      <th>decoding</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>alone</td>
      <td>32.5 tokens/s</td>
    </tr>
    <tr>
      <td>with a light kernel running alongside on another queue (1024 threads)</td>
      <td>51.7 tokens/s</td>
    </tr>
    <tr>
      <td>the same with 4096 threads</td>
      <td>48.8 tokens/s</td>
    </tr>
  </tbody>
</table>

<p>On the tiny model the same light kernel made the passes 2.6 times faster.</p>

<h2 id="a-repro-without-a-model">A repro without a model</h2>

<p><code class="language-plaintext highlighter-rouge">bench/hw/gpu_wait.mm</code> runs the same pattern with no model. It builds a command buffer of “layers” of real
work, a number of small dispatches each, and after every layer the GPU hands over to the CPU. The CPU
answers from a spinning thread, either at once or after a set delay, and the program times three versions:</p>

<ul>
  <li><strong>work only:</strong> the same dispatches, with no handoffs;</li>
  <li><strong>handoffs:</strong> a GPU to CPU to GPU round trip after every layer;</li>
  <li><strong>+ keep-alive:</strong> the same, with a light kernel looping on a second queue the whole time.</li>
</ul>

<p>It prints the time per layer beyond the work and the CPU’s delay. On the M6, over two runs:</p>

<table>
  <thead>
    <tr>
      <th>The CPU answers</th>
      <th>lost per layer beyond the work and the delay</th>
      <th>with the keep-alive</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>at once</td>
      <td>43 to 68 µs</td>
      <td>38 to 64 µs</td>
    </tr>
    <tr>
      <td>after 100 to 300 µs (about an SSD read)</td>
      <td>79 to 102 µs</td>
      <td>50 to 67 µs</td>
    </tr>
  </tbody>
</table>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>clang++ -std=c++20 -O2 -fobjc-arc -framework Metal -framework Foundation \
  -o build/hw/gpu_wait bench/hw/gpu_wait.mm
build/hw/gpu_wait            # delays of 0, 100 and 300 µs
</code></pre></div></div>

<p>The longer the CPU takes, the more the GPU loses on top of the wait itself. That is the signature of a GPU
that clocks down while it is idle, and it hits hardest exactly when the CPU is doing real work, such as
reading from a disk.</p>

<h2 id="the-fix">The fix</h2>

<p>raceline’s expert cache now keeps such a kernel running back to back, on a command queue of its own, while
requests come in, and lets it stop 50 ms after the last one (<code class="language-plaintext highlighter-rouge">RACELINE_GPU_KEEPALIVE=0</code> turns it off). The
kernel is <code class="language-plaintext highlighter-rouge">kernels/keepalive.metal</code>: 1024 threads, a few hundred multiply-adds each, eight dispatches per
command buffer. It shares no memory with the model, so what the model computes does not change; the tests
that require bit-identical output in every mode still pass.</p>

<p>Measured with the keep-alive on and off alternated:</p>

<table>
  <thead>
    <tr>
      <th>Qwen3.6-35B-A3B, experts on disk</th>
      <th>keep-alive</th>
      <th>without</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>24 GB Mac, no drafts</td>
      <td>56.1 / 56.6 tokens/s</td>
      <td>44.2 / 44.4</td>
    </tr>
    <tr>
      <td>the same, with its MTP drafts</td>
      <td>121.8 / 122.0</td>
      <td>116.0 / 116.4</td>
    </tr>
    <tr>
      <td>as a 16 GB Mac would run it (5.79 GB of experts in memory), no drafts</td>
      <td>24.1</td>
      <td>15.6</td>
    </tr>
    <tr>
      <td>the same, with drafts</td>
      <td>30.1</td>
      <td>28.2</td>
    </tr>
  </tbody>
</table>

<p>Drafts gain less: a drafted pass waits as often, 40 times, but yields several tokens, and the 256 tokens
took 57 passes instead of 256. Prompt processing barely moved: 1,096 to 1,105 tokens/s on a 1,024-token
prompt with the keep-alive, 1,057 to 1,089 without.</p>

<p>Dense models do not wait on the CPU inside a pass, and for them the extra kernel only competes for the GPU:
Qwen3.5-9B read a prompt at 997 tokens/s with it against 1,119 without, and decoded at 30.9 against 31.9.
raceline leaves them alone.</p>

<h2 id="what-we-do-not-know">What we do not know</h2>

<ul>
  <li><strong>One machine.</strong> Whether other Apple GPUs (M1 to M5, Pro, Max) behave the same, and by how much, is open.
<code class="language-plaintext highlighter-rouge">bench/hw/gpu_wait.mm</code> needs only Xcode’s command-line tools; results from other Macs are welcome on the
repository.</li>
  <li><strong>Power.</strong> A GPU kept from idling draws more power. We did not measure how much, and for an engine on
battery, that trade may not pay.</li>
  <li><strong>The mechanism.</strong> We see its effect from outside. We have not read anything from Apple that describes
this behaviour, and the keep-alive is a workaround that works, not a documented interface.</li>
</ul>

<p>Code, raw output and the full investigation are in raceline (issue #47 and pull request #50). raceline is
now in maintenance mode, and this is one of the things it found along the way.</p>

<hr />

<p><em>Written with an AI assistant (Claude); the measurements and code are in the linked repository, and every number above comes from the files named at the top.</em></p>]]></content><author><name>Auden Venn</name></author><summary type="html"><![CDATA[Every number below is from one Mac mini (Apple M6, 12-core GPU, 24 GB, macOS 27.2), measured back to back with the setting under test alternated. Sources: raceline issue #47, pull request #50, bench/hw/gpu_wait.mm, bench/results/gpu_keepalive_m6.txt.]]></summary></entry></feed>