Skip to content

Mojo GPU Matrix Multiply

Matrix multiplication is the classic GPU example, and not by accident: it’s the operation at the heart of neural networks, graphics and a lot of science code. It’s also a perfect GPU job, because every cell of the result can be computed on its own. This page builds it step by step: what it computes, a CPU version, a simple kernel with one thread per cell, and a faster kernel that loads tiles into shared memory. Along the way you’ll see why the same math can run ten times faster just by changing how threads touch memory.

Multiply an M by K matrix A with a K by N matrix B, and you get an M by N matrix C. Each cell of C is a dot product: walk along row row of A and down column col of B, multiply the pairs and add them up:

C[row, col] = A[row, 0] * B[0, col] + A[row, 1] * B[1, col] + ... + A[row, K-1] * B[K-1, col]

Here it is with three plain loops, with each matrix stored row by row in a flat list:

def main():
# A is 2x3, B is 3x2, so C = A @ B is 2x2. Stored row by row.
var a: List[Float32] = [1, 2, 3, 4, 5, 6]
var b: List[Float32] = [7, 8, 9, 10, 11, 12]
comptime M = 2
comptime K = 3
comptime N = 2
var c = List[Float32](length=M * N, fill=0)
for row in range(M):
for col in range(N):
var total: Float32 = 0
for k in range(K):
total += a[row * K + k] * b[k * N + col]
c[row * N + col] = total
print(c)

Output:

[58.0, 64.0, 139.0, 154.0]

The first cell is row 0 of A (1, 2, 3) times column 0 of B (7, 9, 11): 1 * 7 + 2 * 9 + 3 * 11 = 58. In Python with NumPy you’d write a @ b; NumPy calls a tuned library for you. Here you see the loops that such libraries are built around.

The row * K + k math is where bugs hide. The LayoutTensor page showed how TileTensor does it for you, and it works on the CPU too:

from layout import TileTensor, row_major
comptime M = 2
comptime K = 3
comptime N = 2
def main():
var a_data: List[Float32] = [1, 2, 3, 4, 5, 6]
var b_data: List[Float32] = [7, 8, 9, 10, 11, 12]
var c_data = List[Float32](length=M * N, fill=0)
var a = TileTensor(a_data, row_major[M, K]())
var b = TileTensor(b_data, row_major[K, N]())
var c = TileTensor(c_data, row_major[M, N]())
# One "thread" per output cell: (row, col).
for row in range(M):
for col in range(N):
var total: Float32 = 0
for k in range(K):
total += a[row, k] * b[k, col]
c[row, col] = total
print(c)

Output:

[[58.0, 64.0], [139.0, 154.0]]

Look at the two outer loops. Nothing in the body for cell (0, 1) depends on cell (0, 0). Every cell is an independent little job, which is exactly what a GPU wants: one thread per output cell, with row and col coming from the thread’s index instead of a loop.

Here’s that idea as a complete GPU program. It multiplies a 100 by 50 matrix by a 50 by 80 one, then checks every cell against a plain CPU calculation:

