680. 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.
def matmul_loads(M, N, K, T)Example 1
Input: M = 64, N = 64, K = 64, T = 16
Output: (524288, 32768, 16.0)
Example 2
Input: M = 128, N = 256, K = 512, T = 32
Output: (33554432, 1048576, 32.0)
Constraints
- Python 3 standard library. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Naive: M * N * 2K.
Hint 2
Tiled: (M / T)(N / T) tiles, each doing K / T steps of 2 T^2 loads.
Common mistakes
- Do not forget the loop over K / T: the buggy version counts only one step per tile.
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.
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.
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.
Topics
Companies1
- NVIDIA the topic appears in interview reports Nvidia Interview Guide 2026: GPU Architecture, CUDA Kernels, Distributed Training, and the AI Boom
From public interview reports and guides. Not affiliated with or endorsed by these companies.