In the last post 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.

The obvious objection is speed. BLAS libraries like Intel MKL are fast because they get to choose the order. So how much do you actually give up if you take that choice away?

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.

The setup

  • 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.
  • Problem: a 4096×4096 fp32 weight matrix W (64 MiB) multiplied by a batch of B input rows, for B = 1, 8 and 64. That's the shape of one projection in a mid-sized transformer layer.
  • Baseline: x @ W.T in PyTorch, which calls MKL.
  • Challenger: a dot product with one fixed order, written in Numba.

The fixed order is this. Split each 4096-long dot product into 16 lanes. Lane j adds up elements j, j+16, j+32, … 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.

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 outputs, 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.

The kernel:

@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 > 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] 

fastmath=False matters: it stops the compiler from reordering the additions, which would defeat the whole purpose.

First, does it actually give the same bits?

Yes. Here is what the script printed:

  • Fixed order, row 0 computed at batch 1, 8 and 64: same bits every time.
  • Fixed order, 1 thread vs 8 threads: same bits.
  • Fixed order in Numba vs the same order written with plain PyTorch elementwise ops: same bits. Two completely different implementations agree exactly, because they perform the same roundings in the same sequence.
  • MKL, row 0 at batch 8 vs batch 1: 3,910 of 4,096 values changed. The same at batch 64.

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.

Is the fixed order less accurate?

Slightly, but not in a way that matters. Against an fp64 reference:

  • Fixed order: mean absolute error 1.49e-05, max 1.09e-04
  • MKL: mean absolute error 1.33e-05, max 8.93e-05

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.

The cost

Best-of-N timings in milliseconds, three rounds each (all from the same run of the script at the end):

  • Batch 1: MKL 2.25–2.43 ms, fixed order 2.90–3.33 ms. Cost: 1.25–1.37×.
  • Batch 8: MKL 12.85–14.00 ms, fixed order 17.85–20.93 ms. Cost: 1.34–1.63×.
  • Batch 64: MKL 19.39–21.49 ms, fixed order 155.6–160.2 ms. Cost: 7.5–8.0×.

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.

(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.)

Why batch 1 is cheap and batch 64 isn't

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.

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.

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 one 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.

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.

Why this matters for LLM inference

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.

So the honest summary is:

  • Reproducible bits come from one rule: fix the order inside every dot product, and let parallelism split only the outputs.
  • With bandwidth as the bottleneck, that rule is nearly free.
  • With compute as the bottleneck, the rule itself doesn't cost much, but reaching BLAS speed under it takes real kernel work.

Reproduce it

The full script prints every number in this post. Save it as post02.py and run pip install torch numba numpy, then python post02.py:

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 > 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] > 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 < 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") 

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.

I'm building Vahana, an open-source engine for exact MoE inference: github.com/vahana-ai/Vahana