Chapter 35A 150x Faster Kernel, and a Lean Proof That It Still Gives the Same Answer
The most suspicious number I've seen this year was 157x: the speedup on one shape after swapping a scalar loop in torchao for a vectorized kernel. When a change is that fast my first thought is "what did I break". Usually the new code skips work and the output is quietly different.
So I wrote a short Lean 4 proof that the fast kernel computes exactly the same integers as the slow one, wrap-around arithmetic and all.
The slow path nobody was looking at#
torchao has a CPU operator for DA8W4 linear: activations quantized to 8 bits on the fly, weights stored as 4-bit integers. The setup you reach for to make an LLM's weights half the size of int8.
The fast path only existed for Intel CPUs with AMX (4th Gen Xeon and newer). Issue #4243 asked about A8W4 on x86, and a maintainer said the kernel "is only optimized for platforms with AMX", with no plan to optimize others and contributions welcome.
"The others" is a big group. Ice Lake and Cascade Lake Xeons and AMD Zen 4 and Zen 5 EPYCs all have AVX512-VNNI, built for exactly this int8 dot product, and none have AMX. There, every GEMM ran:
for (int64_t i = 0; i < M; ++i) {
for (int64_t j = 0; j < N; ++j) {
float sum = 0;
for (int64_t k = 0; k < K; ++k) {
sum += ((int32_t)A_ptr[i * lda + k] - qzeros_a[i]) * (int32_t)dqB[k * N + j];
}
C[i * ldc + j] += sum * scales_a[i] * scales_b[j];
}
}One multiply-add at a time, around 9 GOP/s. Correct, readable, and almost the whole chip idle.
What VNNI wants from you#
vpdpbusd: each 32-bit lane of a 512-bit register multiplies four byte pairs, sums the four products, and adds into a 32-bit accumulator. Sixteen lanes, four products each, one instruction.
The catch is unsigned times signed: the first operand is uint8, the second int8. Fine for weights (small signed numbers after subtracting the zero point). Fine for asymmetric uint8 activations with zero point zp, thanks to some algebra:
Σ (a - zp) * b = Σ a * b - zp * Σ bΣ b doesn't depend on the activations, so prepack computes it once per column (compensation). The kernel runs vpdpbusd on raw uint8 a, then subtracts zp * compensation.
Symmetric activations are int8, which vpdpbusd won't take as the first operand. The trick: flip the top bit. For an int8 byte a, a ^ 0x80 read as uint8 is exactly a + 128. Feed that in, compute Σ (a + 128) * b, subtract 128 * compensation, and you have Σ a * b.
asymmetric (uint8, zero point zp)
a ────────────────────────────▶ vpdpbusd ──▶ acc - zp * comp
▲
symmetric (int8) │ weights b (int8)
a ──▶ xor 0x80 (== a + 128) ──▶ vpdpbusd ──▶ acc - 128 * comp
comp = sum of the weights in the column, computed once at prepackThe fix#
Two parts. First, prepack weights in the VNNI4 layout (groups of four k values side by side) whenever the build has AVX512-VNNI, not only with AMX. Second, on non-AMX machines replace the scalar loop with micro-kernels. For M of 4 or less I reused the small-M kernel already in the file; for bigger M the weight block is unpacked once and reused across 8-row tiles.
for (int64_t k = 0; k < K; k += 4) {
// load 4 k-values x N columns of int8 weights
// for each row: broadcast 4 activation bytes, flip sign bit if symmetric
va = _mm512_xor_si512(va, sign_flip); // a ^ 0x80 == a + 128
vc[row * COLS + col] =
_mm512_dpbusd_epi32(vc[row * COLS + col], va, vb[col]);
}
// epilogue, per 16-lane column:
vacc = _mm512_sub_epi32(vc, _mm512_mullo_epi32(vcomp, _mm512_set1_epi32(zp)));
// then int32 -> float, * scale_a, * scale_b, add into C(Unrolling templates trimmed; the real thing is in the PR.) AMX machines and builds without VNNI take exactly the same path as before.
The numbers#
Op-level timings, float output, 2 threads, warm cache, AMD EPYC 9V45 (AVX512-VNNI, no AMX):
| act | M | N | K | group | before (ms) | after (ms) | speedup |
|---|---|---|---|---|---|---|---|
| sym | 1 | 4096 | 4096 | 128 | 4.05 | 0.09 | 44x |
| sym | 4 | 4096 | 4096 | 128 | 15.64 | 0.19 | 82x |
| sym | 32 | 4096 | 4096 | 128 | 123.85 | 0.89 | 139x |
| sym | 256 | 4096 | 4096 | 128 | 988.03 | 6.45 | 153x |
| sym | 32 | 11008 | 4096 | 32 | 368.21 | 3.07 | 120x |
| asym | 1 | 4096 | 4096 | 128 | 4.09 | 0.09 | 47x |
| asym | 4 | 4096 | 4096 | 128 | 15.85 | 0.12 | 135x |
| asym | 32 | 4096 | 4096 | 128 | 125.56 | 0.87 | 145x |
| asym | 256 | 4096 | 4096 | 128 | 1002.73 | 6.39 | 157x |
| asym | 128 | 4096 | 11008 | 64 | 1498.72 | 10.16 | 148x |
On an AMD EPYC 9V74 it came out between 32x and 176x.
Caveats: the speedups are big mainly because the baseline was a scalar loop, so this is "stop doing the slow thing" more than clever optimization. The single-row cases (M = 1, token-by-token decoding) are weakest at 44x and 47x, and I haven't compared against a hand-tuned library. Every number is from AMD Zen 4 and Zen 5 cloud machines. I don't have an Ice Lake or Cascade Lake box, the Intel chips the issue was about. I said so in the PR and asked for numbers.
So how do I know it's still right?#
The PR states outputs are bitwise identical to the old scalar path across 268 combinations of shape, bias and activation type. Strong for a kernel that reorganizes all the arithmetic, so why should it be true at all?
Both versions compute an integer dot product per block of up to 128 k values, then convert to float, multiply by the activation scale, then the weight scale, and add into C, in the same order. If the integer entering the float epilogue is the same, every IEEE operation after it sees the same input. So the question reduces to: does the VNNI kernel's int32 equal the true integer Σ (a - zp) * b? The VNNI path groups additions differently, works in 32-bit registers that wrap, shifts signed activations by 128, and subtracts a big correction at the end. Any could go wrong at the edges.
A detour: the bug I thought I'd found
While reading the old scalar loop I got excited about a bug that wasn't there. It accumulates sum in a float, with a 24-bit significand, so adding thousands of integer products felt like it should drop low bits, meaning the "reference" wasn't even exact.
It doesn't, because of block size. The loop runs over one block of at most 128 k values. The biggest product is 255 * 15 = 3825, so the worst partial sum is 128 * 3825 = 489,600, far below 2^24 (about 16.7 million), and a float holds every integer up to there exactly. So the old float sum is the exact integer too. I'm leaving it in because "floats are inexact" is a heuristic, not a law, and the bounds decide. (That bound is my back-of-the-envelope argument, not part of the Lean proof.)
Enter Lean#
Lean 4 is a programming language and proof checker. If it compiles, the theorem is true, assuming the definitions say what you meant. Lean has BitVec n, an n-bit machine word with hardware wrap-around, so BitVec 32 addition wraps modulo 2^32 exactly like an int32 lane. The proof can describe the real machine arithmetic, not an infinite-precision idealization.
I modelled vpdpbusd as: exact sum of four products, added to the accumulator with wrap-around.
def dpbusd (acc : BitVec 32) (q : List (Int × Int)) : BitVec 32 :=
acc + BitVec.ofInt 32 (q.foldr (fun p s => p.1 * p.2 + s) 0)The k-loop folds that over the four-element groups from zero. The epilogue is acc - zp * comp, also wrapping.
theorem asym_exact (pairs : List (Int × Int)) (qs : List (List (Int × Int)))
(hqs : qs.flatten = pairs)
(zp comp : BitVec 32)
(hcomp : comp.toInt = (pairs.map Prod.snd).foldr (· + ·) 0)
(ha : ∀ p ∈ pairs, 0 ≤ p.1 ∧ p.1 ≤ 255)
(hb : ∀ p ∈ pairs, -15 ≤ p.2 ∧ p.2 ≤ 15)
(hz : 0 ≤ zp.toInt ∧ zp.toInt ≤ 255)
(hK : pairs.length ≤ 2 ^ 15) :
(epilogue (kloop qs) zp comp).toInt = dotZ zp.toInt pairs := byEverything before the last line is a hypothesis; the last line is the conclusion:
pairsis the (activation, weight) pairs along k, in order.qsis the kernel's grouping forvpdpbusd. Flattening it must givepairs, so any grouping works, including a ragged last group.compreally is the sum of the weights.- Activations are in 0..255, weights in -15..15, zero point in 0..255, at most 2^15 terms along k.
Then the kernel's k-loop and epilogue in wrapping int32, read as signed, equals Σ (a - zp) * b in unbounded integers. No "approximately", no "for these inputs".
The proof is about twenty lines and two facts. A chain of wrapping adds equals the exact sum modulo 2^32, whatever the grouping (kloop_toInt). And with those bounds the true answer is at most 2^15 * 255 * 15, under 2^31, so it fits an int32 and "modulo 2^32" changes nothing. The kernel uses only 128 terms per call, a comfortable margin.
The other theorems
sym_exact handles symmetric activations. It's stated on real BitVec 8 bytes, feeds them through a ^ 0x80, and concludes acc - 128 * comp equals the true Σ a * b. It mostly reuses asym_exact with a zero point of 128, plus:
theorem xor_flip (a : BitVec 8) : ((a ^^^ 0x80#8).toNat : Int) = a.toInt + 128 := by
revert a; decideMy favorite line in the file: decide just checks all 256 bytes. Brute force is a fine proof when the input space is small.
dequant_exact covers the step before: unpacking a 4-bit weight nibble and subtracting a 4-bit zero point in wrapping int8 arithmetic is exact and lands in [-15, 15]. That's where hb comes from.
The file uses Lean core only, no Mathlib, no sorry, and #print axioms lists only Lean's three standard axioms.
What the proof doesn't cover#
The proof is about a hand-written model, not the shipped C++.
| Not covered | Why it matters |
|---|---|
The vpdpbusd model | I transcribed it from Intel's manual: four uint8 x int8 products, summed, added with wrap. The products fit in 16 bits so addition order doesn't matter, but a misreading would make Lean prove things about the wrong instruction. |
| The compensation | Assumed as a hypothesis that comp equals the sum of the weights. Whether prepack computes that isn't proved here. |
| The float epilogue | The proof stops at the int32. The float steps matching is the "same sequence of IEEE operations" argument, made by reading the code. |
| Memory layout and indexing | Not modelled: right bytes at right offsets, row tails, and so on. |
That's what the PR's tests are for. test_da8w4_linear_op_matches_reference calls the op directly and compares against a float64 reference for M in 1, 2, 3, 4, 5, 7, 8, 9, 13, 17, 49, 65 and 130 (so every row-tail branch is hit), both activation types, group sizes 32, 128 and 256. It passes on old and new kernels. The existing test file passed too (58 tests on an AVX512-VNNI machine without AMX), as did the 268-combination bitwise comparison.
Division of labor: Lean shows the arithmetic idea (sign flip, compensation, wrapping int32 accumulation) is exact for every input within the bounds; the tests show the compiled C++ implements that idea.
Where it stands#
The PR is pytorch/ao#5045. Review status lives on the PR itself. The proof is in my lean-perf-proofs repo, next to a few others in the same spirit.
Most of the proof is bookkeeping about bounds. The facts are one-liners: a sign flip is plus 128, wrapping addition is addition mod 2^32, a small enough sum doesn't wrap. The value was being forced to write down |b| ≤ 15 and K ≤ 2^15, exactly the things a future change could quietly break. Widen the weights to 8 bits or make blocks huge and the theorem no longer applies, and now a file says so.
The open question: can I close the gap between the hand-written model and the real C++? Tools exist that verify C or LLVM IR directly, and I'd like to know how far one gets on a kernel full of AVX-512 intrinsics. Maybe the next rabbit hole.