GPU kernels in Python with Numba
A tiled matrix multiplication with shared memory, written in Python — and three details that decide whether it is correct and how fast it looks.
- Write a CUDA kernel in Python with @cuda.jit
- Follow the shared-memory tiling pattern and its two barriers
- Time GPU work correctly
Numba compiles a subset of Python to machine code, and with @cuda.jit to GPU kernels. The repository’s kernel is the classic tiled matrix multiplication from the CUDA course, line for line:
TPB = 16
@cuda.jit
def matmul(A, B, C):
sA = cuda.shared.array(shape=(TPB, TPB), dtype=float32)
sB = cuda.shared.array(shape=(TPB, TPB), dtype=float32)
x, y = cuda.grid(2)
tx, ty = cuda.threadIdx.x, cuda.threadIdx.y
tmp = 0.
for i in range(cuda.gridDim.x):
sA[tx, ty] = A[x, ty + i * TPB]
sB[tx, ty] = B[tx + i * TPB, y]
cuda.syncthreads() # tile fully loaded
for j in range(TPB):
tmp += sA[tx, j] * sB[j, ty]
cuda.syncthreads() # everyone done before the next load
C[x, y] = tmp
Each block copies one 16×16 tile of A and one of B into fast shared memory — every thread loads one value of each — and every loaded value is then read by 16 threads instead of being fetched from global memory 16 times. The two barriers keep threads from reading a tile before it is loaded or overwriting it while others still read. The launch uses a (250, 250) grid of (16, 16) blocks for the 4000×4000 matrices.
Three details to fix
The bounds check. The kernel returns early with if x >= C.shape[0] and y >= C.shape[1]. It should be or — a thread is outside the matrix if either index is — and returning early is unsafe anyway, because the returned threads never reach cuda.syncthreads(). The safe pattern is to let every thread take part in the loop, load a zero when its index is out of range, and only guard the final write. With 4000 = 250 × 16 no thread is out of range, which is why the script works; a size like 4001 would expose it.
The return value. C = matmul[blockspergrid, threadsperblock](A, B, C) assigns the result of a kernel launch, which is always None. The product was written into the original C, but the name C no longer refers to it. Launch the kernel as a statement and keep using C.
The timing. The script times cp.dot(A, B, C) with two time.time() calls. GPU work is asynchronous: the call returns as soon as the work is queued, so the measured time can be far shorter than the multiplication. Synchronise before stopping the clock — cp.cuda.Device().synchronize() — or use CUDA events. Timing the Numba kernel the same way, after a warm-up call that absorbs the JIT compile, gives a fair comparison with cuBLAS behind cp.dot.
These are exactly the issues the CUDA course discusses in C++; the language changed, the GPU did not.
Try it yourself. On a machine with a GPU, fix the bounds check and run with SIZE = 4001, comparing against cp.dot with cp.allclose. Then time both correctly. How far is the hand-written kernel from cuBLAS, and why?