Skip to content

Project: Matrix Multiplication

Matrix multiplication is the workhorse of machine learning, graphics and science: a neural network spends most of its time doing it. It’s also the best-known example of code where the same math can run at wildly different speeds depending on how you write the loops. In this project you’ll write the textbook version, then speed it up in three steps, measuring after each one.

You’ll practise structs and special methods, loops, SIMD, vectorize, parallelize, pointers and benchmarking. Every timing on this page is from our test machine, a 4-core Linux VM with an Intel Xeon at 2.1 GHz. Yours will be different; the point is how the numbers change from step to step.

To multiply matrix A (with n rows and m columns) by matrix B (m rows, p columns), you get a matrix C with n rows and p columns. Each entry is a row of A times a column of B, added up:

C[i, j] = A[i, 0] * B[0, j] + A[i, 1] * B[1, j] + ... + A[i, m-1] * B[m-1, j]

For example:

| 6 5 |
| 1 2 3 | | 4 3 | | 20 14 |
| 4 5 6 | x | 2 1 | = | 56 41 |

The top-left 20 is the first row of A times the first column of B: 1*6 + 2*4 + 3*2. The 14 next to it is the same row times the second column: 1*5 + 2*3 + 3*1.

For two 512 by 512 matrices that’s 512 x 512 x 512, about 134 million multiply-and-adds.

Step 1: A Matrix struct and the textbook loop

Section titled “Step 1: A Matrix struct and the textbook loop”

We store the numbers in one flat List[Float64], row after row. Element (i, j) lives at position i * cols + j. With __getitem__ and __setitem__ taking two numbers, you can write m[i, j] just like the math (see Mojo Special Methods):

struct Matrix(Movable, Writable):
var rows: Int
var cols: Int
var data: List[Float64]
def __init__(out self, rows: Int, cols: Int):
self.rows = rows
self.cols = cols
self.data = List[Float64](length=rows * cols, fill=0)
def __getitem__(self, i: Int, j: Int) -> Float64:
return self.data[i * self.cols + j]
def __setitem__(mut self, i: Int, j: Int, value: Float64):
self.data[i * self.cols + j] = value
def write_to(self, mut writer: Some[Writer]):
for i in range(self.rows):
for j in range(self.cols):
if j > 0:
writer.write(" ")
writer.write(self[i, j])
if i < self.rows - 1:
writer.write("\n")
def matmul_naive(a: Matrix, b: Matrix) -> Matrix:
var c = Matrix(a.rows, b.cols)
for i in range(a.rows):
for j in range(b.cols):
var total: Float64 = 0
for k in range(a.cols):
total += a[i, k] * b[k, j]
c[i, j] = total
return c^
def main():
var a = Matrix(2, 3)
var b = Matrix(3, 2)
for i in range(6):
a.data[i] = Float64(i + 1) # 1 2 3 / 4 5 6
b.data[i] = Float64(6 - i) # 6 5 / 4 3 / 2 1
print(matmul_naive(a, b))

Output:

20.0 14.0
56.0 41.0

The same 20 14 / 56 41 we worked out by hand. A few notes:

  • List[Float64](length=..., fill=0) makes a list of zeros of the right size in one go.
  • return c^ moves the result out, because a Matrix holds a List and isn’t copied implicitly.
  • The loop order is i, j, k: for each entry of C, walk along a row of A and down a column of B. That’s exactly the formula, which is why everyone writes it first.

Now let’s use real sizes: two 512 by 512 matrices. We fill them with a simple pattern so every run uses the same numbers, and print a checksum (the sum of all entries of the result). The checksum lets us check later that the faster versions compute the same thing:

