<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Vahana]]></title><description><![CDATA[Vahana]]></description><link>https://vahana.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6b0c5a854ac1475a8f10ef9f/3de01b0d-02fc-4e7a-ab0a-b1fa5b8ab3f1.png</url><title>Vahana</title><link>https://vahana.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 21:31:00 GMT</lastBuildDate><atom:link href="https://vahana.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Two machines, one AI conversation, bit for bit: lockstep LLM NPCs on a laptop GPU and an H100]]></title><description><![CDATA[On the left: my laptop's RTX 3050 Ti, a 4 GB consumer GPU. On the right: an NVIDIA H100 in a server. Both run the same open model (OLMoE-1B-7B) with random…]]></description><link>https://vahana.hashnode.dev/two-machines-one-ai-conversation-bit-for-bit-lockstep-llm-npcs-on-a-laptop-gpu-and-an-h100</link><guid isPermaLink="true">https://vahana.hashnode.dev/two-machines-one-ai-conversation-bit-for-bit-lockstep-llm-npcs-on-a-laptop-gpu-and-an-h100</guid><category><![CDATA[AI]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[GameDev]]></category><category><![CDATA[Machine Learning]]></category><dc:creator><![CDATA[Vahana]]></dc:creator><pubDate>Wed, 02 Dec 2026 05:01:26 GMT</pubDate><content:encoded><![CDATA[<p><img src="https://raw.githubusercontent.com/vahana-ai/Vahana/main/docs/lockstep.gif" alt="A laptop RTX 3050 Ti and an NVIDIA H100 run the same sampled NPC dialogue; the hashes match every turn" /></p>
<p>On the left: my laptop's RTX 3050 Ti, a 4 GB consumer GPU. On the right: an NVIDIA H100 in a server. Both run the same open model (OLMoE-1B-7B) with random sampling at temperature 0.8, playing Brannoc, a gruff village blacksmith, across ten turns of dialogue. Every turn, each machine prints a hash of every token it generated and every logit the model computed along the way.</p>
<p>The hashes match on every turn. Not "the text looks the same": every bit of every intermediate number is identical.</p>
<h2>Why that is normally impossible</h2>
<p>The same model on two different GPUs usually gives different answers. Floating-point addition is not associative, and every chip, driver and library sums things in its own order with its own fused instructions. The differences start in the last bit and grow; with sampling, one different token sends the whole conversation somewhere else.</p>
<p>That breaks things people want to build:</p>
<ul>
<li><strong>Lockstep multiplayer games.</strong> Strategy and fighting games send only player inputs and let every client simulate the world itself, so every client must compute exactly the same thing. An LLM character can't take part if each player's GPU makes it say something different.</li>
<li><strong>Benchmarks.</strong> The same model and the same harness give different scores on different machines.</li>
<li><strong>Verification.</strong> You can't check that a provider ran the model it claims by re-running it, because your re-run won't match anyway.</li>
</ul>
<h2>How Vahana does it</h2>
<p>Vahana is an open-source inference engine for Mixture-of-Experts models. It computes every operation with one fixed arithmetic on every CPU and GPU it supports (fixed summation order, fixed rounding points), and samples with an exact sampler built from basic IEEE operations and a SHA-256 counter. The result is a pure function of (weights, prompt, settings): the same bits on any machine.</p>
<p>In the demo, each turn's sampling seed comes from the game state (the turn number and the player's line), the way a lockstep game would derive it. Each machine then generates the NPC's answer on its own.</p>
<h2>What I measured (Vahana 1.5.0, installed from PyPI)</h2>
<ul>
<li><strong>Laptop GPU vs laptop CPU:</strong> in lockstep for all 10 turns.</li>
<li><strong>Laptop GPU vs H100:</strong> in lockstep for all 10 turns.</li>
<li><strong>Desync detection:</strong> a player whose seed differs at turn 4 is caught at turn 4 exactly. The NPC's line there differs ("I haven't heard of anyone being attacked, but I can't promise nothing." against "They are. The roads to the capital are safe.").</li>
</ul>
<p>The same property holds beyond games. This week, on the same laptop and the same H100:</p>
<ul>
<li><strong>Logprobs:</strong> the probability of every generated token and the top-5 alternatives are identical on the laptop CPU, the laptop GPU, the server CPU and the H100, for six model families. That matters for training models with reinforcement learning, where a mismatch between the engine that samples and the trainer that scores can make training collapse.</li>
<li><strong>Evaluations:</strong> lm-evaluation-harness, unmodified, run against Vahana's OpenAI-compatible server gives the same answer to every question (200 ARC-Easy questions, 30 GSM8K math problems with generated solutions) on the laptop CPU, the laptop GPU, the laptop GPU with 4 concurrent requests, and the H100. The H100 just does it about 18 times faster.</li>
</ul>
<h2>Try it</h2>
<pre><code class="language-bash">pip install "vahana[gpu]"            # omit [gpu] without an NVIDIA GPU
vahana pull allenai/OLMoE-1B-7B-0924
python examples/lockstep_npc.py models/OLMoE-1B-7B-0924 --device cuda --out gpu.jsonl
python examples/lockstep_npc.py models/OLMoE-1B-7B-0924 --device cpu  --out cpu.jsonl
python examples/lockstep_npc.py --compare gpu.jsonl cpu.jsonl
</code></pre>
<p>(The example script is in the repository; run it on two different machines and compare the two files.)</p>
<h2>Limits</h2>
<p>Latency: a 7B-parameter Mixture-of-Experts model answers in seconds on a laptop, which is fine for an NPC that talks between turns and too slow for one that talks every frame. Smaller models fit tighter budgets, and the same exactness applies to all of them.</p>
<p>Everything here is reproducible from the repository: the logs behind the GIF, the scripts and the results are in <code>experiments/</code> (<code>i4_lockstep</code>, <code>d6_eval</code>, <code>d8_logprobs</code>).</p>
<p>Code (Apache-2.0): <a href="https://github.com/vahana-ai/Vahana">https://github.com/vahana-ai/Vahana</a></p>
]]></content:encoded></item><item><title><![CDATA[How a CPU and a GPU agree bit for bit: the twin dot-product rule]]></title><description><![CDATA[Originally published on dev.to. If you add the same numbers in a different order, floating-point gives you a different answer. A CPU and a GPU almost never…]]></description><link>https://vahana.hashnode.dev/how-a-cpu-and-a-gpu-agree-bit-for-bit-the-twin-dot-product-rule</link><guid isPermaLink="true">https://vahana.hashnode.dev/how-a-cpu-and-a-gpu-agree-bit-for-bit-the-twin-dot-product-rule</guid><category><![CDATA[Machine Learning]]></category><dc:creator><![CDATA[Vahana]]></dc:creator><pubDate>Tue, 01 Dec 2026 16:55:33 GMT</pubDate><content:encoded><![CDATA[<p><em>Originally published on <a href="https://dev.to/vahana/how-a-cpu-and-a-gpu-agree-bit-for-bit-the-twin-dot-product-rule-11ch">dev.to</a>.</em></p>
<p>If you add the same numbers in a different order, floating-point gives you a different answer. A CPU and a GPU almost never add in the same order. So how can a CPU-only laptop and an H100 produce <strong>bit-identical</strong> logits for the same model and prompt?</p>
<p>Vahana does it with one rule for every dot product. I call it the "twin" rule, because each kernel has a twin on the other device that does exactly the same arithmetic. This post explains the rule, shows why it gives identical bits by construction, and lists what it cost, with numbers from the repo's experiment files and one check I ran on my laptop today.</p>
<h2>The rule</h2>
<p>Every dot product <code>y = sum_k w[k] * x[k]</code> is computed like this:</p>
<ol>
<li><strong>16 fp32 lanes.</strong> Lane <code>l</code> owns the elements <code>k = 16j + l</code>.</li>
<li><strong>Ascending order, fused multiply-add.</strong> Each lane walks its elements in ascending <code>j</code> and does <code>acc = fma(w[k], x[k], acc)</code>, one rounding per step.</li>
<li><strong>A fixed tree.</strong> The 16 lane sums are combined by halving: for <code>s = 8, 4, 2, 1</code>: <code>a[i] = a[i] + a[i+s]</code> for <code>i &lt; s</code>. The answer is <code>a[0]</code>.</li>
<li><strong>Fixed rounding points.</strong> The result is rounded to bf16 at the same places on every device.</li>
</ol>
<p>That's it. The point is not that this order is the most accurate one. The point is that it is <strong>one specific order</strong>, written down, and every implementation follows it exactly.</p>
<h2>Why this gives identical bits</h2>
<p>IEEE-754 defines <code>fma(a, b, c)</code> as the exact <code>a*b + c</code>, rounded once. Ordinary fp32 addition is also correctly rounded. So if two machines perform the same sequence of fma and add operations on the same inputs, they must get the same bits. There is nothing left for the hardware to choose.</p>
<p>What usually breaks this is that "the same sequence" is not actually the same: a BLAS library picks a blocking that depends on the CPU, a GPU kernel splits the sum across threads, the compiler fuses a multiply and an add on its own. The twin rule takes all those choices away.</p>
<p>In the CPU kernel (<code>src/vahana/csrc/cpu_moe.cpp</code>), a type called <code>V16</code> holds the 16 lanes, and it is implemented four ways:</p>
<ul>
<li><strong>AVX-512:</strong> one 512-bit register;</li>
<li><strong>AVX2 + FMA3:</strong> two 8-lane registers, lanes 0-7 and 8-15;</li>
<li><strong>ARM NEON:</strong> four 4-lane registers, using <code>vfmaq_f32</code>;</li>
<li><strong>scalar C:</strong> 16 floats and <code>std::fma</code>.</li>
</ul>
<p>The register width changes, but the arithmetic doesn't: lane 11 does the same fma chain on AVX-512 as on NEON or in plain C. The tree is one shared function:</p>
<pre><code class="language-cpp">static inline float tree16(V16 v) {
  float a[16]; v_store(a, v);
  for (int s = 8; s &gt; 0; s &gt;&gt;= 1) for (int i = 0; i &lt; s; i++) a[i] = a[i] + a[i + s];
  return a[0];
}
</code></pre>
<p>On the GPU, the Triton twin (<code>_tree16</code> in <code>src/vahana/twinlin.py</code>) keeps a <code>(rows, 16)</code> fp32 accumulator, runs the same fma chain, and then reduces by reshaping to <code>(rows, 2, 8)</code> and summing the pair axis, then <code>(rows, 2, 4)</code>, and so on. Summing an axis of length 2 is a single add, so it is exactly <code>a[i] + a[i+8]</code>, then <code>a[i] + a[i+4]</code>: the same tree.</p>
<p>Two compiler rules keep it honest. Floating-point contraction is off everywhere (<code>-ffp-contract=off</code> and the equivalents in <code>csrc/build.py</code>), so the compiler can't fuse or split operations on its own. And <code>exp</code> is Vahana's own polynomial built from fmas (<code>dexp</code>), because every library's <code>exp</code> is a little different.</p>
<h2>The glue was the hard part</h2>
<p>Dot products are the easy half. A model also has norms, rotary embeddings, router softmax, activations and divisions, and those are where the devices disagreed in ways I didn't expect. From <code>experiments/p2_twin/README.md</code>, the first unit run matched only 26 of 43 glue ops. The causes:</p>
<ul>
<li><strong>Scalar division.</strong> PyTorch's CUDA backend computes <code>tensor / 3.0</code> as <code>tensor * (1/3.0)</code>, which rounds twice; the CPU divides once. Vahana now passes the divisor as a device tensor.</li>
<li><strong>sqrt.</strong> PyTorch's CUDA float32 <code>sqrt</code> is not correctly rounded: 3124 of 16000 random inputs differed from the CPU's correct result. The twin <code>sqrt</code> is computed in float64 and rounded to float32, which gives the correctly rounded answer.</li>
<li><strong>float64 to bf16</strong> is rounded differently on the two devices, so results now go float64 → float32 → bf16.</li>
</ul>
<p>After those fixes, the final unit file (<code>p2_unit.json</code>) shows glue 52/52 identical, attention 120/120 cases bit-identical CPU vs GPU, and every twin transcendental within 0.5 ulp of float64. A torch function mode (<code>TwinMode</code>) also audits every float op the model runs, and flags any op that is neither twinned nor known to be exact. For all 19 test cases the audit list is empty.</p>
<h2>The results</h2>
<p><strong>Every CPU instruction set, same hashes.</strong> <code>experiments/p1_portable_kernel/README.md</code> hashes the output of 8 kernel paths (raw experts, twin linear, compressed NX12 experts, a fused MoE job, gpt-oss activations with biases) on five builds: AVX-512, AVX2 and scalar on an H100 server's EPYC 9354, and AVX2 and scalar on my Ryzen 7 4800H laptop. Every path gives one hash across all five builds; for example, experts with one token hash to <code>8279cdb07591a881</code> everywhere.</p>
<p><strong>CPU-only equals GPU, for real models too.</strong> From <code>experiments/p2_twin/README.md</code>:</p>
<ul>
<li>19 of 19 test cases (17 MoE families plus gpt-oss and a width-96 Mixtral variant): a CPU-only run equals the H100's CUDA-graph run, ids and every step's logits, bit for bit.</li>
<li>The laptop, with no CUDA and no Triton, reproduced the H100's GPU logits for 19 of 19, under both the AVX2 and the plain-C builds.</li>
<li>On the real OLMoE-1B-7B checkpoint, CPU-only Vahana equals GPU Vahana for 4 prompts × 24 greedy tokens, and for the prefill logits of all 50 prompts (603 positions).</li>
</ul>
<p><strong>Every OS.</strong> <code>experiments/p3_portable/README.md</code>: the CI wheels for Linux x86-64, Linux arm64, macOS arm64 and Windows x86-64 run <code>vahana selftest</code> (18 tiny families, hashes compared with golden hashes recorded on the H100 GPU). All 4 platforms and 9 ISA builds gave 18/18. That was also the first time the NEON code ran on ARM, and it matched.</p>
<h2>A check on my laptop today</h2>
<p>To show why the rule has to be exact, I emulated it in Python (exact fp32 fma via <code>fractions</code>, correct round-to-nearest-even) on 32 rows of 2048 bf16-valued weights against a random fp32 vector, and compared it with small changes to the rule and with <code>torch</code> matmul. Ryzen 7 4800H, Windows, torch 2.10 CPU. The script is about 60 lines of NumPy and PyTorch; it is not in the repo, but I am happy to share it on request.</p>
<ul>
<li>8 lanes instead of 16 (same tree idea): <strong>29 of 32</strong> results differ from the twin rule.</li>
<li>16 lanes, but the lanes summed left to right instead of the tree: <strong>22 of 32</strong> differ.</li>
<li><code>torch</code> matmul: <strong>28 of 32</strong> differ. Its hash was the same at 1, 4 and 8 threads, so on this matrix-vector case torch's own result didn't depend on the thread count.</li>
<li>Ran twice: the twin hash was the same both times (<code>141470d7c15b5f8a</code>).</li>
</ul>
<p>None of these orders is "wrong". Against the exact sum, the largest relative error was 5.44e-06 for the twin rule, 2.75e-06 for 8 lanes, and 9.56e-06 for torch. The twin rule's accuracy is ordinary. What it gives you is that the same 16-lane, fixed-tree answer comes out on every device.</p>
<h2>What it costs</h2>
<p>Honest accounting from the same experiment files:</p>
<ul>
<li><strong>Kernel speed:</strong> the portable AVX-512 build is +0.2% against the pre-portable kernel (1.654/1.658 ms vs 1.650/1.654 ms per MoE layer call on real DeepSeek-V2 236B layers).</li>
<li><strong>GPU decode:</strong> Mixtral-8x7B at a 4 GB GPU budget, steady graph decode step 81.28/81.42 ms vs 80.26/79.59 ms before twin attention (two runs each), <strong>+1.8%</strong>.</li>
<li><strong>Eager work is slower:</strong> the eager decode step went from about 154 ms to about 223 ms (<strong>+45%</strong>), because TwinMode dispatches the glue ops in Python. Prefill and the families that can't use CUDA graphs pay this.</li>
<li><strong>Quality:</strong> on OLMoE, top-1 agreement with a stock fp32 run over 603 positions is 98.18% for the twin build, vs 98.01% before it and 98.51% for stock bf16. Exact does not mean closer to fp32 than stock bf16; it means the same everywhere.</li>
<li><strong>Not covered:</strong> the server's seeded sampler still uses stock torch on the host, so sampled output is reproducible on one machine but not yet across CPUs. Greedy decoding is exact.</li>
</ul>
<h2>Why it matters</h2>
<p>Once every device computes the same bits, where a layer runs stops mattering. Vahana can put experts on a GPU, in RAM or on disk, or run everything on the CPU, and the answer doesn't change. It also makes answers checkable: <code>vahana run --receipt</code> records a hash of every step's logits, and <code>vahana verify</code> recomputes them on a different machine and passes only on an exact match. That gets its own post.</p>
<p>Vahana is open source (Apache-2.0): <a href="https://github.com/vahana-ai/Vahana">https://github.com/vahana-ai/Vahana</a></p>
<pre><code class="language-bash">pip install vahana
vahana selftest
</code></pre>
<p>If you run <code>vahana selftest</code> on a CPU or OS I haven't listed, or you find a case where two devices disagree, please open an issue with the output. A mismatch report is the most useful thing you can send.</p>
]]></content:encoded></item><item><title><![CDATA[What does exactness cost? A fixed-order dot product vs the BLAS kernel, measured on a laptop CPU]]></title><description><![CDATA[Originally published on dev.to. In the last post I showed that one row of a matrix multiply gets different bits depending on the batch it is computed in…]]></description><link>https://vahana.hashnode.dev/what-does-exactness-cost-a-fixed-order-dot-product-vs-the-blas-kernel-measured-on-a-laptop-cpu</link><guid isPermaLink="true">https://vahana.hashnode.dev/what-does-exactness-cost-a-fixed-order-dot-product-vs-the-blas-kernel-measured-on-a-laptop-cpu</guid><category><![CDATA[Machine Learning]]></category><dc:creator><![CDATA[Vahana]]></dc:creator><pubDate>Tue, 01 Dec 2026 00:11:13 GMT</pubDate><content:encoded><![CDATA[<p><em>Originally published on <a href="https://dev.to/vahana/what-does-exactness-cost-a-fixed-order-dot-product-vs-the-blas-kernel-measured-on-a-laptop-cpu-1394">dev.to</a>.</em></p>
<p>In the <a href="https://dev.to/vahana/same-model-same-prompt-different-answer-where-llm-nondeterminism-really-comes-from-480m">last post</a> I showed that one row of a matrix multiply gets different bits depending on the batch it is computed in, because the library picks the summation order and it picks differently for different shapes. The fix I suggested was simple to state: choose one summation order for every dot product and use it everywhere.</p>
<p>The obvious objection is speed. BLAS libraries like Intel MKL are fast <em>because</em> they get to choose the order. So how much do you actually give up if you take that choice away?</p>
<p>I measured it on my laptop. Short answer: at batch size 1 the cost is about 1.3×. At batch size 64 it is about 8×, using a kernel I wrote in about 30 lines. Here is where those numbers come from and why they differ so much.</p>
<h2>The setup</h2>
<ul>
<li>Laptop: AMD Ryzen 7 4800H, Windows, Python 3.10, PyTorch 2.10 (CPU build, MKL backend, AVX2), Numba 0.61, 8 threads for both libraries.</li>
<li>Problem: a 4096×4096 fp32 weight matrix <code>W</code> (64 MiB) multiplied by a batch of <code>B</code> input rows, for B = 1, 8 and 64. That's the shape of one projection in a mid-sized transformer layer.</li>
<li>Baseline: <code>x @ W.T</code> in PyTorch, which calls MKL.</li>
<li>Challenger: a dot product with <strong>one fixed order</strong>, written in Numba.</li>
</ul>
<p>The fixed order is this. Split each 4096-long dot product into 16 lanes. Lane <code>j</code> adds up elements <code>j, j+16, j+32, …</code> in ascending order. Then the 16 lane totals are combined by a fixed pairwise tree: (0+1), (2+3), … then pairs of those, and so on, down to one number.</p>
<p>16 lanes isn't an arbitrary number: it maps naturally onto SIMD registers, so a CPU can run the lanes side by side without changing the order. Parallel threads are only allowed to split the work across <strong>outputs</strong>, never inside one sum. Every output value is therefore computed with the same sequence of roundings, whatever the batch size and however many threads there are.</p>
<p>The kernel:</p>
<pre><code class="language-python">@njit(parallel=True, fastmath=False)
def fixed_matmul(x, W, out):
    B, K = x.shape
    for n in prange(W.shape[0]):          # threads split OUTPUTS, never a sum
        for b in range(B):
            acc = np.zeros(16, np.float32)
            for c in range(0, K, 16):
                for j in range(16):
                    acc[j] += x[b, c + j] * W[n, c + j]
            w = 16
            while w &gt; 1:                  # fixed pairwise tree
                w //= 2
                for j in range(w):
                    acc[j] = acc[2 * j] + acc[2 * j + 1]
            out[b, n] = acc[0]
