L2 Intermediate · Module 6: GEMM and memory optimization

6.1Naive → coalesced → shared-memory tiled matmul

Matrix multiplication is most of an LLM's FLOPs, and the gap between a naive kernel and cuBLAS is 60×. This chapter closes the first part of that gap: fix the access pattern, then stage tiles in shared memory so each value loaded from memory is used many times. It also shows why the second step helps less than you might expect.

GPU required (Colab or a rented GPU)✦ Interactive~30 min

By the end you will be able to

  • ✓Explain why GEMM dominates LLM inference, and compute its FLOPs and minimum memory traffic
  • ✓Map threads to outputs so that global memory accesses coalesce
  • ✓Write a shared-memory tiled matmul, and derive how tiling raises arithmetic intensity
  • ✓Measure each version against cuBLAS and explain what still limits the tiled kernel

Every linear layer in a transformer is a matrix multiplication: Q, K, V and output projections, and the two or three matrices of the MLP (1.2). In prefill, these GEMMs (general matrix multiplies) are more than 90% of the FLOPs. In decode they shrink to matrix-vector products, but batching turns them back into skinny GEMMs (3.4). If you make one kernel fast, make it this one.

The arithmetic

C=A×BC = A \times B with AA of size M×KM \times K and BB of size K×NK \times N. Each of the MNM N outputs is a dot product of length KK:

FLOPs=2MNK,minimum bytes=4(MK+KN+MN) (FP32)\text{FLOPs} = 2MNK, \qquad \text{minimum bytes} = 4(MK + KN + MN) \ \text{(FP32)}

For M=N=K=4096M = N = K = 4096, that is 137 GFLOP against 201 MB: 683 FLOP per byte. A GEMM this size is deeply compute-bound (3.2), if each input is read from memory only once. Each element of AA is used by NN different outputs. The whole game is making those NN uses cost one load from memory, not NN.

Version 1: naive

One thread per output, a loop over kk:

int row = blockIdx.x * blockDim.x + threadIdx.x; // x → row
int col = blockIdx.y * blockDim.y + threadIdx.y;
float acc = 0.0f;
for (int k = 0; k < N; k++) acc += A[row * N + k] * B[k * N + col];
C[row * N + col] = acc;

It’s correct and it’s slow. The 32 threads of a warp differ in threadIdx.x, so they have different rows and the same column. At each k, the warp reads 32 elements of AA that are NN floats apart: 32 separate sectors for 128 useful bytes (4.7). The writes to CC are strided the same way.

Version 2: coalesced

Swap the mapping. If threadIdx.x picks the column, a warp shares one row: at each k it reads a single element of AA (broadcast to all 32 lanes) and 32 adjacent elements of BB, one coalesced 128-byte load. Nothing else changes.

Version 3: shared-memory tiles

Even coalesced, the kernel loads every element of AA and BB from global memory NN times. The caches absorb part of it, but every load is still an instruction and a trip through the memory pipeline.

Tiling makes the reuse explicit. A block of 32×3232 \times 32 threads computes a 32×3232 \times 32 tile of CC. It walks along kk in steps of 32. At each step it loads one 32×3232 \times 32 tile of AA and one of BB into shared memory (4.4), then every thread does 32 multiply-adds from shared memory:

labs/m06/6.1/matmul.cu
__shared__ float As[32][32], Bs[32][32];
for (int k0 = 0; k0 < N; k0 += 32) {
As[ty][tx] = A[row * N + k0 + tx]; // each thread loads one element of each tile
Bs[ty][tx] = B[(k0 + ty) * N + col];
__syncthreads(); // tiles complete before anyone reads them
for (int k = 0; k < 32; k++) acc += As[ty][k] * Bs[k][tx];
__syncthreads(); // everyone done before the tiles are overwritten
}
KernelTile
k-step 1 of 4 · click a tile of C to pick another block
A (rows of the tile)B (columns of the tile)C = A × B×=this step: the block loads one 4×4 tile of A and one of B into shared memory, once
outputs in this block
16
loads from memory so far
32
fewer than untiled
4×
FLOP per byte loaded
1.00

Each value in shared memory is used by 4 threads, so memory traffic falls by the tile width, 4×, and the intensity rises to T / 4 FLOP per byte. Bigger tiles mean more reuse, until shared memory and registers run out.

fig. 6.1One block computing one tile of C (violet). At each k-step it needs a tile of A (amber) and a tile of B (blue); faded cells are tiles already used. Compare memory loads with and without shared-memory tiles, for different tile sizes.

Each element loaded into shared memory is used by 32 threads, so global traffic falls 32×. The intensity of the inner loop rises from 0.25 to T/4T / 4 FLOP per byte of global memory, 8 for T=32T = 32.

Measured

output (RTX 3050 6GB Laptop)
C = A * B, 4096 x 4096 FP32 (137.4 GFLOP):
kernel time GFLOP/s of cuBLAS max |error|
naive 1821.42 ms 75 1.7% 3.5e-04 PASS
coalesced 256.99 ms 535 11.9% 3.5e-04 PASS
tiled 203.87 ms 674 15.0% 3.5e-04 PASS
cuBLAS 30.55 ms 4498 100.0%
  • Coalescing: 7.1×. One changed line, the biggest win in the chapter.
  • Tiling: only 1.26× more. On this GPU, the 128 KB L1 cache per SM already catches most of the coalesced kernel’s repeated loads, so making the reuse explicit buys less than the 32× drop in traffic suggests.
  • Still 6.7× slower than cuBLAS. The tiled kernel is no longer limited by DRAM. It is limited by shared memory: every FMA needs two shared-memory loads (As[ty][k] and Bs[k][tx]), and an SM can’t issue loads as fast as it can issue FMAs. Moving the bottleneck from DRAM to shared memory to registers is exactly what the next chapter does.

Lab: three matmuls and cuBLAS 🔴

Terminal window
cd labs/m06/6.1 && nvcc -O2 -arch=native -DUSE_CUBLAS matmul.cu -o matmul -lcublas && ./matmul

Sources

Check your understanding

0 / 4 answered
  1. 1.How many FLOPs does a 4096 × 4096 × 4096 matmul take?

  2. 2.Why is the naive kernel (threadIdx.x → row) so slow?

  3. 3.With 32 × 32 shared-memory tiles, by how much does global memory traffic fall?

  4. 4.After tiling, the kernel is still 6.7× slower than cuBLAS. What limits it now?