from std.time import perf_counter_ns
struct Matrix(Movable):
var rows: Int
var cols: Int
var data: List[Float64]
def __init__(out self, rows: Int, cols: Int):
self.rows = rows
self.cols = cols
self.data = List[Float64](length=rows * cols, fill=0)
def __getitem__(self, i: Int, j: Int) -> Float64:
return self.data[i * self.cols + j]
def __setitem__(mut self, i: Int, j: Int, value: Float64):
self.data[i * self.cols + j] = value
@no_inline
def matmul_naive(a: Matrix, b: Matrix) -> Matrix:
var c = Matrix(a.rows, b.cols)
for i in range(a.rows):
for j in range(b.cols):
var total: Float64 = 0
for k in range(a.cols):
total += a[i, k] * b[k, j]
c[i, j] = total
return c^
def filled(n: Int, factor: Int) -> Matrix:
var m = Matrix(n, n)
for i in range(n * n):
m.data[i] = Float64((i * factor) % 10)
return m^
def checksum(m: Matrix) -> Float64:
var total: Float64 = 0
for x in m.data:
total += x
return total
def main():
var a = filled(512, 3)
var b = filled(512, 7)
var t0 = perf_counter_ns()
var c = matmul_naive(a, b)
var ms = (perf_counter_ns() - t0) // 1_000_000
print("naive:", checksum(c), "in", ms, "ms")

You’ll see something like this (on our test VM):

naive: 2717893632.0 in 1159 ms

Over several runs the naive version took between about 0.8 and 1.7 seconds. The VM shares its CPU with other work, so the slow runs are noise; look at the fast end. About one second for 134 million multiply-and-adds is not good for compiled code. The next step shows why.

Look at how the inner loop reads B: b[k, j] with k going up. In our flat list, going down a column means jumping 512 places forward on every step. CPUs fetch memory in small blocks (cache lines) and are fastest when you read neighbouring numbers one after another. Jumping around wastes most of every block.

The fix is to swap the j and k loops. The result is the same, because we’re adding up the same products, just in a different order:

@no_inline
def matmul_reordered(a: Matrix, b: Matrix) -> Matrix:
var c = Matrix(a.rows, b.cols)
for i in range(a.rows):
for k in range(a.cols):
var a_ik = a[i, k]
for j in range(b.cols):
c[i, j] += a_ik * b[k, j]
return c^

Now the inner loop walks along a row of B and a row of C, one neighbor at a time. a[i, k] doesn’t change inside it, so we read it once into a_ik. c[i, j] += ... works because Matrix has both __getitem__ and __setitem__.

Add it to the Step 2 program and time it the same way. On our test VM it took 314 to 377 ms, roughly 3 times faster than the naive loop, with the same checksum. Nothing changed except the loop order.

The inner loop now does the same thing to neighbouring numbers: c[j] += a_ik * b[j] for j = 0, 1, 2, …. That’s a perfect fit for SIMD: load several b values at once, multiply them all by a_ik, add to several c values, store them back. vectorize from std.algorithm runs that for you over the whole row, chunk by chunk, and handles the leftover at the end. The Mojo Vectorize lesson explains it in detail, and the vectorize reference has the full signature.

from std.algorithm import vectorize
from std.sys import simd_width_of
comptime W = simd_width_of[DType.float64]()
@no_inline
def matmul_vectorized(a: Matrix, b: Matrix) -> Matrix:
var c = Matrix(a.rows, b.cols)
var b_ptr = b.data.unsafe_ptr()
var c_ptr = c.data.unsafe_ptr()
for i in range(a.rows):
for k in range(a.cols):
var a_ik = a[i, k]
var b_row = k * b.cols
var c_row = i * c.cols
def step[width: Int](j: Int) {imm a_ik, imm b_ptr, imm c_ptr, imm b_row, imm c_row}:
var c_now = c_ptr.unsafe_load[width=width](c_row + j)
var b_now = b_ptr.unsafe_load[width=width](b_row + j)
c_ptr.unsafe_store(c_row + j, c_now + a_ik * b_now)
vectorize[W](b.cols, step)
return c^