</code></pre>
<p><code>fastmath=False</code> matters: it stops the compiler from reordering the additions, which would defeat the whole purpose.</p>
<h2>First, does it actually give the same bits?</h2>
<p>Yes. Here is what the script printed:</p>
<ul>
<li>Fixed order, row 0 computed at batch 1, 8 and 64: <strong>same bits</strong> every time.</li>
<li>Fixed order, 1 thread vs 8 threads: <strong>same bits</strong>.</li>
<li>Fixed order in Numba vs the same order written with plain PyTorch elementwise ops: <strong>same bits</strong>. Two completely different implementations agree exactly, because they perform the same roundings in the same sequence.</li>
<li>MKL, row 0 at batch 8 vs batch 1: <strong>3,910 of 4,096</strong> values changed. The same at batch 64.</li>
</ul>
<p>One thing I expected and didn't see: MKL gave identical results at 1 thread and 8 threads on this machine (0 of 262,144 values changed). So on this CPU, with this build, the batch shape is what moves the bits, not the thread count. That may not hold on your machine; the script checks it.</p>
<h2>Is the fixed order less accurate?</h2>
<p>Slightly, but not in a way that matters. Against an fp64 reference:</p>
<ul>
<li>Fixed order: mean absolute error 1.49e-05, max 1.09e-04</li>
<li>MKL: mean absolute error 1.33e-05, max 8.93e-05</li>
</ul>
<p>MKL's error is about 11% smaller on average. Both are ordinary fp32 results. "Exact" here means reproducible, not more precise: the fixed order gives the same answer every time, and that answer is about as close to the true value as MKL's.</p>
<h2>The cost</h2>
<p>Best-of-N timings in milliseconds, three rounds each (all from the same run of the script at the end):</p>
<ul>
<li><strong>Batch 1:</strong> MKL 2.25–2.43 ms, fixed order 2.90–3.33 ms. Cost: <strong>1.25–1.37×</strong>.</li>
<li><strong>Batch 8:</strong> MKL 12.85–14.00 ms, fixed order 17.85–20.93 ms. Cost: <strong>1.34–1.63×</strong>.</li>
<li><strong>Batch 64:</strong> MKL 19.39–21.49 ms, fixed order 155.6–160.2 ms. Cost: <strong>7.5–8.0×</strong>.</li>
</ul>
<p>For comparison, the same fixed order written as a loop of PyTorch elementwise ops took 38.9 ms at batch 1. That's about 12× slower than the Numba kernel, with identical output bits. How you implement the order matters far more than the order itself.</p>
<p>(One run during development gave fixed-order timings that were much faster than these, and I couldn't reproduce them. I left that run out. The numbers above come from the clean script below and were consistent across three rounds. A second run of the published script, while the laptop was busier, was noisier: MKL itself slowed down in some rounds, and the batch-64 cost ranged from 3.7× to 7.0×. Laptop timings move around; the exactness lines were identical in every run.)</p>
<h2>Why batch 1 is cheap and batch 64 isn't</h2>
<p>At batch 1 the matrix multiply is really a matrix-vector product. Every weight is read once and used once. The 64 MiB of weights have to come from RAM, and reading them takes most of the time: 64 MiB in 2.25 ms is about 30 GB/s, which is about all this laptop's memory can deliver. The arithmetic is cheap by comparison, so how cleverly you order it hardly matters. The fixed-order kernel reads the same bytes, so it finishes in roughly the same time.</p>
<p>At batch 64 each weight is used 64 times. Now the arithmetic dominates, and MKL is very good at it. It loads a block of weights into registers once and reuses it across many rows, uses fused multiply-add instructions, and keeps every SIMD unit busy. That works out to about 110 GFLOP/s here. My kernel computes one output at a time and reaches about 14 GFLOP/s.</p>
<p>None of that speed comes from MKL's freedom to pick an order. It comes from reusing data in registers, which you can do within a fixed per-output order: the order only fixes how <em>one</em> sum is computed, not which outputs you work on together. I tried a quick tiled version in Numba (4 rows × 2 weight rows sharing each loaded chunk). It gave bit-identical results, but it wasn't faster, because Numba didn't vectorize it well. Closing that gap needs hand-written SIMD code, which I haven't done here. So read the 8× as "a naive kernel against one of the most heavily tuned libraries in existence", not as the price of exactness itself.</p>
<p>A side note that surprised me: MKL took about 13 ms at batch 8 and about 20 ms at batch 64. Eight times as many rows cost only 1.5× the time. Batch 8 is clearly not a shape MKL's fast path is tuned for. That's the other side of "the library picks the kernel by shape": performance jumps around with shape too, not just bits.</p>
<h2>Why this matters for LLM inference</h2>
<p>Generating one token for one user is the batch-1 case: memory-bound, every weight read once. That's exactly where a fixed order costs least. On this laptop it's roughly a third slower, from a naive kernel. Prefill, where a long prompt is processed in one go, and large server batches are the compute-bound cases, where a fixed-order kernel has to be engineered as carefully as a BLAS kernel to keep up.</p>
<p>So the honest summary is:</p>
<ul>
<li>Reproducible bits come from one rule: fix the order inside every dot product, and let parallelism split only the outputs.</li>
<li>With bandwidth as the bottleneck, that rule is nearly free.</li>
<li>With compute as the bottleneck, the rule itself doesn't cost much, but reaching BLAS speed under it takes real kernel work.</li>
</ul>
<h2>Reproduce it</h2>
<p>The full script prints every number in this post. Save it as <code>post02.py</code> and run <code>pip install torch numba numpy</code>, then <code>python post02.py</code>:</p>
<pre><code class="language-python">import time, numpy as np, torch, numba
from numba import njit, prange

LANES = 16

@njit(parallel=True, fastmath=False)
def fixed_matmul(x, W, out):
    B, K = x.shape
    for n in prange(W.shape[0]):
        for b in range(B):
            acc = np.zeros(LANES, np.float32)
            for c in range(0, K, LANES):
                for j in range(LANES):
                    acc[j] += x[b, c + j] * W[n, c + j]
            w = LANES
            while w &gt; 1:
                w //= 2
                for j in range(w):
                    acc[j] = acc[2 * j] + acc[2 * j + 1]
            out[b, n] = acc[0]

def fixed_torch(x, W):
    B, K = x.shape; N = W.shape[0]
    xs = x.view(B, K // LANES, LANES); Ws = W.view(N, K // LANES, LANES)
    acc = torch.zeros(B, N, LANES)
    for c in range(K // LANES):
        acc += xs[:, None, c, :] * Ws[None, :, c, :]
    while acc.shape[-1] &gt; 1:
        acc = acc[..., 0::2] + acc[..., 1::2]
    return acc[..., 0]

def fixed(x, W):
    out = np.empty((x.shape[0], W.shape[0]), np.float32)
    fixed_matmul(x, W, out); return out

def best_ms(f, reps):
    f(); ts = []
    for _ in range(reps):
        t0 = time.perf_counter(); f(); ts.append(time.perf_counter() - t0)
    return min(ts) * 1e3

numba.set_num_threads(8); torch.set_num_threads(8)
torch.manual_seed(0)
K = N = 4096
W = torch.randn(N, K); X = torch.randn(64, K)
Wn, Xn = W.numpy(), X.numpy()

f1, f8, f64 = fixed(Xn[:1], Wn), fixed(Xn[:8], Wn), fixed(Xn, Wn)
print("fixed, same bits at batch 1/8/64:",
      np.array_equal(f1[0], f8[0]) and np.array_equal(f1[0], f64[0]))
numba.set_num_threads(1); f64_1t = fixed(Xn, Wn); numba.set_num_threads(8)
print("fixed, 1 vs 8 threads same bits:", np.array_equal(f64_1t, f64))
print("fixed, Numba vs PyTorch same bits:",
      np.array_equal(fixed_torch(X[:8], W).numpy(), f8))
m1 = (X[:1] @ W.T)[0]
for B in (8, 64):
    print(f"MKL, values changed at batch {B}:", int(((X[:B] @ W.T)[0] != m1).sum()))
torch.set_num_threads(1); m1t = X @ W.T; torch.set_num_threads(8)
print("MKL, values changed 1 vs 8 threads:", int((m1t != X @ W.T).sum()))
ref = X.double() @ W.double().T
for name, o in (("fixed", torch.from_numpy(f64)), ("MKL", X @ W.T)):
    e = (o.double() - ref).abs()
    print(f"{name} error vs fp64: mean {e.mean():.2e} max {e.max():.2e}")

for rnd in range(3):
    for B in (1, 8, 64):
        xb = X[:B].contiguous(); xn = Xn[:B].copy(); o = np.empty((B, N), np.float32)
        r = 40 if B &lt; 64 else 10
        tm = best_ms(lambda: xb @ W.T, r)
        tf = best_ms(lambda: fixed_matmul(xn, Wn, o), r)
        print(f"round {rnd} batch {B}: MKL {tm:.2f} ms fixed {tf:.2f} ms cost {tf/tm:.2f}x")
print(f"pure-PyTorch fixed order, batch 1: {best_ms(lambda: fixed_torch(X[:1], W), 5):.1f} ms")
</code></pre>
<p>Your numbers will differ: a different CPU, memory speed or MKL version will move the timings and may move the batch size where MKL's bits change. If you run it, I'd like to see what you get, especially on ARM or AVX-512 machines.</p>
<p>I'm building Vahana, an open-source engine for exact MoE inference: github.com/vahana-ai/Vahana</p>
]]></content:encoded></item><item><title><![CDATA[Introducing Vahana: run MoE models bigger than your GPU, with the same bits on every device]]></title><description><![CDATA[Originally published on dev.to. My 4 GB laptop GPU runs a 30-billion-parameter model faster than llama.cpp, and the same laptop's CPU can check every…]]></description><link>https://vahana.hashnode.dev/introducing-vahana-run-moe-models-bigger-than-your-gpu-with-the-same-bits-on-every-device</link><guid isPermaLink="true">https://vahana.hashnode.dev/introducing-vahana-run-moe-models-bigger-than-your-gpu-with-the-same-bits-on-every-device</guid><dc:creator><![CDATA[Vahana]]></dc:creator><pubDate>Sun, 29 Nov 2026 17:15:45 GMT</pubDate><content:encoded><![CDATA[<p><em>Originally published on <a href="https://dev.to/vahana/introducing-vahana-run-moe-models-bigger-than-your-gpu-with-the-same-bits-on-every-device-4d67">dev.to</a>.</em></p>
<p>My 4 GB laptop GPU runs a 30-billion-parameter model faster than llama.cpp, and the same laptop's CPU can check every answer bit for bit. This post introduces the engine that does it: <strong>Vahana</strong>, open source under Apache-2.0.</p>
<p><img src="https://raw.githubusercontent.com/vahana-ai/Vahana/main/docs/demo.gif" alt="Generate an answer with Qwen3-30B on a 4 GB laptop GPU, then verify it bit for bit on the same laptop's CPU (real output of Vahana 1.4.0, waits sped up)" /></p>
<p><em>Real output, unedited, waits sped up: Qwen3-30B 4-bit answers on the laptop's RTX 3050 Ti (4 GB) and writes a receipt; then <code>vahana verify</code> recomputes every token's logits on the CPU and says PASS.</em></p>
<h2>The problem: big MoE models, small GPUs, and answers that don't reproduce</h2>
<p>Mixture-of-Experts models like Qwen3-30B-A3B, Mixtral or DeepSeek-V2 are huge on disk but only use a few experts per token. That makes them a good fit for ordinary hardware: keep attention and the most-used experts on the GPU, and the rest in RAM or on disk.</p>
<p>The catch is that once a model is split across a GPU and a CPU, the arithmetic is split too. GPU kernels and CPU kernels add numbers in different orders, so they round differently, and the output depends on where each expert happened to run. The same is true of batching: in most engines, a request's output changes with the requests batched around it (I measured this in my <a href="https://vahana.hashnode.dev/same-model-same-prompt-different-answer-where-llm-nondeterminism-really-comes-from">previous post</a>).</p>
<p>Vahana's answer to both is the same: <strong>fix the arithmetic, everywhere</strong>.</p>
<h2>What Vahana guarantees</h2>
<p>The same request gives <strong>bit-identical</strong> tokens and logits regardless of:</p>
<ul>
<li><strong>the machine:</strong> a CPU-only laptop and an H100 agree bit for bit, on Linux, Windows and macOS, on AVX-512, AVX2, ARM NEON or plain C;</li>
<li><strong>where the weights live:</strong> GPU, the GPU expert cache, RAM, or streamed from disk;</li>
<li><strong>what else is running:</strong> batching, continuous batching in the server, padding, speculative decoding, prefill vs decode.</li>
</ul>
<p>Not "close". The same bits. Every rule in the next section exists to make that true.</p>
<h2>How: one arithmetic rule, implemented twice</h2>
<p>Every dot product follows one rule: 16 fp32 FMA lanes accumulate in ascending order, a fixed reduction tree combines them, and bf16 rounding happens at the same points. That rule is implemented identically in C++ (AVX-512, AVX2, NEON, scalar) and in Triton for NVIDIA GPUs, so an expert gives the same bits on either device. Kernels reduce each row in an order that depends only on that row, so batch neighbours and padding can't move a rounding.</p>
<p>For 4-bit checkpoints, the product of a 4-bit weight and its group scale is exact in fp32, so the same rule carries over unchanged.</p>
<h2>Receipts: verifiable answers</h2>
<p>Because the bits don't depend on the machine, an answer can be checked by anyone with the same weights:</p>
<pre><code class="language-bash">vahana run    models/Qwen3-30B-A3B-w4a16 --prompt "..." --receipt answer.json
vahana verify answer.json --model models/Qwen3-30B-A3B-w4a16 --device cpu   # PASS or FAIL
</code></pre>
<p>A receipt records the prompt's token ids, the decoding settings, a fingerprint of the weights, the output tokens, and a SHA-256 of every step's logits. <code>vahana verify</code> recomputes all of it in one teacher-forced pass and passes only on an exact match. There is no tolerance. In the GIF, 48 tokens of Qwen3-30B check in 8.3 s on the laptop CPU.</p>
<h2>Does exactness cost speed? I measured it</h2>
<p>Against llama.cpp (b12494, Q4_K_M) on the same machines, each engine at its own tuned best setting, alternating runs:</p>
<ul>
<li><strong>Laptop, RTX 3050 Ti 4 GB, Qwen3-30B 4-bit:</strong> decode 1.57× faster on five real prompts (15.3 vs 9.7 tok/s) and 1.86× on the benchmark text (21.4 vs 11.6 tok/s); first token 2.8× sooner (2.9 vs 8.2 s).</li>
<li><strong>Free Colab T4:</strong> decode 1.96× on the benchmark text and 1.65× on real prompts; first token 3.4× sooner.</li>
<li><strong>16 GB Apple M4 (Vahana on the CPU, llama.cpp on Metal):</strong> decode 1.98× on the benchmark text and 5.4× on real prompts; first token 1.9× sooner.</li>
<li><strong>Mixtral-8x7B on a T4:</strong> decode about level; first token 2.0× sooner.</li>
<li><strong>Plain 2-core CPU (Kaggle), no GPU:</strong> <strong>llama.cpp is about 3.5× faster</strong> (7.91 vs 2.21 tok/s). llama.cpp's int8 dot products handle many weights per instruction; a fixed fp32 order can't.</li>
</ul>
<p>Quality, against the bf16 original on WikiText-2: the 4-bit checkpoint Vahana runs has a mean KL divergence of 0.065, vs 0.093 for Q4_K_M (both scored with llama.cpp's own statistics).</p>
<p>On a server: DeepSeek-Coder-V2 236B (438 GB) runs at 7.49 tok/s with a 16 GB GPU budget, and Qwen3-30B-A3B serves 64 requests at once at 130 tok/s aggregate, with every response bit-identical to running it alone. On the GPU, exactness costs +1.8% per decode step.</p>
<p>Every number above comes from a pre-registered experiment in the repo, including the bars it missed. The sources: <a href="https://github.com/vahana-ai/Vahana/blob/main/docs/benchmarks.md">docs/benchmarks.md</a>, <a href="https://github.com/vahana-ai/Vahana/blob/main/experiments/v15_decode/README.md">experiments/v15_decode</a>, <a href="https://github.com/vahana-ai/Vahana/blob/main/experiments/v15_quality/README.md">experiments/v15_quality</a>, and the one-command reproduction in <a href="https://github.com/vahana-ai/Vahana/blob/main/experiments/reproduce/README.md">experiments/reproduce</a>.</p>
<h2>Which models</h2>
<p>18 MoE families pass the exactness selftest. Real checkpoints are validated for Mixtral, DeepSeek-V2 (Lite and 236B), Qwen1.5-MoE, Qwen3-MoE, Qwen3.5-MoE and OLMoE; DeepSeek-V3, GLM-4-MoE, MiniMax-M2, gpt-oss (bf16 experts) and others are validated on the real architecture with tiny weights. Not yet supported: MXFP4 and FP8 checkpoints, Llama 4, DBRX. One NVIDIA GPU or none; Macs run on the CPU.</p>
<h2>Try it in five minutes</h2>
<pre><code class="language-bash">pip install torch "vahana[gpu]"     # omit [gpu] without an NVIDIA GPU
vahana selftest                     # does this machine give the reference bits?
hf download allenai/OLMoE-1B-7B-0924 --local-dir models/OLMoE-1B-7B-0924
vahana run models/OLMoE-1B-7B-0924 --prompt "The capital of France is" --max-tokens 16 --receipt answer.json
vahana verify answer.json --model models/OLMoE-1B-7B-0924 --device cpu
</code></pre>
<p>There's also an OpenAI-compatible server (<code>vahana serve ... --slots 32</code>) with continuous batching, where every response equals the same request run alone.</p>
<h2>Where I'd love help</h2>
<p>Run it on your machine and tell me what you get, especially where it loses. Speed numbers from other GPUs and CPUs, models that fail to load, and receipts that don't verify across machines are all exactly the reports I want.</p>
<ul>
<li>GitHub: <a href="https://github.com/vahana-ai/Vahana">https://github.com/vahana-ai/Vahana</a></li>
<li><code>pip install vahana</code></li>
</ul>
<p>Next posts: how the CPU and GPU kernels are made to agree bit for bit, and how the expert cache fits a 30B model in 4 GB.</p>
]]></content:encoded></item><item><title><![CDATA[Same model, same prompt, different answer: where LLM nondeterminism really comes from]]></title><description><![CDATA[Originally published on dev.to. Every number below comes from a script I ran on my laptop (PyTorch 2.10, CPU, 8 threads). The script is at the end, so you…]]></description><link>https://vahana.hashnode.dev/same-model-same-prompt-different-answer-where-llm-nondeterminism-really-comes-from</link><guid isPermaLink="true">https://vahana.hashnode.dev/same-model-same-prompt-different-answer-where-llm-nondeterminism-really-comes-from</guid><category><![CDATA[llm]]></category><category><![CDATA[Machine Learning]]></category><dc:creator><![CDATA[Vahana]]></dc:creator><pubDate>Sun, 29 Nov 2026 17:06:44 GMT</pubDate><content:encoded><![CDATA[<p><em>Originally published on <a href="https://dev.to/vahana/same-model-same-prompt-different-answer-where-llm-nondeterminism-really-comes-from-480m">dev.to</a>. Every number below comes from a script I ran on my laptop (PyTorch 2.10, CPU, 8 threads). The script is at the end, so you can run it on yours.</em></p>
<hr />
<p>Set temperature to 0. Send the same prompt to the same model twice. You'd expect the same answer twice. Often you don't get it, and not because of sampling. Greedy decoding is deterministic by definition: take the highest-scoring token, every time.</p>
<p>So where does the difference come from? Not from randomness. It comes from <strong>arithmetic order</strong>, and once you see it, it shows up everywhere.</p>
<h2>1. Floating-point addition doesn't care what you learned in school</h2>
<p>In real numbers, (a + b) + c = a + (b + c). In floating point it isn't guaranteed:</p>
<pre><code class="language-python">&gt;&gt;&gt; (0.1 + 0.2) + 0.3
0.6000000000000001
&gt;&gt;&gt; 0.1 + (0.2 + 0.3)
0.6
</code></pre>
<p>Every addition rounds to the nearest representable number, and <em>where</em> the rounding happens depends on the order. With three numbers the error is tiny. A transformer layer adds thousands of products for every output value.</p>
<p>Here are 200,000 random fp32 numbers summed three ways:</p>
<table>
<thead>
<tr>
<th>Order</th>
<th>Result</th>
</tr>
</thead>
<tbody><tr>
<td>Left to right</td>
<td>26.134367</td>
</tr>
<tr>
<td>Right to left</td>
<td>26.134922</td>
</tr>
<tr>
<td>Pairwise (NumPy)</td>
<td>26.135086</td>
</tr>
<tr>
<td>Exact (fp64)</td>
<td>26.135116</td>
</tr>
</tbody></table>
<p>Same numbers, three different answers. None of them is "wrong"; they're all legal fp32 results. They're just different.</p>
<h2>2. Your batch size changes the order</h2>
<p>You never choose the order of additions inside a matrix multiply: the library does. And libraries choose differently depending on the <strong>shape</strong> of the problem, because a different tiling or blocking is faster for a different shape.</p>
<p>The experiment: take one row <code>x</code>, multiply it by a 4096×4096 weight matrix, then do the same row again inside a batch of other rows, and compare only that row's result.</p>
<table>
<thead>
<tr>
<th>Batch the row was computed in</th>
<th>Bit-identical to batch of 1?</th>
<th>Output values that differ (of 4096)</th>
</tr>
</thead>
<tbody><tr>
<td>1, 2, 3</td>
<td>yes</td>
<td>0</td>
</tr>
<tr>
<td>8, 16, 32, 64</td>
<td><strong>no</strong></td>
<td><strong>3,993</strong></td>
</tr>
</tbody></table>
<p>Same row, same weights, same machine, same library. Put the row in a batch of 8 and 97% of its outputs change in the last bits (the largest difference was 0.00047). Somewhere between batch 3 and batch 8 the library switched to a different kernel path, and the reduction order changed with it.</p>
<p>This is why an inference server can give a different answer to <em>your</em> request depending on <strong>who else is using it at the same moment</strong>. Your request gets batched with strangers; the batch size changes the kernel; the kernel changes the order; the order changes the bits.</p>
<h2>3. "It's only the last bits", until it isn't</h2>
<p>Models usually run in bf16, which keeps only 8 bits of mantissa. Rounding to bf16 hides most of those tiny differences: of the 3,993 differing values above, <strong>only 2 still differed</strong> after rounding to bf16.</p>
<p>That sounds reassuring. It's actually the dangerous part. The differences don't disappear evenly; they survive exactly where a value sits near a rounding boundary. And a language model makes a hard decision every token: the argmax. When two candidate tokens are close (which happens constantly in long generations), a difference in the last bit of a logit picks a different word. From that token on, the two runs are reading different text, and they diverge completely.</p>
<p>So: tiny arithmetic difference → rarely visible → occasionally flips one token → the rest of the answer is different.</p>
<h2>4. The full list of things that change the order</h2>
<p>Once you think in terms of "who decides the summation order", the sources line up:</p>
<ul>
<li><strong>Batch size and padding.</strong> Different shapes, different kernels (shown above).</li>
<li><strong>Hardware.</strong> A different GPU generation or CPU instruction set (AVX2 vs AVX-512 vs ARM NEON) has different vector widths, so the natural way to split a sum changes.</li>
<li><strong>Library and driver versions.</strong> A new cuBLAS, oneDNN or PyTorch release can pick a new kernel for the same shape.</li>
<li><strong>Thread count.</strong> Parallel reductions split work by thread; 8 threads and 14 threads split a sum differently.</li>
<li><strong>Kernel tricks for speed.</strong> Split-K matmuls, atomics in reductions, fused attention kernels that tile the sequence differently for prefill and decode.</li>
<li><strong>Where the weights live.</strong> Offloading systems that compute some layers on the CPU and some on the GPU are mixing two different arithmetic implementations by construction.</li>
</ul>
<p>Note what's <em>not</em> on the list: true randomness. Run the exact same thing on the exact same setup and you usually do get the same bits. The problem is that "the exact same setup" almost never holds in production.</p>
<h2>5. Why anyone should care</h2>
<p>If outputs only matched to within a tolerance, you might shrug. Three places where you can't:</p>
<ul>
<li><strong>Evaluations.</strong> Benchmark scores move between inference backends and batch sizes. If your eval number changes when you change the serving setup, you're measuring the setup, not the model.</li>
<li><strong>Debugging.</strong> "It produced this bad output yesterday" is hard to investigate when you can't reproduce yesterday's output.</li>
<li><strong>Verification.</strong> If a provider says "this answer came from model X with these settings", you can only check that claim by recomputing it. Recomputing only proves something if the bits are supposed to match.</li>
</ul>
<h2>6. Can it be fixed?</h2>
<p>Yes, and the fix is conceptually simple: <strong>stop letting the shape, the hardware or the library choose the order.</strong> Pick one summation order for every dot product, and implement that exact order everywhere the model runs: every batch size, every kernel, every device. Then "the same request gives the same bits" stops being luck and becomes a property you can test.</p>
<p>That's what I built Vahana to do: an open-source engine for Mixture-of-Experts models that gives bit-identical output on any CPU or GPU. More on how it works, and what it costs, in the next posts. <a href="https://github.com/vahana-ai/Vahana">https://github.com/vahana-ai/Vahana</a></p>
<p>Further reading: Horace He and Thinking Machines Lab, <em>Defeating Nondeterminism in LLM Inference</em> (2025), on batch invariance in GPU kernels.</p>
<hr />
<h2>The script (reproduce every number above)</h2>
<pre><code class="language-python">import numpy as np, torch

# 1. order of summation
rng = np.random.default_rng(0)
x = rng.standard_normal(200_000).astype(np.float32)
fwd = np.float32(0)
for v in x: fwd = np.float32(fwd + v)
rev = np.float32(0)
for v in x[::-1]: rev = np.float32(rev + v)
print(fwd, rev, np.sum(x, dtype=np.float32), np.sum(x.astype(np.float64)))

# 2. batch size changes the bits of one row
torch.manual_seed(0)
W = torch.randn(4096, 4096); X = torch.randn(64, 4096)
one = X[:1] @ W
for bs in (1, 2, 3, 8, 16, 32, 64):
    row = (X[:bs] @ W)[:1]
    print(bs, torch.equal(row, one), int((row != one).sum()))

# 3. after bf16 rounding
full = (X @ W)[:1]
print(int((one.bfloat16() != full.bfloat16()).sum()))
</code></pre>
<p>Results depend on your CPU and PyTorch build; that's the point. Run it and see where <em>your</em> machine switches kernels.</p>
]]></content:encoded></item></channel></rss>