Phase 02/Writing and measuring kernels/Matrix multiplication on GPUs
PHASE 02 · Writing and measuring kernels

Matrix multiplication on GPUs

0%
8 h6 subtopics3 lessons · 2 required
In plain English

Almost all the arithmetic in a language model is multiplying two big grids of numbers together. The obvious way to do it on a GPU is to give each worker one cell of the answer and have them fetch everything they need from the slow pantry. That works but the workers spend all day walking. The fast way is like a team of builders who carry one pallet of bricks to the site, use every brick in that pallet before fetching the next, and lay many bricks per trip. In GPU terms, blocks load small tiles of both matrices into shared memory, reuse each number dozens of times from there, and modern chips add a special "tensor core" that lays an entire small tile of bricks in one move. You will build this up step by step and watch the speed climb toward what cuBLAS, NVIDIA's library, achieves.

Why it matters

Every linear layer, attention score and output projection is a matmul; the prefill phase of inference is almost pure matmul. Understanding tiling and tensor cores explains why FP16 is faster than FP32, why shapes that are not multiples of 8 or 64 are slow, and how FlashAttention works.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Implement naive, shared-memory tiled and register-tiled matmul kernels.
  • Explain why tiling raises arithmetic intensity and by how much.
  • Describe what a tensor core computes and how shapes affect its use.
  • Compare your kernels to cuBLAS and account for the remaining gap.

Key concepts

GEMM
General matrix multiply, C = alpha*A*B + beta*C; the BLAS name for the operation.
Tiling / blocking
Partitioning C into tiles so that one block computes a tile using slices of A and B loaded once into shared memory.
Arithmetic intensity of a tile
For a TxT tile each loaded element is used T times, so intensity grows linearly with tile size.
Register tiling
Each thread computes a small sub-tile (for example 8x8) of outputs held in registers to cut shared-memory traffic.
Tensor core / MMA
Hardware that performs a fixed-size matrix multiply-accumulate (for example 16x16x16 FP16) per instruction.
cuBLAS / CUTLASS
NVIDIA's tuned GEMM library and its open-source template library; the baselines to measure against.
Padding and alignment
Tensor cores need dimensions that are multiples of 8 (FP16) to be used; odd shapes fall back to slower paths.

Subtopics

  1. 1. Naive matmul and its bandwidth problem

    One thread per output; 2N FLOPs against 2N global loads per output gives intensity about 1 FLOP/byte for FP32.

  2. 2. Shared-memory tiling

    The load-tile, syncthreads, multiply-accumulate, syncthreads loop over the K dimension; coalesced tile loads.

  3. 3. Register tiling and vectorised loads

    Each thread owns a micro-tile of outputs; float4 loads; avoiding shared-memory bank conflicts with padding.

  4. 4. Tensor cores and WMMA

    The mma.sync / wmma API, supported shapes and dtypes on T4 (Turing) versus A100, and FP32 accumulation.

  5. 5. Why cuBLAS wins

    Software pipelining, double-buffered shared memory, swizzled layouts and auto-tuned tile shapes per architecture.

  6. 6. Matmul shapes in LLM inference

    Prefill as [tokens x d_model] x [d_model x 4 d_model]; decode as a skinny GEMV; why batch size changes the regime.

Resources

article
repo
  • CUTLASS ↗
    Read the "efficient GEMM" doc in media/docs to see the full hierarchy.

Hands-on lessons

L1

Tiled matmul in NumPy, counting bytes

CPU · your Macscript60 minrequired

Goal · A Python simulation of block-tiled matmul that counts "global memory" loads for several tile sizes and shows arithmetic intensity rising with T.

  1. 1Write naive_matmul(A, B) with explicit triple loops over small matrices (N=64) and count every element read from A and B.
  2. 2Write tiled_matmul(A, B, T) that loads TxT tiles into local arrays, counts one load per tile element, and multiplies from the tiles.
  3. 3Verify both against numpy A @ B.
  4. 4Tabulate loads and FLOPs for T in 1, 4, 8, 16, 32 and compute FLOPs per byte assuming float32.
  5. 5Plot intensity versus T and mark the T4 ridge point from your roofline lesson; state the smallest T that would be compute-bound.
Deliverable
tiled_sim.py and the intensity table.
Check
Results match numpy within 1e-4; loads for tile size T are exactly (2 N^3 / T) elements, so intensity scales linearly with T.
L2

Climb from naive to tiled to tensor cores on a T4

Colab T4 · freenotebook180 minrequired

Goal · Three CUDA matmul kernels (naive, shared-memory tiled, WMMA tensor-core) benchmarked at N=4096 against torch.matmul, with a plot of GFLOP/s per version.

  1. 1Use %%writefile and nvcc to build a naive FP32 kernel, one thread per output, and verify against a CPU reference at N=512.
  2. 2Add the 32x32 shared-memory tiled kernel from the programming guide; verify, then time both at N=1024, 2048, 4096 with CUDA events.
  3. 3Add register tiling where each thread computes a 4x4 micro-tile; time again.
  4. 4Write an FP16 kernel using nvcuda::wmma with 16x16x16 fragments and FP32 accumulation (compile with -arch=sm_75).
  5. 5Measure torch.matmul in FP32 and FP16 at the same sizes as the cuBLAS baseline.
  6. 6Plot GFLOP/s for all versions and compute each as a percentage of the T4 peak (8.1 FP32, 65 FP16 tensor).
  7. 7Write a paragraph explaining the remaining gap to cuBLAS using the Boehm worklog as a guide.
