Sub topic 13
Blocking (tiling) for matrix-style loops
This chapter assumes you have read the earlier chapters on cache lines, locality, and traversal order. You should be comfortable with C arrays, nested loops, and the idea that a cache line (commonly 64 bytes) is the unit of transfer between memory and cache.
The problem: one good stride, one bad stride
Some loop nests cannot be fixed by reordering the loops. A matrix transpose is the standard example. It reads src[i][j] and writes dst[j][i]. If the loops run over i then j, the reads are sequential but the writes jump by one full row each time. If you swap the loops, the writes become sequential and the reads jump. Either way, one of the two arrays is accessed with a large stride.
For a 4096 by 4096 matrix of double, one row is 32 KiB. The strided array touches a new cache line on almost every access. By the time the loop returns to the neighbouring element in that line, the line has usually been evicted. Each cache line is loaded from memory once for each element it holds, instead of once in total.
Blocking, also called tiling, fixes this by changing the order of work. You split the iteration space into small square tiles. You finish all the work on one tile before moving to the next. The tile is small enough that its cache lines stay resident until every element in them has been used.
The idea
Take an n by n matrix and a tile size B. Instead of two loops over the whole matrix, use four loops:
- The outer two loops step over tiles,
iiandjj, in increments ofB. - The inner two loops walk the elements inside one tile.
The set of elements visited is the same. Only the order changes, so the result is identical. Within a tile, the strided access still happens, but it now touches only B distinct cache lines per array, and those lines are reused B times each before the tile is finished.
#include <stddef.h>
#define B 32
/* Transposes an n-by-n row-major matrix one B-by-B tile at a time. */
void transpose_blocked(double *dst, const double *src, size_t n) {
for (size_t ii = 0; ii < n; ii += B)
for (size_t jj = 0; jj < n; jj += B)
for (size_t i = ii; i < ii + B && i < n; i++)
for (size_t j = jj; j < jj + B && j < n; j++)
dst[j * n + i] = src[i * n + j];
}The bounds checks i < n and j < n handle the case where n is not a multiple of B. Without them the last tiles would read and write past the end of the arrays.
Choosing the tile size
The tile size is a trade-off. Too small, and you pay loop overhead and do not fill whole cache lines. Too large, and the tile no longer fits in cache, so you lose the reuse you wanted.
A rough way to pick B:
- For the transpose, a tile touches
Brows ofsrcandBrows ofdst, eachB * sizeof(double)bytes long. The working set is about2 * B * B * 8bytes. - With
B = 32that is 16 KiB. This fits in a typical 32 KiB or 48 KiB L1 data cache with room to spare. - Each row segment of a tile should be at least one cache line. With 8-byte doubles and 64-byte lines,
Bshould be at least 8.
Treat these numbers as a starting point. Cache sizes, associativity, and other data competing for the cache all vary between machines. The reliable method is to benchmark several values such as 8, 16, 32, 64, and 128 on your target hardware.
| Tile size B | Working set (two tiles of double) | Likely result |
|---|---|---|
| 4 | 256 bytes | Too small. Each row segment is half a cache line, so lines are only half used per tile. |
| 32 | 16 KiB | Fits in L1 on most current CPUs. |
| 128 | 256 KiB | Spills out of L1, may fit in L2. |
| 512 | 4 MiB | Likely misses in L2 as well. |
Blocking matrix multiplication
Transpose has no reuse of individual elements. Each element is read once and written once. Blocking helps only because it lets whole cache lines be used before eviction. Matrix multiplication is different: every element of the inputs is used n times, so there is much more reuse to protect.
The naive version computes C[i][j] += A[i][k] * B[k][j]. In the i, j, k order, the inner loop reads A sequentially but walks down a column of B with a stride of one row. For large n, the whole of B does not fit in cache, so each pass over a column reloads it from memory.
A blocked version works on tiles of all three matrices:
#include <stddef.h>
#define T 32
/* C += A * Bm for n-by-n row-major matrices. C must be initialized by the caller. */
void matmul_blocked(double *C, const double *A, const double *Bm, size_t n) {
for (size_t ii = 0; ii < n; ii += T)
for (size_t kk = 0; kk < n; kk += T)
for (size_t jj = 0; jj < n; jj += T)
for (size_t i = ii; i < ii + T && i < n; i++)
for (size_t k = kk; k < kk + T && k < n; k++) {
double a = A[i * n + k];
for (size_t j = jj; j < jj + T && j < n; j++)
C[i * n + j] += a * Bm[k * n + j];
}
}Two things changed besides the tiling. The inner loops are ordered i, k, j, so the innermost loop reads Bm and writes C sequentially along a row. The value a is loaded once and reused across the whole j loop. The tiling then keeps a T by T tile of Bm in cache while it is reused by T different rows of A.
Three tiles of T = 32 doubles take 3 × 8 KiB = 24 KiB. That is why 32 is a common choice for L1-sized tiles, and why larger T often needs to target L2 instead.
Edge cases and pitfalls
Sizes that are not a multiple of the tile
The && i < n checks in the examples are required. Alternatives are to handle the remainder in separate loops, or to pad the matrix to a multiple of B. Padding costs memory but removes branches from the inner loops.
Power-of-two sizes and conflict misses
When n * sizeof(double) is a large power of two, rows of a tile can map to the same few cache sets. A tile that fits by size can still evict its own lines because of low associativity. This is the conflict miss problem from the earlier chapter on associativity. Two common fixes are padding each row by one cache line, so the row stride is no longer a power of two, or choosing a tile size that avoids the pattern. If a blocked loop is slower than expected at exactly 2048 or 4096, suspect this.
Tiles that fit one level but not the next
A tile sized for L1 helps L1 hit rates. If the data does not also fit in L2 or L3 in a sensible pattern, the traffic between those levels can still be high. Multi-level blocking addresses this, at the cost of more loops and more parameters to tune.
Blocking is not free
Blocking adds four to six loops instead of two to three. It makes the code harder to read and to vectorize by hand. For small matrices that already fit in cache, the blocked version can be slower. Block only when profiling shows cache misses dominate.
Hardware dependence
The best tile size changes from one CPU to another. If the code is distributed to unknown machines, either pick a conservative size or tune at start-up. The cache-oblivious layouts discussed later in the tutorial avoid this by recursing on sub-blocks instead of fixing a size.
Verifying that blocking helped
Do not assume the tiled version is faster. Time both versions on the same input, on a matrix large enough to exceed the last-level cache, and repeat the measurement. Where hardware counters are available, compare L1 data cache load misses or last-level cache misses between the two versions. A real improvement shows up as fewer misses, not only as less time. The chapter on measuring cache behavior covers how to do this without being misled by warm-up effects or compiler optimizations.
Exercise
A blocked transpose uses B = 64 with 8-byte doubles on a CPU with a 32 KiB L1 data cache. Estimate the working set of one tile pair and say whether you expect it to fit in L1. What would you try next?
Show answer
A tile of src is 64 × 64 × 8 = 32 KiB and a tile of dst is the same, so the pair needs about 64 KiB. That is twice the L1 size, so the tiles will evict each other and you lose most of the benefit. Try B = 32, which gives about 16 KiB for the pair, and benchmark it against B = 16 and B = 64.
Exercise
Why does blocking help matrix multiplication more than it helps a simple transpose, even though both use the same tiling technique?
Show answer
In matrix multiplication each input element is used n times, so keeping a tile in cache turns many potential memory loads into cache hits. In a transpose each element is touched once, so blocking only ensures that each loaded cache line is fully used before it is evicted.