← Back to all chapters

Chapter 36Making ONNX Runtime's int4 Dequantize Fast, Then Proving I Didn't Break It

9 min read
performanceonnxruntimequantizationleanformal-verification

I sped up a piece of ONNX Runtime by 4 to 12 times on a single core, and up to the low twenties with a few threads, without touching the math. Every output float is computed by the same expression, in the same order. The output is bit-identical. All the speed came from moving loops around.

That makes the failure modes narrow: read the wrong byte, use the wrong scale, skip an element, write one twice. Exactly the bugs tests catch on shapes you thought of and miss on shapes you didn't. So I also wrote a Lean 4 proof that the new loops visit every output exactly once and pair it with the right scale.

The slow path#

I was hunting for scalar code paths nobody had made fast. ONNX Runtime's CPU DequantizeLinear for the sub-byte types (int4, uint4, int2, uint2) was one, with a TODO in the file about threading it.

These models pack two or four weights per byte. Dequantizing turns each packed integer q back to a float:

y = float(q - zero_point) * scale

Scale and zero point can be per-tensor, per-axis, or per-block. The old kernel handled all with a per-element loop. The per-axis version, trimmed:

for (size_t m = 0; m < M; m++) {
  for (size_t bd = 0; bd < K; bd++) {
    auto zp = zero_point ? static_cast<int32_t>(zero_point[bd_i].GetElem(bd_j)) : 0;
    auto sc = static_cast<float>(scale[bd]);
    for (size_t bs = 0; bs < N; bs++) {
      int32_t val = static_cast<int32_t>(input[input_i].GetElem(input_j));
      *output++ = static_cast<OutT>(static_cast<float>(val - zp) * sc);
      input_index += 1;
    }
  }
}

Correct and readable, but slow for two reasons:

  • GetElem per element. It shifts, masks and sign-extends through a 32-bit int, working out which byte and which half each iteration. The compiler can't vectorize that, so you do one element at a time on hardware that could do sixteen or thirty-two.
  • One thread. thread_pool is passed in and explicitly marked unused.
for each output element:
 find the byte -> find the half -> shift, mask, sign-extend
 -> subtract zero point -> multiply by scale -> store one float

scalar, one thread, 1 element at a time
Work done per output element. Schematic.

On a 4096x4096 weight tensor that was somewhere between 10 and 50 ms per dequantize, for what is essentially "unpack some nibbles and multiply".

Moving the loops around#

float(q - zp) * scale stays exactly as it was. Only the structure around it changes.

The new dequantize pipeline. Click a box.

For signed values the unpack shifts the wanted element to the top of the byte, then arithmetic-shifts back down, which sign-extends for free:

for (size_t b = 0; b < num_bytes; ++b) {
  const uint8_t v = packed[b];
  int8_t* o = out + b * elements_per_byte;
  [&]<size_t... J>(std::index_sequence<J...>) {
    if constexpr (is_signed) {
      // Move element J to the top bits, then arithmetic-shift it back down to sign-extend it.
      ((o[J] = static_cast<int8_t>(static_cast<int8_t>(v << (8 - bits * (J + 1))) >> (8 - bits))), ...);
    } else {
      ((o[J] = static_cast<int8_t>((v >> (bits * J)) & mask)), ...);
    }
  }(std::make_index_sequence<elements_per_byte>{});
}
packed byte 0xF3, two int4 values: element 0 is the low nibblev11110011v << 400110000>> 4, signed00000011= 0xF3element 0 now on top= 3element 1: v << 0, then >> 4 sign-extends 1111 into 11111111, which is -1Shaded cells are the wanted element at each step. Worked example for int4.
Decoding one int4 byte with two shifts. Worked example.

Every lane does the same 8-bit shifts on its own byte, so GCC and Clang turn it into SIMD. A scalar loop before it handles a run starting mid-byte, and one after handles the tail. The dequantize step is then a dead simple loop over contiguous int8:

for (size_t i = 0; i < n; ++i) {
  output[i] = static_cast<OutT>(static_cast<float>(static_cast<int32_t>(values[i]) - zp) * scale);
}

Same expression as before. That's the point.

output tensor, split into disjoint chunkschunk 0thread 0chunk 1thread 1chunk 2thread 2chunk 3thread 3Each output index belongs to exactly one chunk: none skipped, none written twice.That is the property the Lean proof covers. Schematic, 4 threads.
How the thread pool splits the work. Schematic.

The numbers, including the bad ones#

4096x4096 tensor, best of 7 runs, standalone harness built around the new code:

1 thread4 threads
EPYC 7763, GCC 154-12x7-21x
EPYC 7763, Clang 212-8x4-14x
Neoverse-N2, GCC 133-7x10-23x
EPYC 9V74, MSVC1.6-4.6x3-9x
M4 Pro, Apple Clang (8 threads)6-12x16-35x
  • EPYC 7763 GCC, 1 thread4-12x
  • EPYC 7763 GCC, 4 threads7-21x
  • EPYC 7763 Clang, 1 thread2-8x
  • EPYC 7763 Clang, 4 threads4-14x
  • Neoverse-N2, 1 thread3-7x
  • Neoverse-N2, 4 threads10-23x
  • EPYC 9V74 MSVC, 1 thread1.6-4.6x
  • EPYC 9V74 MSVC, 4 threads3-9x
  • M4 Pro, 1 thread6-12x
  • M4 Pro, 8 threads16-35x
Best-case speedup per platform. Labels show the full range from the table.

Ranges are wide because they span int4 vs int2, signed vs unsigned, per-tensor vs per-axis vs blocked, with and without a zero point.

  • MSVC gains less. It doesn't vectorize the int8 unpack, so Windows mostly gets the cleaner dequantize loop and the threading. The fix is probably a hand-written SSE2/NEON unpack, which I left for later rather than putting intrinsics in a first PR.
  • Very short rows don't get faster single-threaded. With rows of 2 to 4 elements, per-row bookkeeping dominates: roughly 0.7x to 1.1x on one thread, a wash or slightly slower. With threads it's 1.6x to 4.8x, because the old code had none.

So how do I know it's still right?#

Both kernels compute, for every output index e:

y[e] = float(q(e) - zp(σ(e))) * float(scale(σ(e)))

q(e) is the e-th packed integer and σ(e) the index of the scale and zero point it uses. The float part is literally the same source expression on both sides: an exact small-integer-to-float conversion and one multiply. No addition, so no fused multiply-add can change the rounding. Unless you build with fast-math, it rounds the same scalar or vectorized.

So floating point drops out. The outputs are identical if two integer facts hold:

  1. The new shift trick decodes every byte to the same integers as GetElem.
  2. Every output index is written exactly once, reading the same scale index σ(e) the old loop would have.

Both are statements about bits and natural numbers, which is what a proof assistant is good at.

What the Lean proof says#

Lean is a programming language where the compiler won't accept a theorem until you give it a checkable proof. The first fact is easy: I defined GetElem's decoding and the shift trick on BitVec 8 and asked Lean to check they agree.

theorem decode_int4 : ∀ v : BitVec 8, ∀ j : Fin 2, unpackSigned 4 j v = getElemSigned 4 j v := by
  decide +kernel

For all 256 bytes and both nibbles, new decode equals old. decide just checks every case. A matching decode_int2 covers the four 2-bit elements.

The second fact is the real one. "This loop is exact" is a structure with four fields:

structure Exact {α : Type} (D : α → Prop) (enc sc : α → Nat) (total : Nat) (σ : Nat → Nat) : Prop where
  in_range : ∀ d, D d → enc d < total
  inj : ∀ d₁ d₂, D d₁ → D d₂ → enc d₁ = enc d₂ → d₁ = d₂
  surj : ∀ e, e < total → ∃ d, D d ∧ enc d = e
  scale : ∀ d, D d → sc d = σ (enc d)

