Map program ids to tiles with grouped ordering for cache reuse

Why it matters Grouped launch ordering improves L2 hit rates for large matmuls and is a standard option in GPU kernel libraries.

If matmul tiles are launched row by row, consecutive blocks share one row of A but each needs a different column of B, so little stays in L2 cache. Grouped ordering walks a band of group_m tile rows column by column, so neighbouring blocks reuse both A rows and B columns.

Write grouped_order(num_m, num_n, group_m, window). Tiles are (pid_m, pid_n) with pid_m < num_m and pid_n < num_n. For program id p: per_group = group_m * num_n; g = p // per_group; first = g * group_m; size = min(num_m - first, group_m); local = p % per_group; pid_m = first + local % size; pid_n = local // size. Return (order, loads) where order lists (pid_m, pid_n) for p = 0 to num_m * num_n - 1, and loads is the number of distinct pid_m values plus distinct pid_n values among the first window programs (a proxy for tiles fetched into cache).

Signaturedef grouped_order(num_m, num_n, group_m, window)

Example

num_m 4, num_n 4, group_m 2, window 4 gives order starting [(0, 0), (1, 0), (0, 1), (1, 1), (0, 2), ...] and loads 4.

Understand the idea

Imagine filling a grid of classroom seats with students who must each fetch one book from a row shelf and one from a column shelf. If you fill the grid one full row at a time, each new seat needs a new column book. If you fill a small block of 2 rows at a time, going down then right, each column book is used twice before moving on. Worked example: 4 by 4 tiles, group_m 2. The first four programs are (0, 0), (1, 0), (0, 1), (1, 1): they touch rows {0, 1} and columns {0, 1}, 4 loads. Row-major order would give (0, 0) to (0, 3): 1 row and 4 columns, 5 loads. Rule: band g covers rows g group_m to g group_m + size - 1, with pid_m = first + local mod size and pid_n = local div size. Larger matrices see a much bigger difference in cache reuse.

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

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

  • Sample 1: example(lambda r: (r[0][:5], r[1]))(grouped_order(4, 4, 2, 4))
  • Sample 2: ragged bandgrouped_order(3, 2, 2, 6)[0]