Deliverable
matmul.cu with all kernels, the GFLOP/s plot and the explanatory paragraph.
Check
All kernels match the reference within 1e-2 relative error (FP16 within 5e-2); tiled is at least 3x faster than naive; WMMA is at least 2x faster than your best FP32 kernel at N=4096.
Fallback
Kaggle T4; or follow the Boehm worklog and annotate each kernel in a document instead.
L3

Measure the tensor-core alignment cliff from PyTorch

Colab T4 · freeexperiment45 minoptional

Goal · A plot showing torch.matmul FP16 throughput for N from 4090 to 4104, revealing the drop for shapes that are not multiples of 8.

  1. 1On a T4, time torch.matmul for float16 square matrices with N in range(4090, 4105) using torch.cuda.Event and 20 iterations each.
  2. 2Repeat for float32 to show the effect is absent or much smaller.
  3. 3Plot TFLOP/s versus N for both dtypes.
  4. 4Pad a 4093 x 4093 FP16 matmul to 4096 and show the padded version is faster despite doing more work.
Deliverable
Notebook with the plot and the padded-versus-unpadded timings.
Check
FP16 throughput at N=4096 exceeds that at N=4093 by at least 20 percent; FP32 shows under 5 percent variation across the range.
Fallback
Kaggle T4; the shape sensitivity also appears on any Volta or newer GPU.

Build your own

Build your own SGEMM

CUDA C++Colab T4 · free~8 h

An fp32 matrix multiply that climbs from a naive kernel to shared-memory tiling, 2D register blocking and vectorised loads, reported at every step as a percentage of cuBLAS on a T4, with an optional tensor-core finale.

The real thing: github.com/siboehm/SGEMM_CUDA ↗

How you know a stage passes

sgemm.cu keeps every kernel behind a `-k N` flag. The driver computes C = alpha * A @ B + beta * C for square sizes 512, 1024, 2048 and 4096, verifies against cuBLAS (max relative error below 1e-3 in fp32), and prints GFLOP/s and percent of cuBLAS from CUDA events (median of 10). tests/test_sgemm.py, written first, runs the binary via subprocess and asserts correctness plus the speed-up relationships below; plot.py draws gflops_by_stage.png. Run `pytest -q` on a Colab T4.

Stages, in order. Each one leaves you with something that runs.0/8
  1. 01naive, one thread per output element
    Each thread loops over K reading a row of A and a column of B from global memory; correct for every size.
    test · Max relative error below 1e-3 against cuBLAS at all four sizes; GFLOP/s recorded, expected under 10 percent of cuBLAS.
  2. 02coalesce the global loads
    Remap thread indices so consecutive threads in a warp read consecutive elements of B and write consecutive elements of C.
    test · At least 2x faster than s1 at N = 4096 with the same error bound.
  3. 03shared-memory tiling
    32 x 32 tiles of A and B staged through __shared__ with __syncthreads between load and compute phases, each loaded element reused 32 times.
    test · At least 1.3x faster than s2 at N = 4096; the ncu or event-derived arithmetic intensity rises by about 32x over s2 and is reported.
  4. 041D register blocking
    Each thread computes a column of 8 outputs, holding a B value in a register and reusing it across 8 FMAs so the kernel is no longer shared-memory-bandwidth-bound.
    test · At least 2x faster than s3 at N = 4096.
  5. 052D register blocking
    128 x 128 block tiles with BK = 8 and an 8 x 8 micro-tile of outputs per thread accumulated in 64 registers.
    test · At least 1.5x faster than s4 and at least 50 percent of cuBLAS at N = 4096; `nvcc --ptxas-options=-v` shows no register spills.
  6. 06float4 loads and a transposed A tile
    128-bit vectorised global loads and stores, with the A tile stored transposed in shared memory so the inner loop reads it with conflict-free broadcasts.
    test · Faster than s5 and at least 60 percent of cuBLAS at N = 4096 with the error bound intact.
  7. 07autotune the tile shape
    A script compiles the s6 kernel with -D flags for BM, BN, BK, TM and TN over a small grid, times each at every size, and records the best configuration per N.
    test · The best configuration reaches at least 70 percent of cuBLAS at N = 4096 (cuBLAS SGEMM on a Colab T4 reaches about 4-5 TFLOPS of the 8.1 peak, so expect roughly 3-3.5 TFLOPS); gflops_by_stage.png is in the README.
  8. 08fp16 tensor cores with WMMA
    An fp16 kernel using nvcuda::wmma 16x16x16 fragments with fp32 accumulation, compiled for sm_75, compared with torch.matmul in float16.
    test · Max relative error below 5e-2 against torch fp16 matmul; at least 2x the GFLOP/s of your best fp32 kernel at N = 4096; percent of the 65 TFLOPS T4 tensor-core peak reported.

Knowledge check

QWhy does a 32x32 shared-memory tile raise arithmetic intensity by about 32x over the naive kernel?

Each element loaded from global memory into the tile is reused by 32 threads instead of one, so bytes moved drop by 32x for the same FLOPs.

QWhat does one WMMA 16x16x16 instruction compute?

D = A*B + C for a 16x16 A tile and 16x16 B tile (FP16) with 16x16 FP32 accumulators, executed cooperatively by one warp.

QWhy is decode-phase matmul at batch 1 closer to a GEMV than a GEMM, and what does that imply?

The activation has one row, so each weight is used once; intensity is tiny and the operation is memory-bound regardless of tiling.

QName two things cuBLAS does that a simple tiled kernel does not.

Double-buffers shared memory to overlap loads with compute, and uses architecture-specific tile shapes and swizzled layouts to avoid bank conflicts.

Completion

  • All 6 subtopics marked done
  • All 2 required lessons done
  • All six subtopics marked completed.
  • Lessons l1 and l2 saved with checks passing and the GFLOP/s plot recorded.
  • Can sketch the tiled matmul loop with __syncthreads placement from memory.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →