Chapter 4 · Compute and Systems 4.3
GPU kernels: from tiled matrix multiplication to fusion
GPU kernel tuning combines thread-level memory access, on-chip reuse, and output stores. Derive the logical traffic of tiled matrix multiplication with edge masks, check it with a CPU experiment, and trace practical limits from staging buffers to register spills.
After this page you will be able to
- Decompose a matrix multiply into output and reduction tiles and describe how a thread block loads, accumulates, and stores data.
- Derive and check logical traffic for masked edge tiles on dimensions that do not divide evenly.
- Identify which resources and timing characteristics change with output and reduction tile sizes.
- Use correctness, memory traffic, and a device timeline to distinguish the effects of layout, tiling, and fusion.
On this page
A GPU kernel maps work to threads and decides when to put data in registers or shared memory, reuse it, and write it back. Two matrix multiplications with the same inputs, outputs, and FLOP count can move different amounts of data due to thread access order, tile size, and where intermediates live. A runnable tiled implementation makes those differences concrete.

Who owns an output tile?
Let have shape , have shape , and have shape . Assign a thread block to each output tile. It advances elements at a time along the reduction dimension, multiplying one input tile by one input tile and accumulating the result into the same output tile.
- Address. Map a tile coordinate and the tensor strides to the address of each element. Adjacent threads accessing adjacent addresses can share memory transactions.
- Load. Threads cooperate to stage the inputs on chip. Missing edge elements act like zeros. An input value can contribute to multiple multiply-adds in the output tile.
- Compute. Keep partial sums in accumulators. Establish the dependencies before using staged inputs. Prefetching the next tile also requires protecting the current one from being overwritten.
- Store. Write after traversing the reduction dimension. A bias or activation may fit before the store.
An interior tile needs at least elements of input staging and elements of accumulation. Inputs and accumulators can have different element sizes. Double buffering doubles the input staging budget. A compiler can also need registers for addresses, masks, and other intermediates, so inspect its resource report.
Account for uneven edges
Count valid input reads and final stores within each output tile. Ignore cross-tile cache reuse, memory transaction alignment, and spills. For each output column tile, the rows of that contribute to all output row tiles cover the entire matrix once. Analogously, each output row tile consumes all of across output column tiles. Thus:
Count only valid elements at the edges and write output elements. For equal-size elements of bytes:
Counting two operations per multiply-add gives an arithmetic intensity of . The reduction tile size disappears from the traffic formula. It still affects synchronization frequency, staging and registers, and how well the dimensions fit the device’s instruction shapes.
If an implementation physically pads the arrays, budget the padded traffic. With masking, invalid positions generate no logical reads, but nearby valid addresses can share hardware memory transactions. Check whether a profiler counter refers to logical requests, a cache level, or memory controller traffic before comparing it with the formula.
Experiment: verify values and counts on edge tiles
This example ran on an Apple M2 Max with Python 3.12.14 and NumPy 2.5.4. The inputs use small integer values stored as float32. Intermediate sums stay within the range in which float32 represents those integers exactly, so exact equality is appropriate for this fixture. A test using arbitrary fractional inputs should allow for rounding differences caused by a different reduction order.
import numpy as np
def tiled_matmul(
left: np.ndarray, right: np.ndarray, tiles: tuple[int, int, int]
) -> tuple[np.ndarray, int]:
"""Accumulate output tiles and count logical reads and writes."""
rows, depth = left.shape
right_depth, cols = right.shape
if depth != right_depth or min(tiles) <= 0:
raise ValueError("incompatible matrix shapes or nonpositive tiles")
tile_m, tile_n, tile_k = tiles
result = np.empty((rows, cols), dtype=np.result_type(left, right))
moved = 0
for row in range(0, rows, tile_m):
row_end = min(row + tile_m, rows)
for col in range(0, cols, tile_n):
col_end = min(col + tile_n, cols)
block = np.zeros((row_end - row, col_end - col), dtype=result.dtype)
for start in range(0, depth, tile_k):
end = min(start + tile_k, depth)
a = left[row:row_end, start:end]
b = right[start:end, col:col_end]
block += a @ b
moved += a.size + b.size
result[row:row_end, col:col_end] = block
moved += block.size
return result, moved
def traffic_elements(
rows: int, cols: int, depth: int, tile_m: int, tile_n: int
) -> int:
"""Count live input loads and output stores with masked edge tiles."""
if min(rows, cols, depth, tile_m, tile_n) <= 0:
raise ValueError("all sizes must be positive")
row_tiles = (rows + tile_m - 1) // tile_m
col_tiles = (cols + tile_n - 1) // tile_n
return col_tiles * rows * depth + row_tiles * depth * cols + rows * cols
rng = np.random.default_rng(0)
m, n, k = 65, 49, 33
left = rng.integers(-4, 5, size=(m, k)).astype(np.float32)
right = rng.integers(-4, 5, size=(k, n)).astype(np.float32)
expected = left @ right
for tiles in ((4, 4, 4), (8, 8, 4), (8, 8, 16)):
answer, elements = tiled_matmul(left, right, tiles)
assert np.array_equal(answer, expected)
assert elements == traffic_elements(m, n, k, *tiles[:2])
print(f"tile {tiles}: {elements * left.itemsize:,} B")
tile (4, 4, 4): 234,236 B
tile (8, 8, 4): 131,012 B
tile (8, 8, 16): 131,012 B
The widget below makes this counting table draggable: pick a preset tiling or drag tile_m / tile_n to watch the traffic bytes of the 65×49×33 matmul change live — (4,4)‘s 234,236 bytes and (8,8)‘s 131,012 recompute digit for digit, with green marking the theoretical floor of one input pass and one output pass; tile_k does not change the traffic.
Connect the model to measurements
First check correctness on small examples against a reference. Then benchmark regular shapes, common uneven shapes, and small batches from the target workload. A large square matrix alone does not represent every layer in a serving system.
| Change | Expected first effect | Inspect on the device |
|---|---|---|
| Remap neighboring threads | Address sectors covered by one load | Memory transactions, cache hits, and bandwidth |
| Increase output tiles | More input reuse, larger accumulators | Traffic, registers, and resident blocks |
| Increase reduction tiles | Fewer stages, larger input buffers | Static resources, synchronization, and active cycles |
| Add pipeline stages | More loads can be issued early | Memory stalls, shared memory, and elapsed time |
| Fuse bias and activation into the store | Fewer reads and writes of intermediates | Kernel count, global traffic, and spills |
GPU launches are usually asynchronous. Use device events for kernel time or synchronize around a wall-clock measurement. Warm up first and account separately for compilation and allocation. Change one factor at a time. If traffic decreases while time stays flat, investigate compute throughput and resource occupancy.
What fusion saves and where it costs
For elementwise , assume equal-length input arrays and a single element type. Separate addition and activation read and , write the intermediate, then read it and write . That moves logical elements. A fused kernel can keep the sum in a register and move . Broadcasting and caches can change the actual global memory cost.
A fused matrix multiplication epilogue needs the full reduction. If several thread blocks split , each holds a partial sum. Combine the sums before bias and activation. Applying ReLU on the partial sums changes the computation because ReLU does not commute with summation. Include signed values, tail blocks, padding, and split reductions in correctness tests.
Efficient attention keeps mergeable softmax state on chip so it can process pieces of the attention matrix without materializing the full intermediate. For any fused kernel, draw the data reuse within each block and the state that has to cross block boundaries.
Summary and exercises
- The output tile controls reuse and accumulation footprint. The reduction tile controls staging and iteration granularity.
- Logical counts estimate an upper-level data schedule. Compare them with alignment, caches, registers, and device timing.
- Fusion can eliminate intermediate memory traffic. Reductions and nonlinearities still have to preserve the intended semantics.
Quick self-check
1. In this model, what changes when the reduction tile grows at a fixed output tile size?
- The number of reduction iterations
- The number of valid matrix elements read
The same valid input set gets grouped into differently sized loads.
2. Why mask the final output tile?
- Avoid out-of-bounds loads
- Avoid writing invalid output positions
- Guarantee hardware traffic matches the logical byte count
Physical transfers still follow the device’s memory transaction rules.
3. Which resources can limit a larger output tile?
- Registers for accumulators
- Shared memory for input tiles
- A change in the intended matrix product
More resources per block can reduce the number of resident blocks per SM.
4. What can happen if ReLU is applied to each split reduction before the sums merge?
- The result always matches activation after the full sum
- The result can change
Positive and negative contributions can cancel, and early truncation loses that cancellation.
Change one uneven dimension
Set to an output tile boundary and add one column. Calculate , , and traffic separately. Which terms jump?
Worked answer
The extra column opens a new output column tile, increasing by . Each row tile reads another values from , increasing by . Output writes increase by . Benchmarking adjacent shapes can reveal this boundary.
Further reading
- CMU 15-442/15-642 schedule, weeks 4 and 7 on CUDA, layouts, and matrix multiplication.
- Stanford CS336 Systems assignment, which includes profiling and tiled attention.
- GPU roofline and numerical precision.
FAQ
- What is a tile in a GPU kernel?
- A tile is a piece of data that a thread block processes together. In matrix multiplication, the output tile defines the output positions, while the reduction tile defines the subset of inputs needed in one iteration.
- Why might a larger reduction tile leave traffic unchanged?
- At a fixed output tile size, changing the reduction chunk only changes how the same valid input elements are grouped. Instruction shape, alignment, cache behavior, and pipelining can still change hardware performance.
- Does fusion always make a kernel faster?
- Fusion can eliminate a global write and read of an intermediate array. It can also extend data lifetimes and increase register pressure. Compare elapsed time, traffic, and spills on the device.