from std.math import ceildiv
from std.sys import has_accelerator
from max.gpu import global_idx
from max.gpu.host import DeviceContext
from layout import TileTensor, row_major
comptime dtype = DType.float32
comptime M = 100
comptime K = 50
comptime N = 80
comptime a_layout = row_major[M, K]()
comptime b_layout = row_major[K, N]()
comptime c_layout = row_major[M, N]()
comptime BLOCK = 16
def matmul_naive(
a: TileTensor[dtype, type_of(a_layout), ImmutAnyOrigin],
b: TileTensor[dtype, type_of(b_layout), ImmutAnyOrigin],
c: TileTensor[dtype, type_of(c_layout), MutAnyOrigin],
):
var row = global_idx.y
var col = global_idx.x
if row < M and col < N:
var total: c.ElementType = 0
for k in range(K):
total += a[row, k] * b[k, col]
c[row, col] = total
def main() raises:
comptime if not has_accelerator():
print("No compatible GPU found")
else:
var ctx = DeviceContext()
var a_host = ctx.enqueue_create_host_buffer[dtype](M * K)
var b_host = ctx.enqueue_create_host_buffer[dtype](K * N)
var c_host = ctx.enqueue_create_host_buffer[dtype](M * N)
ctx.synchronize()
for i in range(M * K):
a_host[i] = Float32(i % 7)
for i in range(K * N):
b_host[i] = Float32(i % 5)
var a_dev = ctx.enqueue_create_buffer[dtype](M * K)
var b_dev = ctx.enqueue_create_buffer[dtype](K * N)
var c_dev = ctx.enqueue_create_buffer[dtype](M * N)
ctx.enqueue_copy(dst_buf=a_dev, src_buf=a_host)
ctx.enqueue_copy(dst_buf=b_dev, src_buf=b_host)
ctx.enqueue_function[matmul_naive](
TileTensor(a_dev, a_layout),
TileTensor(b_dev, b_layout),
TileTensor(c_dev, c_layout),
grid_dim=(ceildiv(N, BLOCK), ceildiv(M, BLOCK)),
block_dim=(BLOCK, BLOCK),
)
ctx.enqueue_copy(dst_buf=c_host, src_buf=c_dev)
ctx.synchronize()
# Check every cell against a plain CPU calculation.
var wrong = 0
for row in range(M):
for col in range(N):
var expected: Float32 = 0
for k in range(K):
expected += a_host[row * K + k] * b_host[k * N + col]
if c_host[row * N + col] != expected:
wrong += 1
print("cells:", M * N, "wrong:", wrong)

How it fits together:

  • The kernel body is the CPU loop body from above. The two outer loops are gone: col comes from global_idx.x and row from global_idx.y.
  • The grid is 2D: ceildiv(N, BLOCK) blocks across (columns first, as on the threads page) and ceildiv(M, BLOCK) down, each block 16 by 16 threads. That’s 5 by 7 blocks, 8,960 threads for 8,000 cells, so the kernel checks row < M and col < N.
  • total is a local variable, so it lives in the thread’s own fast storage. The thread only writes to c once, at the end. c.ElementType is the tensor’s element type.
  • The inputs are small whole numbers (i % 7, i % 5), so every sum is exact in Float32, and the CPU check can compare with !=. With real data, compare with a small tolerance instead, because the GPU may add in a different order.

We compiled this program for NVIDIA and AMD targets but couldn’t run it. If the kernel is right, it prints cells: 8000 wrong: 0.

Modular’s matrix multiplication guide starts with almost the same kernel, with one difference: its “naive” version maps the thread’s x index to rows. Its next version, “coalescing”, swaps that so x goes to columns, which is what the kernel above does.

Why would that matter? Threads with neighbouring x indexes run together in a warp. With x mapped to columns, neighbouring threads read neighbouring elements of B and write neighbouring elements of C, which sit next to each other in memory (row-major). The GPU can then combine those reads into a few wide memory transactions. That’s called memory coalescing. With x mapped to rows, neighbouring threads touch elements a whole row apart, and the GPU needs many separate memory accesses for the same work.

On an NVIDIA A100 with 4096 by 4096 float32 matrices, Modular measured these speeds (in billions of floating-point operations per second, higher is better):

Kernel GFLOPS/s (Modular’s A100 numbers)
naive (x mapped to rows) 292
coalescing (x mapped to columns) 2936
tiled (shared memory) 3943
tiled_register 7078
block_tiled 10661
block_tiled_vectorized 10663

So swapping two lines made it about 10 times faster on their GPU. The guide says the numbers will differ on other GPUs, but the order should be similar. To put the rates in perspective: one 4096 by 4096 multiplication is 2 * 4096³, about 137 billion floating-point operations. At 292 GFLOPS/s that’s roughly half a second; at 10,663 GFLOPS/s it’s about 13 milliseconds. (That’s arithmetic on Modular’s published numbers, not a measurement of ours.)

Even the coalesced kernel reads every element of A and B from global memory many times: each element of A is read once for every column of C. The next step is tiling. A block of threads works together on one 16 by 16 tile of C:

  1. Every thread loads one element of a 16 by 16 tile of A and one of B into shared memory (fast memory that the whole block shares).
  2. barrier() makes every thread wait until all the loads are done.
  3. Each thread computes its part of the dot product from shared memory, which is much faster than global memory.
  4. Another barrier(), so nobody overwrites the tiles while others still read them. Then on to the next pair of tiles.