What’s new:

  • b.data.unsafe_ptr() gives a pointer to the first number in the list. unsafe_load[width=width](pos) reads width numbers starting at pos as one SIMD value, and unsafe_store(pos, value) writes them back. There’s no bounds checking, so the positions must be right. (See Mojo Unsafe Pointers.)
  • a_ik * b_now multiplies a single number by a whole vector: the number is copied into every lane first.
  • step is a nested function with a capture list ({imm a_ik, ...}) that says which outside values it reads. vectorize[W](b.cols, step) calls it with j = 0, W, 2W, … and a smaller width for any leftover at the end.
  • W is how many Float64s fit in one SIMD register on this CPU: 8 on our machine.

On our test VM this usually took 20 to 33 ms, again with the same checksum. That’s about 13 times faster than Step 3.

Each row of C depends only on one row of A and all of B, so different rows can be computed at the same time on different cores. parallelize(func, n) calls func(0) to func(n - 1) spread over worker threads, and waits until all are done.

In Mojo 1.2, parallelize isn’t in the standard library. It lives in Modular’s separate max package, so add it to your project first:

Terminal window
uv add max

Then move the work for one row into a function and hand it to parallelize:

from max.algorithm import parallelize
@no_inline
def matmul_parallel(a: Matrix, b: Matrix) -> Matrix:
var c = Matrix(a.rows, b.cols)
var b_ptr = b.data.unsafe_ptr()
var c_ptr = c.data.unsafe_ptr()
def one_row(i: Int) {imm a, imm b, imm b_ptr, imm c_ptr}:
for k in range(a.cols):
var a_ik = a[i, k]
var b_row = k * b.cols
var c_row = i * b.cols
def step[width: Int](j: Int) {imm a_ik, imm b_ptr, imm c_ptr, imm b_row, imm c_row}:
var c_now = c_ptr.unsafe_load[width=width](c_row + j)
var b_now = b_ptr.unsafe_load[width=width](b_row + j)
c_ptr.unsafe_store(c_row + j, c_now + a_ik * b_now)
vectorize[W](b.cols, step)
parallelize(one_row, a.rows)
return c^

The body of one_row is the Step 4 loop for one value of i. Every task writes only to its own row of C, so no two threads ever touch the same number, and no locking is needed. The Mojo Parallelize lesson explains why that matters.

On our 4-core VM this took 10 to 21 ms: about 2 times faster than Step 4. Not 4 times, even with 4 cores: starting the tasks costs time, the other programs on the VM take their share, and all cores compete for the same memory.

Here are all four versions with one timing loop, so you can run them side by side:

