Matrix multiplication

Going 2D, then using shared memory as a hand-managed cache to cut global memory traffic.

What you'll learn
  • How to map a 2D thread grid onto a 2D output matrix
  • Why the naive kernel re-reads the same data hundreds of times
  • How tiling through shared memory turns those repeats into one read

Matrix multiplication is where the GPU starts to look like a real machine, because for the first time the naive version is correct but wasteful, and fixing it requires knowing something about the hardware.

Each output element is a dot product of a row and a column:

\[C_{ij} = \sum_{k=0}^{n-1} A_{ik} \, B_{kj}\]

One thread per output element

__global__ void matrixMul(int *a, int *b, int *c, int n) {
    int row = blockIdx.y * blockDim.y + threadIdx.y;
    int col = blockIdx.x * blockDim.x + threadIdx.x;

    int temp_sum = 0;
    if ((row < n) && (col < n)) {
        for (int k = 0; k < n; k++) {
            temp_sum += a[row * n + k] * b[k * n + col];
        }
        c[row * n + col] = temp_sum;
    }
}

The indexing idea from the previous lesson now applies twice, once per dimension, which is what dim3 is for:

int BLOCK_SIZE = 16;
int GRID_SIZE  = (int)ceil(n / BLOCK_SIZE);
dim3 grid(GRID_SIZE, GRID_SIZE);
dim3 threads(BLOCK_SIZE, BLOCK_SIZE);
matrixMul<<<grid, threads>>>(d_a, d_b, d_c, n);

The matrices are stored as flat arrays, so element \((i, j)\) lives at i * n + j. A 16×16 block means 256 threads, each computing one element of C.

Why this is slow

Count the reads. Every thread walks a full row of A and a full column of B, so the kernel performs \(2n^3\) global memory reads to produce \(n^2\) outputs. For a 1024×1024 matrix that is over two billion reads — and almost all of them are repeats, because every thread in a row reads the identical row of A.

Global memory is the slowest memory on the device. Re-reading it two billion times is the bottleneck, not the multiply-accumulate.

Tiling with shared memory

Shared memory is a small, fast scratchpad that all threads in a block share. The fix is to have the block cooperatively load a tile of A and a tile of B once, then have all 256 threads read from the scratchpad instead of global memory.

__global__ void tiledMatrixMul(int *a, int *b, int *c, int n, int tile_size) {
    __shared__ int A[SHMEM_SIZE];
    __shared__ int B[SHMEM_SIZE];

    int tx = threadIdx.x, ty = threadIdx.y;
    int row = blockIdx.y * tile_size + ty;
    int col = blockIdx.x * tile_size + tx;
    int temp_val = 0;

    // Sweep tiles across the matrix
    for (int i = 0; i < (n / tile_size); i++) {
        // Every thread loads exactly one element of each tile
        A[(ty * tile_size) + tx] = a[row * n + (i * tile_size + tx)];
        B[(ty * tile_size) + tx] = b[(i * tile_size * n + ty * n) + col];

        __syncthreads();   // wait until the whole tile has arrived

        for (int j = 0; j < tile_size; j++) {
            temp_val += A[(ty * tile_size) + j] * B[(j * tile_size) + tx];
        }

        __syncthreads();   // nobody may overwrite the tile until all are done
    }
    c[(row * n) + col] = temp_val;
}

The two __syncthreads() calls are the heart of it, and both are necessary for opposite reasons. The first stops a thread from reading a tile before its neighbours have finished writing it. The second stops a fast thread from racing ahead to the next iteration and overwriting the tile while slower threads are still reading it. Remove either and you get wrong answers that vary between runs.

With a tile size of \(T\), each element is read from global memory \(n/T\) times instead of \(n\) — a 16× reduction in traffic for 16×16 tiles.

One block computing its patch of C. Each step loads the next tile of A and B into shared memory; the faint cells are the full row and column the block needs overall.

What the versions measure

Version Technique Speed vs. naive
01matrix_mul.cu one thread per element 1×
02cache_tiled_matrix_mul.cu shared-memory tiling ~2.8×
03alignment_matrix.cu transposed for coalesced access ~1.8×
04cublas_matmul.cu cuBLAS GEMM ~8.5×

cuBLAS wins by a wide margin, and that is the practical lesson: write the tiled version once to understand it, then use the vendor library in real code.

Tiling buys almost 3×; the vendor library buys three times more again.

Run it

cd cuda_from_scratch/02matrix_multiplication
nvcc -o matmul 01matrix_mul.cu
./matmul

nvcc -o matmul_tiled 02cache_tiled_matrix_mul.cu && ./matmul_tiled
nvcc -o matmul_cublas 04cublas_matmul.cu -lcublas && ./matmul_cublas

Try it yourself. The tiled kernel assumes n divides evenly by tile_size — its loop runs n / tile_size times with no remainder handling. Work out what it computes for n = 1000 with 16×16 tiles, then fix it by guarding the tile loads and padding with zeros. Afterwards, try block sizes of 8, 16 and 32 and see which wins on your GPU.

View source on GitHub →