Shared memory tiling and a tiled matmul
Why a naive matrix multiply is starved for data, how shared-memory tiles cut global memory traffic by the tile size, why that alone still isn't enough, and how register blocking (each thread computing a small grid of outputs) raises arithmetic intensity until the kernel can approach the compute roofline. You write three versions and compare them with cuBLAS.
By Sandip Maity, Applied AI Engineer
Matrix multiplication is where the FLOPs are. Every linear layer in a transformer is one, and in prefill or at large batch they're compute-bound (roofline). This lesson builds a matmul from scratch, in three steps, and each step fixes exactly one bottleneck. By the end you'll understand what every high-performance GEMM library is doing, even the ones that look like magic.
We use FP32 on ordinary CUDA cores here, so the ideas stand alone. The next-but-one lesson moves the same structure onto tensor cores.
The problem: , with of shape , of shape , all row-major. Each output is a dot product of a row of and a column of : FLOPs. The whole thing is FLOPs.
#Version 1: one thread per output
__global__ void sgemm_naive(const float* A, const float* B, float* C, int M, int N, int K) {
int r = blockIdx.y * blockDim.y + threadIdx.y;
int c = blockIdx.x * blockDim.x + threadIdx.x;
if (r >= M || c >= N) return;
float acc = 0.f;
for (int k = 0; k < K; k++) acc += A[r * K + k] * B[k * N + c];
C[r * N + c] = acc;
}
// launch: dim3 block(32, 32); dim3 grid((N + 31) / 32, (M + 31) / 32);Check the access pattern per warp (32 threads with the same r, consecutive c): B[k * N + c] is coalesced. A[r * K + k] is the same address for every thread in the warp, which is a broadcast and costs one sector. So far so good.
The problem is reuse. Every thread reads its whole row of and column of from global memory: two 4-byte loads per multiply-add. That's FLOPs per byte. The T4's balance point is about FLOPs per byte. On paper this kernel is 100 times on the wrong side. The L1 and L2 caches save it from being quite that bad, because neighbouring threads ask for the same data, but it's still far from the compute limit.
#Version 2: shared-memory tiles
The fix is to load each piece of data from global memory once per block and let every thread in the block reuse it from shared memory.
Split the work into 32 by 32 output tiles, one block each. To compute its tile, a block walks along in steps of 32. At each step it loads a 32 by 32 tile of and a 32 by 32 tile of into shared memory, then every thread does 32 multiply-adds from shared memory. Step through it:
A (rows × K)
B (K × cols)
C
Step 1 of 4: tile k = 0
The block loads tile (1, 0) of A and tile (0, 2) of B into shared memory once, syncs, then each of its threads does 32 multiply-adds from shared memory. Without tiling, each of the 1,024 threads would read those values from DRAM itself.
A 4 × 4 grid of 32 × 32 tiles. The highlighted block owns tile (1, 2) of C and walks along K one tile at a time.
#define T 32
__global__ void sgemm_tiled(const float* A, const float* B, float* C, int M, int N, int K) {
__shared__ float As[T][T], Bs[T][T];
int r = blockIdx.y * T + threadIdx.y, c = blockIdx.x * T + threadIdx.x;
float acc = 0.f;
for (int k0 = 0; k0 < K; k0 += T) {
As[threadIdx.y][threadIdx.x] = (r < M && k0 + threadIdx.x < K) ? A[r * K + k0 + threadIdx.x] : 0.f;
Bs[threadIdx.y][threadIdx.x] = (k0 + threadIdx.y < K && c < N) ? B[(k0 + threadIdx.y) * N + c] : 0.f;
__syncthreads(); // the tile is fully loaded
for (int k = 0; k < T; k++) acc += As[threadIdx.y][k] * Bs[k][threadIdx.x];
__syncthreads(); // everyone is done reading before the next load
}
if (r < M && c < N) C[r * N + c] = acc;
}Now each element of and is loaded from global memory once per tile and used by 32 threads. Global traffic falls 32 times, and intensity rises to about FLOPs per byte.
Both __syncthreads() calls matter. The first makes sure the whole tile is loaded before anyone reads it. The second makes sure nobody starts overwriting the tile with the next slice while slower threads are still reading it. Remove the second and you'll get answers that are almost right, which is the worst kind of bug.
Pro content
Keep reading with Inference Academy Pro
Unlock the rest of this lesson, plus every advanced lesson, hands-on lab, the larger playground models and completion certificates.
Still to come in this lesson
- Version 3: register blocking
- Lab: run all three and compare with cuBLAS
- Why this matters for inference
- What you can now do
- Common mistakes
- Exercise
- Going deeper
You will be able to answer
- In a naive matmul, each thread computes one output and reads a row of A and a column of B from global memory. What is its global arithmetic intensity?
- With 32 by 32 shared-memory tiles, how many times is each element of A read from global memory per block, compared with the naive kernel?
- Why does register blocking (each thread computing a 4 by 4 patch of outputs) speed up the tiled kernel?
- A block tile of BM by BN outputs uses a BK-wide slice of K. What is its global arithmetic intensity in FP32?
- Why are the two __syncthreads() calls in the tile loop both needed?