This kernel is from Modular’s GPU block and warp guide, with some comments removed. It multiplies two 64 by 64 matrices:

from std.math import ceildiv
from std.sys import exit, has_accelerator
from max.gpu.sync import barrier
from max.gpu.host import DeviceContext
from max.gpu import thread_idx, block_idx
from layout import TileTensor, stack_allocation
from layout.tile_layout import row_major
comptime float_dtype = DType.float32
comptime MATRIX_SIZE = 64 # 64x64 matrices
comptime MATRIX_M = MATRIX_SIZE
comptime MATRIX_N = MATRIX_SIZE
comptime MATRIX_K = MATRIX_SIZE
comptime TILE_SIZE = 16 # 16x16 tiles
comptime TILE_M = TILE_SIZE
comptime TILE_N = TILE_SIZE
comptime TILE_K = TILE_SIZE
comptime NUM_TILES_PER_SIDE = MATRIX_SIZE // TILE_SIZE # 4
comptime matrix_a_layout = row_major[MATRIX_M, MATRIX_K]()
comptime matrix_b_layout = row_major[MATRIX_K, MATRIX_N]()
comptime matrix_c_layout = row_major[MATRIX_M, MATRIX_N]()
comptime tile_a_layout = row_major[TILE_M, TILE_K]()
comptime tile_b_layout = row_major[TILE_K, TILE_N]()
def tiled_matmul_kernel(
matrix_a: TileTensor[float_dtype, type_of(matrix_a_layout), ImmutAnyOrigin],
matrix_b: TileTensor[float_dtype, type_of(matrix_b_layout), ImmutAnyOrigin],
matrix_c: TileTensor[float_dtype, type_of(matrix_c_layout), MutAnyOrigin],
):
var thread_x = thread_idx.x
var thread_y = thread_idx.y
var block_x = block_idx.x
var block_y = block_idx.y
var global_row = block_y * TILE_M + thread_y
var global_col = block_x * TILE_N + thread_x
var tile_row_start = block_y * TILE_M
var tile_col_start = block_x * TILE_N
# Allocate shared memory tiles for fast on-chip access
var tile_a_shared = stack_allocation[
float_dtype, address_space=.SHARED
](tile_a_layout)
var tile_b_shared = stack_allocation[
float_dtype, address_space=.SHARED
](tile_b_layout)
var accumulator: matrix_c.ElementType = 0.0
# Iterate through tiles along K dimension
comptime for k_tile in range(0, MATRIX_K, TILE_K):
var a_global_row = tile_row_start + thread_y
var a_global_col = k_tile + thread_x
var b_global_row = k_tile + thread_y
var b_global_col = tile_col_start + thread_x
var load_a_valid = (a_global_row < MATRIX_M) and (
a_global_col < MATRIX_K
)
var load_b_valid = (b_global_row < MATRIX_K) and (
b_global_col < MATRIX_N
)
# Load tiles into shared memory with bounds checking
if load_a_valid:
tile_a_shared[thread_y, thread_x] = matrix_a[
a_global_row, a_global_col
]
else:
tile_a_shared[thread_y, thread_x] = 0.0
if load_b_valid:
tile_b_shared[thread_y, thread_x] = matrix_b[
b_global_row, b_global_col
]
else:
tile_b_shared[thread_y, thread_x] = 0.0
# Ensure all threads finish loading tiles before any thread starts computing
barrier()
# Compute dot product using shared memory tiles
comptime for k in range(TILE_K):
var a_element = tile_a_shared[thread_y, k]
var b_element = tile_b_shared[k, thread_x]
accumulator += a_element * b_element
# Ensure all threads finish computing before any thread loads next tiles
barrier()
# Write final result to global memory with bounds checking
if (global_row < MATRIX_M) and (global_col < MATRIX_N):
matrix_c[global_row, global_col] = accumulator