D is the set of loop coordinates a path visits (which work unit, which position in it), enc maps a coordinate to the output index it writes, and sc is the scale index it reads.

FieldGuarantees
in_rangeevery write lands inside the output tensor
injno two coordinates write the same index: no double writes
surjevery output index is written by some coordinate: nothing skipped
scalethe scale index each write reads is the one the old loop would use

Injective plus surjective onto [0, total) is a precise way to say "every output exactly once". Since work units write disjoint indices, the result also doesn't depend on how the thread pool schedules them.

There's one theorem per loop path: per-axis long rows, quantize axis last, short rows packed several to a unit, the blocked variants, and blocked with the quantize axis last. None uses sorry, and the only axioms are Lean's three standard ones.

One theorem unpacked, and the supporting lemmas

The long-rows per-axis path (rows of 512 or more elements, which includes per-tensor):

theorem axis_long_rows_exact {M K N C : Nat} (hC : 0 < C) :
    let cpr := (N + C - 1) / C
    Exact (fun d : Nat × Nat => d.1 < M * K * cpr ∧ d.2 < C ∧ d.1 % cpr * C + d.2 < N)
      (fun d => d.1 / cpr * N + (d.1 % cpr * C + d.2))
      (fun d => d.1 / cpr % K) (M * K * N) (σAxis K N)

C is the chunk size (512 in the real code), cpr is chunks per row, rounded up. A coordinate is a pair: unit d.1 and position d.2 within the chunk. The domain says the unit is in range, the position is inside the chunk, and the column doesn't run past the row end (that last condition handles the partial chunk at the end of each row). The write index is row times row length plus column; the scale index is "row mod K". The claim is that this is Exact against σAxis, the old loop's scale index in closed form, e / N % K.

Smaller theorems fill the gaps:

  • unpack_bulk: the byte loop reads exactly element first + i for output slot i and stays in bounds, given where the leading scalar loop stopped.
  • rowStep_correct: the counter-based (m, k, block) tracking in the short-rows path always equals what division would give.
  • short_rows_buffer and block_last_buffer: the 512-element stack buffers never overflow.

What is proved and what is modelled#

"Formally verified" can sound like more than it is. The proof is about a model of the C++. I transcribed each loop path by hand: its domain, write index, scale index. A mis-transcribed loop would make the proof about code that doesn't exist. Explicit assumptions:

  • The old loop's scale index σ is in closed form. The real loop bumps pointers per element and per block; I didn't prove that equals the closed form.
  • size_t indices don't overflow. All are below the tensor size, so reasonable, but assumed.
  • The float expression isn't modelled at all, per the argument above: same source expression, one exact conversion and one multiply, no fast-math.

Tests tie the model to the compiled code. The PR adds a SubByteMatchesReference test for each of int4, uint4, int2 and uint2 that runs every code path against a scalar reference with zero tolerance: odd shapes, rows starting mid-byte, partial blocks, with and without a zero point. I also diffed old against new on 3000 random shapes with GCC, Clang and MSVC with no mismatches, and the 526 existing quantization tests pass locally on macOS arm64.

The tests check the real code matches the model on many concrete inputs; the proof checks the model is right on all inputs. Tests alone leave me wondering about the shape I didn't try; the proof alone leaves me wondering about the transcription.

Where it stands#

The PR is microsoft/onnxruntime#33784. Review status lives on the PR itself. The proof is in lean-perf-proofs/onnxruntime-subbyte-dequant, next to a few others for different fixes, and checks with plain Lean core, no Mathlib.

The obvious next step is the MSVC gap: a small SSE2/NEON unpack. But the question I keep coming back to is transcription. The weakest link is me reading C++ and writing down what I think it does. I'd love to close that, by extracting the model from the source or writing the kernel in a form that is the model. I don't know the least painful version for a codebase the size of ONNX Runtime. If you do, I'd like to hear about it.

© 2026 Bharat Kaurav. Built with Next.js & Tailwind.

>_ bk@netherwatcheresc to close

Welcome, reader. Type help to see what this shell can do.