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.
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
with of size and of size . Each of the outputs is a dot product of length :
For , 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 is used by different outputs. The whole game is making those uses cost one load from memory, not .
Version 1: naive
One thread per output, a loop over :
int row = blockIdx.x * blockDim.x + threadIdx.x; // x → rowint 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 that are floats apart: 32 separate sectors for 128 useful bytes
(4.7). The writes to 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 (broadcast to
all 32 lanes) and 32 adjacent elements of , one coalesced 128-byte load. Nothing else changes.
Version 3: shared-memory tiles
Even coalesced, the kernel loads every element of and from global memory 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 threads computes a tile of . It walks along in steps of 32. At each step it loads one tile of and one of into shared memory (4.4), then every thread does 32 multiply-adds from shared memory:
__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}- 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.
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 FLOP per byte of global memory, 8 for .
Measured
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]andBs[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 🔴
cd labs/m06/6.1 && nvcc -O2 -arch=native -DUSE_CUBLAS matmul.cu -o matmul -lcublas && ./matmulSources
Check your understanding
0 / 4 answered1.How many FLOPs does a 4096 × 4096 × 4096 matmul take?
2.Why is the naive kernel (threadIdx.x → row) so slow?
3.With 32 × 32 shared-memory tiles, by how much does global memory traffic fall?
4.After tiling, the kernel is still 6.7× slower than cuBLAS. What limits it now?