The official guide shows only the kernel. We added a main like the one in kernel 1 (launched with grid_dim=(NUM_TILES_PER_SIDE, NUM_TILES_PER_SIDE) and block_dim=(TILE_SIZE, TILE_SIZE)) and compiled it for NVIDIA and AMD; we couldn’t run it. The new pieces:

  • stack_allocation[float_dtype, address_space=.SHARED](tile_a_layout) (from layout) gives a TileTensor in shared memory. Despite the name, it’s set up at compile time, and every thread in the block sees the same tile.
  • barrier() (from max.gpu.sync) is the meeting point. No thread in the block passes it until all of them have reached it. The official guide warns that every thread must reach the same barrier(); putting one inside an if that only some threads take makes the kernel hang.
  • comptime for unrolls the loops when the program compiles, because the sizes are compile-time constants (see comptime control flow).
  • Out-of-range loads write 0.0 into the tile instead of reading past the end of a matrix. Zeros add nothing to a dot product, so they’re harmless.

Use the TileTensor CPU version to multiply A = [[1, 2], [3, 4], [5, 6]] by B = [[1, 0, 2], [0, 1, 3]]. What’s C?

Hint: M is 3, K is 2, N is 3; store each matrix row by row.

Show solution
from layout import TileTensor, row_major
comptime M = 3
comptime K = 2
comptime N = 3
def main():
var a_data: List[Float32] = [1, 2, 3, 4, 5, 6]
var b_data: List[Float32] = [1, 0, 2, 0, 1, 3]
var c_data = List[Float32](length=M * N, fill=0)
var a = TileTensor(a_data, row_major[M, K]())
var b = TileTensor(b_data, row_major[K, N]())
var c = TileTensor(c_data, row_major[M, N]())
for row in range(M):
for col in range(N):
var total: Float32 = 0
for k in range(K):
total += a[row, k] * b[k, col]
c[row, col] = total
print(c)

Output:

[[1.0, 2.0, 8.0], [3.0, 4.0, 18.0], [5.0, 6.0, 28.0]]

The first two columns of B are an identity matrix, so they copy A’s columns. The last column is 2 * first + 3 * second of each row: 2 + 6 = 8, 6 + 12 = 18, 10 + 18 = 28.

For kernel 1 with M = 100, N = 80, K = 50 and 16 by 16 blocks, work out grid_dim, the number of threads, and the number of multiply-adds the whole kernel does.

Hint: columns first in grid_dim; each output cell does K multiply-adds.

Show solution
from std.math import ceildiv
comptime M = 100
comptime N = 80
comptime K = 50
comptime BLOCK = 16
def main():
var grid_x = ceildiv(N, BLOCK)
var grid_y = ceildiv(M, BLOCK)
print(t"grid_dim = ({grid_x}, {grid_y})")
print("threads:", grid_x * grid_y * BLOCK * BLOCK, "output cells:", M * N)
print("multiply-adds:", M * N * K)

Output:

grid_dim = (5, 7)
threads: 8960 output cells: 8000
multiply-adds: 400000

80 columns fit exactly in 5 blocks of 16, but 100 rows need 7 (the last one partly empty). Each of the 8,000 cells does 50 multiply-adds.

  • Each cell of C = A @ B is a dot product of a row of A and a column of B, and every cell is independent: a perfect fit for one GPU thread per cell.
  • Write the CPU version first (with TileTensor it reads a[row, k] * b[k, col]), then turn the two outer loops into global_idx.y and global_idx.x.
  • Map x to columns: neighbouring threads then touch neighbouring memory (coalescing). Modular measured about 10 times the speed of the x-to-rows version on an A100.
  • Tiling loads blocks of A and B into shared memory (stack_allocation[..., address_space=.SHARED]), with barrier() between loading and using them.
  • Every thread must reach the same barrier(), or the kernel hangs.
  • Check GPU results against a CPU version, and use a tuned library for real work.

Next up: Mojo and MAX, what Modular’s MAX is and when you’d use it.

Quick check

1. Why is matrix multiplication a good fit for a GPU?
2. In the naive kernel, why use col = global_idx.x instead of row = global_idx.x?
3. What does the first barrier() in the tiled kernel protect against?
4. What happens if only some threads in a block reach a barrier() because it is inside an if?