4 Compute and Systems 3 / 5
  1. In this chapter
  2. LLM hardware basics
  3. GPUs and the Roofline Model
  4. GPU kernels
  5. Numerical Precision
  6. Collective Communication
All chapters →

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.

Intermediate 9 min read Updated Companion code ↓

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
  1. Who owns an output tile?
  2. Account for uneven edges
  3. Experiment: verify values and counts on edge tiles
  4. Connect the model to measurements
  5. What fusion saves and where it costs
  6. Summary and exercises
  7. Quick self-check
  8. Change one uneven dimension
  9. Further reading
  10. FAQ

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.

Cutaway GPU: data tiles move from memory through on-chip storage into parallel compute arrays.
Matrix multiplication tiles inputs, stages them on chip, and processes them across many compute units; reuse reduces repeated transfers.

Who owns an output tile?

Let AA have shape M×KM\times K, BB have shape K×NK\times N, and C=ABC=AB have shape M×NM\times N. Assign a thread block to each BM×BNB_M\times B_N output tile. It advances BKB_K elements at a time along the reduction dimension, multiplying one BM×BKB_M\times B_K input tile by one BK×BNB_K\times B_N input tile and accumulating the result into the same output tile.

  1. Address. Map a tile coordinate and the tensor strides to the address of each element. Adjacent threads accessing adjacent addresses can share memory transactions.
  2. 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.
  3. 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.
  4. Store. Write CC after traversing the reduction dimension. A bias or activation may fit before the store.

An interior tile needs at least BMBK+BKBNB_MB_K+B_KB_N elements of input staging and BMBNB_MB_N 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 AA that contribute to all output row tiles cover the entire matrix once. Analogously, each output row tile consumes all of BB across output column tiles. Thus:

QA=MK⌈NBN⌉,QB=KN⌈MBM⌉Q_A = MK\left\lceil\frac{N}{B_N}\right\rceil, \qquad Q_B = KN\left\lceil\frac{M}{B_M}\right\rceil

Count only valid elements at the edges and write MNMN output elements. For equal-size elements of ss bytes:

Qbytes=s(QA+QB+MN)Q_{\mathrm{bytes}} = s\left(Q_A+Q_B+MN\right)

Counting two operations per multiply-add gives an arithmetic intensity of 2MNK/Qbytes2MNK/Q_{\mathrm{bytes}}. The reduction tile size BKB_K 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.

ChangeExpected first effectInspect on the device
Remap neighboring threadsAddress sectors covered by one loadMemory transactions, cache hits, and bandwidth
Increase output tilesMore input reuse, larger accumulatorsTraffic, registers, and resident blocks
Increase reduction tilesFewer stages, larger input buffersStatic resources, synchronization, and active cycles
Add pipeline stagesMore loads can be issued earlyMemory stalls, shared memory, and elapsed time
Fuse bias and activation into the storeFewer reads and writes of intermediatesKernel 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 y=ReLU⁡(x+b)y=\operatorname{ReLU}(x+b), assume equal-length input arrays and a single element type. Separate addition and activation read xx and bb, write the intermediate, then read it and write yy. That moves 5N5N logical elements. A fused kernel can keep the sum in a register and move 3N3N. Broadcasting and caches can change the actual global memory cost.

A fused matrix multiplication epilogue needs the full reduction. If several thread blocks split KK, 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 NN to an output tile boundary and add one column. Calculate AA, BB, and CC traffic separately. Which terms jump?

Worked answer

The extra column opens a new output column tile, increasing QAQ_A by MKMK. Each row tile reads another KK values from BB, increasing QBQ_B by K⌈M/BM⌉K\lceil M/B_M\rceil. Output writes increase by MM. Benchmarking adjacent shapes can reveal this boundary.

Further reading

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.