from std.algorithm import vectorize
from std.sys import simd_width_of
from std.time import perf_counter_ns
from max.algorithm import parallelize
comptime W = simd_width_of[DType.float64]()
struct Matrix(Movable):
var rows: Int
var cols: Int
var data: List[Float64]
def __init__(out self, rows: Int, cols: Int):
self.rows = rows
self.cols = cols
self.data = List[Float64](length=rows * cols, fill=0)
def __getitem__(self, i: Int, j: Int) -> Float64:
return self.data[i * self.cols + j]
def __setitem__(mut self, i: Int, j: Int, value: Float64):
self.data[i * self.cols + j] = value
@no_inline
def matmul_naive(a: Matrix, b: Matrix) -> Matrix:
var c = Matrix(a.rows, b.cols)
for i in range(a.rows):
for j in range(b.cols):
var total: Float64 = 0
for k in range(a.cols):
total += a[i, k] * b[k, j]
c[i, j] = total
return c^
@no_inline
def matmul_reordered(a: Matrix, b: Matrix) -> Matrix:
var c = Matrix(a.rows, b.cols)
for i in range(a.rows):
for k in range(a.cols):
var a_ik = a[i, k]
for j in range(b.cols):
c[i, j] += a_ik * b[k, j]
return c^
@no_inline
def matmul_vectorized(a: Matrix, b: Matrix) -> Matrix:
var c = Matrix(a.rows, b.cols)
var b_ptr = b.data.unsafe_ptr()
var c_ptr = c.data.unsafe_ptr()
for i in range(a.rows):
for k in range(a.cols):
var a_ik = a[i, k]
var b_row = k * b.cols
var c_row = i * c.cols
def step[width: Int](j: Int) {imm a_ik, imm b_ptr, imm c_ptr, imm b_row, imm c_row}:
var c_now = c_ptr.unsafe_load[width=width](c_row + j)
var b_now = b_ptr.unsafe_load[width=width](b_row + j)
c_ptr.unsafe_store(c_row + j, c_now + a_ik * b_now)
vectorize[W](b.cols, step)
return c^
@no_inline
def matmul_parallel(a: Matrix, b: Matrix) -> Matrix:
var c = Matrix(a.rows, b.cols)
var b_ptr = b.data.unsafe_ptr()
var c_ptr = c.data.unsafe_ptr()
def one_row(i: Int) {imm a, imm b, imm b_ptr, imm c_ptr}:
for k in range(a.cols):
var a_ik = a[i, k]
var b_row = k * b.cols
var c_row = i * b.cols
def step[width: Int](j: Int) {imm a_ik, imm b_ptr, imm c_ptr, imm b_row, imm c_row}:
var c_now = c_ptr.unsafe_load[width=width](c_row + j)
var b_now = b_ptr.unsafe_load[width=width](b_row + j)
c_ptr.unsafe_store(c_row + j, c_now + a_ik * b_now)
vectorize[W](b.cols, step)
parallelize(one_row, a.rows)
return c^
def filled(n: Int, factor: Int) -> Matrix:
var m = Matrix(n, n)
for i in range(n * n):
m.data[i] = Float64((i * factor) % 10)
return m^
def checksum(m: Matrix) -> Float64:
var total: Float64 = 0
for x in m.data:
total += x
return total
def main():
var a = filled(512, 3)
var b = filled(512, 7)
for _ in range(3):
var t0 = perf_counter_ns()
var c1 = matmul_naive(a, b)
var t1 = perf_counter_ns()
var c2 = matmul_reordered(a, b)
var t2 = perf_counter_ns()
var c3 = matmul_vectorized(a, b)
var t3 = perf_counter_ns()
var c4 = matmul_parallel(a, b)
var t4 = perf_counter_ns()
print("naive: ", checksum(c1), (t1 - t0) // 1_000_000, "ms")
print("reordered: ", checksum(c2), (t2 - t1) // 1_000_000, "ms")
print("vectorized:", checksum(c3), (t3 - t2) // 1_000_000, "ms")
print("parallel: ", checksum(c4), (t4 - t3) // 1_000_000, "ms")

Here’s one complete run on our test VM:

naive: 2717893632.0 1252 ms
reordered: 2717893632.0 634 ms
vectorized: 2717893632.0 27 ms
parallel: 2717893632.0 14 ms
naive: 2717893632.0 1042 ms
reordered: 2717893632.0 330 ms
vectorized: 2717893632.0 47 ms
parallel: 2717893632.0 21 ms
naive: 2717893632.0 976 ms
reordered: 2717893632.0 337 ms
vectorized: 2717893632.0 20 ms
parallel: 2717893632.0 16 ms

See the 634 ms and the 47 ms? Those are the VM being busy with something else for a moment. That’s why we run every version several times and look at the typical numbers, not at one lucky or unlucky round.

Put together, from all our runs on this machine:

Version 512 x 512, our test VM Compared with naive
Naive (i, j, k) about 0.8 to 1.7 s, usually about 1 s 1x
Reordered (i, k, j) about 310 to 380 ms about 3x
Vectorized about 20 to 33 ms about 40x
Parallel + vectorized about 10 to 21 ms about 80x

The checksum is the same on every line, so all four compute the same matrix. (Here all the numbers are small whole numbers, so even the different order of additions gives exactly the same sums. With messy real-world numbers, the last digits can differ slightly between versions, because floating-point addition depends on order.)

  • Try other sizes, like 256 and 1024. Time grows with the cube of the size, so 1024 takes about 8 times as long as 512.
  • Tiling. Process C in blocks of, say, 64 by 64, so the parts of A and B you’re using stay in the cache. Measure whether it helps on your machine.
  • Float32. Switch every Float64 to Float32. SIMD registers then hold twice as many numbers. Does the vectorized version get faster? (The checksum may come out slightly different, because Float32 rounds sooner.)
  • The identity matrix has 1 on the diagonal and 0 elsewhere; multiplying by it changes nothing. Write identity(n) and use it as a quick test.
  • Compare with NumPy. Call numpy.matmul from Mojo through the Mojo with NumPy lesson’s interop and time it on the same sizes.

Write def same(x: Matrix, y: Matrix) -> Bool that returns True when two matrices have the same size and every entry is equal. Use it to check matmul_reordered against matmul_naive on a 3 by 3 example.

Hint: compare rows and cols first, then loop over data.

Show solution
struct Matrix(Movable):
var rows: Int
var cols: Int
var data: List[Float64]
def __init__(out self, rows: Int, cols: Int):
self.rows = rows
self.cols = cols
self.data = List[Float64](length=rows * cols, fill=0)
def __getitem__(self, i: Int, j: Int) -> Float64:
return self.data[i * self.cols + j]
def __setitem__(mut self, i: Int, j: Int, value: Float64):
self.data[i * self.cols + j] = value
def matmul_naive(a: Matrix, b: Matrix) -> Matrix:
var c = Matrix(a.rows, b.cols)
for i in range(a.rows):
for j in range(b.cols):
var total: Float64 = 0
for k in range(a.cols):
total += a[i, k] * b[k, j]
c[i, j] = total
return c^
def matmul_reordered(a: Matrix, b: Matrix) -> Matrix:
var c = Matrix(a.rows, b.cols)
for i in range(a.rows):
for k in range(a.cols):
var a_ik = a[i, k]
for j in range(b.cols):
c[i, j] += a_ik * b[k, j]
return c^
def same(x: Matrix, y: Matrix) -> Bool:
if x.rows != y.rows or x.cols != y.cols:
return False
for i in range(len(x.data)):
if x.data[i] != y.data[i]:
return False
return True
def main():
var a = Matrix(3, 3)
var b = Matrix(3, 3)
for i in range(9):
a.data[i] = Float64(i)
b.data[i] = Float64(9 - i)
print(same(matmul_naive(a, b), matmul_reordered(a, b)))
print(same(a, b))

Output:

True
False

Checking a fast version against a simple, obviously correct one is the most useful test you can write for code like this. For floating-point data in general, compare with a small tolerance instead of !=.

  • Store a matrix as one flat list, row after row: entry (i, j) is at i * cols + j. Two-argument __getitem__ / __setitem__ give you m[i, j].
  • The textbook i, j, k order reads B down columns, which is slow. Swapping to i, k, j reads memory in order and was about 3 times faster on our VM.
  • vectorize with unsafe_load / unsafe_store does several multiply-adds per instruction. Together with pointer access, it was about 13 times faster again.
  • Rows are independent, so parallelize (from the max package in Mojo 1.2, uv add max) spreads them over cores: about 2 times more on 4 cores.
  • Always check the fast versions compute the same result, and say which machine your timings come from.

Next up: Project: GPU Image Filter, where you process an image on the CPU and see how the same job is written for a GPU.

Quick check

1. Why is the i, j, k loop order slow for a row-by-row matrix?
2. In the vectorized version, what does a_ik * b_now do when b_now is a SIMD value of 8 numbers?
3. Why don't the rows in matmul_parallel need any locking?
4. In Mojo 1.2, where does parallelize come from?