On paper, matrix multiplication is just three nested loops, a multiply, and an add.
Write that in Rust, compile with --release, and it is easy to assume the compiler
is already doing most of the heavy lifting.
I wanted to see what actually happens under the hood, and how far a single CPU thread
can be pushed on f64 math.
Normally, when I want to speed up a hot loop, I would reach straight for SIMD intrinsics[1]. But, this time, I measured first, read the generated assembly to see what the CPU is actually doing, and pushed safe Rust as far as it could go before writing a single intrinsic.
⁕ The Baseline #
The matrix itself is a flat, row-major Vec<f64>. I've implemented a cache-friendly
i-k-j loop order, where the inner loop walks the row-major mem sequentially instead
of striding down columns.
pub struct Matrix {
pub rows: usize,
pub cols: usize,
pub data: Vec<f64>,
}
pub fn matmul(&self, rhs: &Matrix) -> Matrix {
assert_eq!(self.cols, rhs.rows);
let mut out = Matrix::zeros(self.rows, rhs.cols);
for i in 0..self.rows {
for k in 0..self.cols {
let a = self.get(i, k);
for j in 0..rhs.cols {
let idx = i * rhs.cols + j;
out.data[idx] += a * rhs.get(k, j);
}
}
}
out
}I benchmarked this with Criterion across two sets of shapes. The first four are
small, non-square matrices from a neural network workload, while the rest scale from
64x64 to 512x512 to test cache behavior.
| Shape | Latency | Throughput (GFLOP/s) |
|---|---|---|
nn_l1_16x2x32 |
850.14 ns | 2.41 |
nn_l2_16x16x32 |
3.60 µs | 4.55 |
nn_dw2_16x32x16 |
5.42 µs | 3.02 |
nn_out_1x16x32 |
291.37 ns | 3.51 |
sq_64 |
93.62 µs | 5.60 |
sq_128 |
667.18 µs | 6.29 |
sq_256 |
5.41 ms | 6.20 |
sq_512 |
41.43 ms | 6.48 |
Two things stood out right away. Throughput hit a flat ~6.5 GFLOP/s ceiling across
128, 256, and 512. Stranger still, 16x16x32 and 16x32x16 perform the exact
same number of FLOPs (16,384), yet 16x32x16 was 50% slower (3.60 µs vs
5.42 µs).
Running cargo asm --release matmul explained both. Following is the hot inner loop
the compiler emitted,
.LBB15_25:
movupd xmm2, xmmword ptr [r8 + 8*rax - 16] ; load 2 f64s from rhs
movupd xmm3, xmmword ptr [r8 + 8*rax] ; load next 2 f64s from rhs
mulpd xmm2, xmm1 ; SSE2 multiply (2 f64s)
mulpd xmm3, xmm1
movupd xmm4, xmmword ptr [r14 + 8*rax - 16] ; load 2 f64s from out
addpd xmm4, xmm2 ; separate add (no FMA)
movupd xmm2, xmmword ptr [r14 + 8*rax]
addpd xmm2, xmm3
movupd xmmword ptr [r14 + 8*rax - 16], xmm4 ; store back to out
movupd xmmword ptr [r14 + 8*rax], xmm2
add rax, 4
cmp rcx, rax
jne .LBB15_25Reading the full disassembly exposed four major bottlenecks.
- Default
--releasebuilds, when target is x86-64, limit the loop to 128-bitxmmregisters and separatemulpd&addpdinstructions with no FMA[2]. - Manual indexing stops LLVM from proving
data.len() == rows * colsor thatout&rhsdo not alias, resulting in running ~40 instructions of bounds math and pointer overlap checks every(i, k)step. - The
.LBB15_25loads, updates and storesouton everykstep instead of accumulating in registers. - A pre-loop guard skips SIMD whenever
rhs.cols < 5, dropping into scalar loop with two bounds checks per element.
⁕ Pushing Safe Rust #
Before reaching for unsafe, I wanted to see how far idiomatic Rust could go on its
own. So, I added a matmul_into helper that asserts all dimensions and slice lengths
up front, then walks the matrices using chunks_exact and zip instead of manual
indexing.
pub fn matmul_into(&self, rhs: &Matrix, out: &mut Matrix) {
assert_eq!(self.cols, rhs.rows);
assert_eq!(out.rows, self.rows);
assert_eq!(out.cols, rhs.cols);
assert_eq!(self.data.len(), self.rows * self.cols);
assert_eq!(rhs.data.len(), rhs.rows * rhs.cols);
assert_eq!(out.data.len(), out.rows * out.cols);
out.data.fill(0.0);
if self.rows == 0 || self.cols == 0 || rhs.cols == 0 {
return;
}
for (a_row, c_row) in self
.data
.chunks_exact(self.cols)
.zip(out.data.chunks_exact_mut(rhs.cols))
{
for (&a, b_row) in a_row.iter().zip(rhs.data.chunks_exact(rhs.cols)) {
for (c, &b) in c_row.iter_mut().zip(b_row.iter()) {
*c += a * b;
}
}
}
}Upon inspecting the assembly, we can observe,
- Under default flags, every
panic_bounds_checkinside the loop has vanished - The 40 or so instruction aliasing check was hoisted out of the
kloop - Compiling w/
RUSTFLAGS="-C target-cpu=native"widened the inner loop to 256-bit AVX2[3] and unrolled itself to 4x in order to process 16 f64's per iter
.LBB0_31:
vmulpd ymm2, ymm1, ymmword ptr [rcx + 8*r10 - 96]
vmulpd ymm3, ymm1, ymmword ptr [rcx + 8*r10 - 64]
vmulpd ymm4, ymm1, ymmword ptr [rcx + 8*r10 - 32]
vmulpd ymm5, ymm1, ymmword ptr [rcx + 8*r10]
vaddpd ymm2, ymm2, ymmword ptr [r13 + 8*r10 - 96]
vaddpd ymm3, ymm3, ymmword ptr [r13 + 8*r10 - 64]
vaddpd ymm4, ymm4, ymmword ptr [r13 + 8*r10 - 32]
vaddpd ymm5, ymm5, ymmword ptr [r13 + 8*r10]
vmovupd ymmword ptr [r13 + 8*r10 - 96], ymm2
vmovupd ymmword ptr [r13 + 8*r10 - 64], ymm3
vmovupd ymmword ptr [r13 + 8*r10 - 32], ymm4
vmovupd ymmword ptr [r13 + 8*r10], ymm5
add r10, 16target-cpu=native, showing 256-bit AVX2 but still no FMAtarget-cpu=native, Rust emitted separate vmulpd and vaddpd
instructions instead of a single vfmadd231pd. Because Rust enforces strict
IEEE-754 rounding, it will not auto-fuse *c += a * b into an FMA without opting
in explicitly.
Even w/o FMA[2], the Criterion numbers jumped across every shape.
| Shape | Naive | Slices | Slices + native |
Speedup |
|---|---|---|---|---|
nn_l1_16x2x32 |
850.1 ns | 634.5 ns | 295.8 ns (6.92 GF/s) | 2.87x |
nn_l2_16x16x32 |
3.60 µs | 3.45 µs | 1.45 µs (11.34 GF/s) | 2.49x |
nn_dw2_16x32x16 |
5.42 µs | 3.81 µs | 2.00 µs (8.18 GF/s) | 2.71x |
nn_out_1x16x32 |
291.4 ns | 245.7 ns | 108.2 ns (9.46 GF/s) | 2.69x |
sq_64 |
93.62 µs | 93.51 µs | 38.13 µs (13.75 GF/s) | 2.46x |
sq_128 |
667.2 µs | 566.2 µs | 355.0 µs (11.82 GF/s) | 1.88x |
sq_256 |
5.41 ms | 4.62 ms | 3.02 ms (11.12 GF/s) | 1.79x |
sq_512 |
41.43 ms | 34.86 ms | 26.88 ms (9.99 GF/s) | 1.54x |
target-cpu=native compared against the naive baselineJust switching to slice iterators cut nn_dw2_16x32x16 by about 29% before
AVX2[3] even kicked in.
Still, throughput peaked at 13.75 GFLOP/s on sq_64 and faded to
9.99 GFLOP/s on sq_512. The inner loop is still missing FMA and still bouncing
out to memory on every k step.
⁕ The 4x8 Micro-Kernel #
Even though the impl achieves 13.75 GFLOP/s it still leaves most of the CPU core idle. A modern x86-64 single core has two independent 256-bit FMA execution units, each capable of 4x f64 multiply + adds per cycle. That is 16 FLOPs per clock cycle on a single thread, assuming both pipes stay fed.
The safe AVX2 loop couldn't get close for two reasons.
- It still emits separate
vmulpdandvaddpdinstructions instead of singlevfmadd231pd - It loads and stores
outon everykiteration, bottlenecking on L1 load and store ports.
The fix is register blocking[4], which is the core idea behind BLAS libraries like OpenBLAS and BLIS.
Instead of updating one row of C in memory on every k step, we accumulate a 4x8
tile of C (32 f64s) entirely inside 8 ymm registers (ymm0 to ymm7) across the
full k loop, and store C to memory once at the end.
#[target_feature(enable = "avx2", enable = "fma")]
unsafe fn microkernel_4x8(
k_len: usize,
a: *const f64, a_stride: usize,
b: *const f64, b_stride: usize,
c: *mut f64, c_stride: usize,
) {
let mut c00 = _mm256_setzero_pd();
let mut c01 = _mm256_setzero_pd();
let mut c10 = _mm256_setzero_pd();
let mut c11 = _mm256_setzero_pd();
let mut c20 = _mm256_setzero_pd();
let mut c21 = _mm256_setzero_pd();
let mut c30 = _mm256_setzero_pd();
let mut c31 = _mm256_setzero_pd();
for k in 0..k_len {
let b_ptr = b.add(k * b_stride);
let b0 = _mm256_loadu_pd(b_ptr);
let b1 = _mm256_loadu_pd(b_ptr.add(4));
let a0 = _mm256_set1_pd(*a.add(0 * a_stride + k));
c00 = _mm256_fmadd_pd(a0, b0, c00);
c01 = _mm256_fmadd_pd(a0, b1, c01);
let a1 = _mm256_set1_pd(*a.add(1 * a_stride + k));
c10 = _mm256_fmadd_pd(a1, b0, c10);
c11 = _mm256_fmadd_pd(a1, b1, c11);
let a2 = _mm256_set1_pd(*a.add(2 * a_stride + k));
c20 = _mm256_fmadd_pd(a2, b0, c20);
c21 = _mm256_fmadd_pd(a2, b1, c21);
let a3 = _mm256_set1_pd(*a.add(3 * a_stride + k));
c30 = _mm256_fmadd_pd(a3, b0, c30);
c31 = _mm256_fmadd_pd(a3, b1, c31);
}
_mm256_storeu_pd(c.add(0 * c_stride), c00);
_mm256_storeu_pd(c.add(0 * c_stride + 4), c01);
_mm256_storeu_pd(c.add(1 * c_stride), c10);
_mm256_storeu_pd(c.add(1 * c_stride + 4), c11);
_mm256_storeu_pd(c.add(2 * c_stride), c20);
_mm256_storeu_pd(c.add(2 * c_stride + 4), c21);
_mm256_storeu_pd(c.add(3 * c_stride), c30);
_mm256_storeu_pd(c.add(3 * c_stride + 4), c31);
}Running cargo asm on matmul_avx2_fma confirmed what mattered. There are zero
stack spills, all 8 accumulators stay pinned in registers, and 8 vfmadd231pd
instructions fire on every k step.
.LBB0_5:
vmovupd ymm8, ymmword ptr [r9 - 32]
vmovupd ymm9, ymmword ptr [r9]
vbroadcastsd ymm10, qword ptr [rcx + 8*rbp]
vfmadd231pd ymm0, ymm10, ymm8
vfmadd231pd ymm7, ymm9, ymm10
vbroadcastsd ymm10, qword ptr [r11 + 8*rbp]
vfmadd231pd ymm1, ymm10, ymm8
vfmadd231pd ymm2, ymm9, ymm10
vbroadcastsd ymm10, qword ptr [rbx + 8*rbp]
vfmadd231pd ymm3, ymm10, ymm8
vfmadd231pd ymm4, ymm9, ymm10
vbroadcastsd ymm10, qword ptr [r12 + 8*rbp]
inc rbp
vfmadd231pd ymm5, ymm10, ymm8
vfmadd231pd ymm6, ymm10, ymm9
add r9, r15
cmp rsi, rbp
jne .LBB0_5ymm accumulators, 8 FMAs per k step, and zero stack spillsmul then add).
One should always test FMA kernels against a naive reference using a tolerance like
1e-12, not exact ==
The new benches gave us a massive jump, but we've uncovered a brand new wall ☹️.
| Shape | Slices + native |
avx2_4x8 |
Speedup vs Naive |
|---|---|---|---|
nn_l1_16x2x32 |
295.8 ns | 254.4 ns | 3.34x |
nn_l2_16x16x32 |
1.45 µs | 496.4 ns | 7.26x |
nn_dw2_16x32x16 |
2.00 µs | 403.5 ns | 13.43x |
nn_out_1x16x32 |
108.2 ns | 66.8 ns | 4.36x |
sq_64 |
38.13 µs | 13.94 µs | 6.72x |
sq_128 |
355.0 µs | 97.31 µs | 6.86x |
sq_256 |
3.02 ms | 1.44 ms | 3.75x |
sq_512 |
26.88 ms | 15.30 ms | 2.71x |
sq_128 before dropping sharply on sq_256 and sq_512Throughput climbs to 43.1 GFLOP/s at 128x128, then falls off a cliff to be
around 23.2 at 256x256 and around 17.5 at 512x512. Meanwhile,
nn_dw2_16x32x16 flipped from being 50% slower than nn_l2_16x16x32 in the
baseline to being faster (403.5 ns vs 496.4 ns, 13.4x faster than naive)
because k = 32 amortizes the C tile stores over twice as many FMAs.
⁕ Cache Blocking and Packing #
Why did sq_512 fall from 43.1 GFLOP/s down to 17.5 GFLOP/s? One line in
.LBB0_5 gives it away.
add r9, r15 ; advance B pointer by 8 * N bytes.LBB0_5When N = 512, 8 * N is 4,096 bytes (4 KiB), an exact power of two. On an
8-way set-associative 32 KiB L1 data cache, stepping by 4 KiB maps every k
iteration into the exact same L1 cache set, evicting your own lines every 8
iterations. On top of that, a 512x512 f64 matrix is 2 MiB, so B gets evicted from
L2 cache long before the next row block of A comes back to reuse it.
The fix is the 5-loop BLIS style[5] layout.
With both panels packed sequentially, the inner loop of microkernel_4x8_packed
drops all stride math completely.
for p in 0..kc {
let bp = b_panel.add(p * 8);
let b0 = _mm256_loadu_pd(bp);
let b1 = _mm256_loadu_pd(bp.add(4));
let ap = a_panel.add(p * 4);
let a0 = _mm256_set1_pd(*ap);
c00 = _mm256_fmadd_pd(a0, b0, c00);
c01 = _mm256_fmadd_pd(a0, b1, c01);
let a1 = _mm256_set1_pd(*ap.add(1));
c10 = _mm256_fmadd_pd(a1, b0, c10);
c11 = _mm256_fmadd_pd(a1, b1, c11);
let a2 = _mm256_set1_pd(*ap.add(2));
c20 = _mm256_fmadd_pd(a2, b0, c20);
c21 = _mm256_fmadd_pd(a2, b1, c21);
let a3 = _mm256_set1_pd(*ap.add(3));
c30 = _mm256_fmadd_pd(a3, b0, c30);
c31 = _mm256_fmadd_pd(a3, b1, c31);
}microkernel_4x8_packed streaming contiguous A and B micro-panelsThe generated assembly compiles down with zero push, pop, or sub rsp overhead
in the entire function, and consists of a 17 instruction hot loop.
.LBB4_4:
vmovupd ymm8, ymmword ptr [rdx + 2*rax - 32]
vmovupd ymm9, ymmword ptr [rdx + 2*rax]
vbroadcastsd ymm10, qword ptr [rsi + rax - 16]
vfmadd231pd ymm7, ymm10, ymm8
vfmadd231pd ymm6, ymm9, ymm10
vbroadcastsd ymm10, qword ptr [rsi + rax - 8]
vfmadd231pd ymm5, ymm10, ymm8
vfmadd231pd ymm4, ymm9, ymm10
vbroadcastsd ymm10, qword ptr [rsi + rax]
vfmadd231pd ymm3, ymm10, ymm8
vfmadd231pd ymm2, ymm9, ymm10
vbroadcastsd ymm10, qword ptr [rsi + rax + 8]
vfmadd231pd ymm1, ymm10, ymm8
vfmadd231pd ymm0, ymm10, ymm9
add rax, 32
dec rdi
jne .LBB4_4microkernel_4x8_packed, showing pure sequential streaming, 8 FMAs per step, and zero stack spillsWith cache blocking and packing in place, the cache cliff disappeared.
| Shape | avx2_4x8 |
blis_packed |
Throughput (GFLOP/s) | Mean Change |
|---|---|---|---|---|
sq_64 |
13.94 µs | 11.38 µs | 46.07 | -18.7% |
sq_128 |
97.31 µs | 104.89 µs | 39.99 | +5.6% |
sq_256 |
1.44 ms | 817.06 µs | 41.07 | -44.0% |
sq_512 |
15.30 ms | 6.96 ms | 38.57 | -54.5% |
sq_128, sq_256, and sq_512sq_128 regressed by 5.6% (~7.6 µs), which is a real algorithmic trade-off.
Packing scales as while compute scales as . At 128x128, all
three matrices still fit inside L2 cache, so the upfront packing copy slightly
outweighs the cache savings. By 256x256 and 512x512, compute dominates and
throughput jumps by +78.6% and +119.8%.
⁕ Conclusion #
Putting every step side by side shows how each layer compounded on a single CPU thread.
| Shape | Naive | Safe+AVX2 | AVX2+FMA | BLIS | Speedup |
|---|---|---|---|---|---|
nn_l1_16x2x32 |
850.1 ns | 295.8 ns | 254.4 ns | 152.9 ns | 5.56x |
nn_l2_16x16x32 |
3.60 µs | 1.45 µs | 496.4 ns | 453.3 ns | 7.95x |
nn_dw2_16x32x16 |
5.42 µs | 2.00 µs | 403.5 ns | 417.6 ns | 12.98x |
nn_out_1x16x32 |
291.4 ns | 108.2 ns | 66.8 ns | 70.5 ns | 4.13x |
sq_64 |
93.62 µs | 38.13 µs | 13.94 µs | 11.38 µs | 8.23x |
sq_128 |
667.2 µs | 355.0 µs | 97.31 µs | 104.9 µs | 6.36x |
sq_256 |
5.41 ms | 3.02 ms | 1.44 ms | 817.1 µs | 6.62x |
sq_512 |
41.43 ms | 26.88 ms | 15.30 ms | 6.96 ms | 5.95x |
Hitting ~40 GFLOP/s on a single thread is satisfying, but the real payoff here
was the process. Reading the assembly before guessing explained why 16x32x16 lagged
behind 16x16x32, why target-cpu=native never fused an FMA, and why sq_512 fell
off a cliff at 4 KiB strides.
Exhausting safe Rust first delivered a clean 1.5x–2.8x speedup before writing a
single line of unsafe code. Even once intrinsics became necessary, SIMD alone still
wasn't enough. Saturating the core took register blocking to keep both FMA pipes
fed without bouncing C to L1, and cache blocking with panel packing to keep the
CPU fed once matrices outgrew L2.
You can access the complete matrix crate implementation, unit tests, and Criterion
benchmark setup in this repository.