Count global memory loads for naive vs tiled matmul

This is a counting exercise that models GPU memory traffic; no GPU is involved.

For C = A @ B with A (M, K) and B (K, N):
- Naive kernel: each of the M * N output threads reads a full row of A and a full column of B from global memory.
- Tiled kernel with tile size T (T divides M, N and K): each (T x T) output tile loops over K / T steps; at each step the block loads one T x T tile of A and one of B into shared memory.

Write matmul_loads(M, N, K, T) returning (naive_loads, tiled_loads, ratio) where loads count individual elements read from global memory and ratio = naive / tiled.

Signaturedef matmul_loads(M, N, K, T)

Understand the idea

Reading global GPU memory is slow, so the number of elements loaded often decides speed. In a naive matmul each output element reads its full row of A and full column of B, so the same inputs are fetched again and again. A tiled kernel loads T by T tiles of A and B into fast shared memory once and reuses each loaded element T times. Like buying groceries for the week in one trip instead of a trip per meal. Worked example: M = N = K = 4, T = 2. Naive: 16 outputs, each reads 4 + 4 = 8 elements, total 128. Tiled: (4/2) x (4/2) = 4 output tiles, each runs K/T = 2 steps, each step loads 2 tiles of 4 elements = 8, so 4 x 2 x 8 = 64. Ratio 128 / 64 = 2 = T. Rule: naive = M N (2K); tiled = (M/T)(N/T)(K/T)(2 T^2) = 2MNK / T; ratio = naive / tiled. Every fast matmul kernel, including those behind LLM training, uses tiling.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: smallmatmul_loads(64, 64, 64, 16)
  • Sample 2: rectangularmatmul_loads(128, 256, 512, 32)