---
title: Cache lab
heading: Classifying misses into the three Cs, blocking a matrix multiply, and fitting the √2 rule, in Python
eyebrow: S4 · Lesson 23 · Cache lab
xp: 60
---

::: hook
The three Cs, blocking and the √2 rule from lessons 18 to 20 are all statements about miss counts, and miss counts are what a cache simulator produces. This lab writes a set-associative LRU simulator and uses it three ways: to split a trace's misses into compulsory, capacity and conflict by simulating an infinite cache, a fully associative one and the real one; to measure how much blocking cuts a matrix multiply's misses; and to fit the exponent of the √2 rule to measured miss rates.
:::

::: play
- The lines are miss rate against cache size on log–log axes for the rule $m = m_0(S/S_0)^{-\alpha}$; the slider sets α.
- α = 0.5 is the √2 rule: each doubling of the cache divides the miss rate by √2. Programs with little reuse beyond a working set show smaller α until the working set fits, then a cliff.
- The lab fits α to measured points by least squares on the logarithms.
:::

```sim plot
view: graph
x: S = 4..1024 log
y: m = 0.001..0.2 log
slider: a = 0.2..1 = 0.5
plot: 0.08*(S/8)^(-a) | label: miss rate
plot: 0.08*(S/8)^(-0.5) | dashed | label: √2 rule
```

::: predict
## A 256 × 256 matrix of 4-byte integers, stored by rows, is read down its columns through a 32 KB, 4-way cache with 64-byte lines. Its 65 536 accesses all miss. How do those misses split into the three Cs?

- [x] 4096 compulsory, no capacity misses, 61 440 conflict misses
- [ ] 65 536 compulsory
- [ ] 4096 compulsory and 61 440 capacity misses
- [ ] All conflict misses

::: reveal
The matrix occupies $256 \times 1024/64 = 4096$ lines: those first touches are compulsory. A fully associative 32 KB cache holds 512 lines, enough for the 256 lines one column walk touches, so the next column finds them all: no capacity misses. The real cache maps all 256 of them into 8 sets, and evicts each before its reuse: the other 61 440 are conflicts.
:::
:::

::: nameit
## The simulator

For a cache of S bytes, B-byte lines and W ways: block = address ÷ B, set = block mod (S/(BW)), tag = block ÷ (S/(BW)); each set is an LRU list of up to W tags.

## The three Cs, measured

- **Compulsory** = distinct lines touched (an infinite cache's misses).
- **Capacity** = fully associative LRU cache of the same size's misses − compulsory.
- **Conflict** = the real cache's misses − the fully associative cache's.

## Blocking

A matrix multiply's inner loop touches a row of A and a column of B; once N grows past what the cache holds, B's column lines are evicted before reuse. Working on tiles small enough that three fit in the cache reuses each line many times.

## Fitting α

On log axes the rule is a line: $\ln m = \ln m_0 - \alpha\ln(S/S_0)$, so α is minus the least-squares slope of $\ln m$ against $\ln S$.
:::

::: check
kind: python

## Write `misses(addrs, size, line, ways)`: an LRU set-associative cache simulator returning the miss count, and `three_c(addrs, size, line, ways)`: return (compulsory, capacity, conflict).

```python starter
def misses(addrs, size, line, ways):
    return len(addrs)

def three_c(addrs, size, line, ways):
    return (0, 0, 0)
```

```python solution
from collections import OrderedDict

def misses(addrs, size, line, ways):
    sets = size // (line * ways)
    tags = [OrderedDict() for _ in range(sets)]
    m = 0
    for a in addrs:
        b = a // line
        d = tags[b % sets]
        t = b // sets
        if t in d:
            d.move_to_end(t)
        else:
            m += 1
            if len(d) == ways:
                d.popitem(last=False)
            d[t] = 1
    return m

def three_c(addrs, size, line, ways):
    comp = len({a // line for a in addrs})
    fa = misses(addrs, size, line, size // line)
    real = misses(addrs, size, line, ways)
    return (comp, fa - comp, real - fa)
```

```python tests
cols = [(r * 256 + c) * 4 for c in range(256) for r in range(256)]
assert three_c(cols, 32768, 64, 4) == (4096, 0, 61440), "The predict: compulsory and conflict only."
rows = [(r * 256 + c) * 4 for r in range(256) for c in range(256)]
assert three_c(rows, 32768, 64, 4) == (4096, 0, 0), "Row order: only the first touches miss."
big = [i * 64 for i in range(1024)] * 2
assert three_c(big, 32768, 64, 4) == (1024, 1024, 0), "A 64 KB loop through a 32 KB cache: the second pass is all capacity misses."
```

::: right
Right. Simulating the two reference caches is how architects tell whether more ways or more capacity would help.
:::
:::

::: check
kind: python

## Write `mm_trace(N, block)`: the address trace of $C = C + AB$ for N × N matrices of 8-byte doubles at base addresses 0, $2^{20}$ and $2^{21}$, reading A[i][k] and B[k][j] in the inner loop and writing C[i][j] after it; with block = None use plain i, j, k loops, otherwise tile the j and k loops in blocks of that size (jj, kk outermost, then i, j, k).

```python starter
def mm_trace(N, block):
    return []
```

```python solution
def mm_trace(N, block):
    A, B, C = 0, 1 << 20, 2 << 20
    out = []
    if block is None:
        for i in range(N):
            for j in range(N):
                for k in range(N):
                    out += [A + (i * N + k) * 8, B + (k * N + j) * 8]
                out.append(C + (i * N + j) * 8)
    else:
        for jj in range(0, N, block):
            for kk in range(0, N, block):
                for i in range(N):
                    for j in range(jj, jj + block):
                        for k in range(kk, kk + block):
                            out += [A + (i * N + k) * 8, B + (k * N + j) * 8]
                        out.append(C + (i * N + j) * 8)
    return out
```

```python tests
from collections import OrderedDict
def misses(addrs, size, line, ways):
    sets = size // (line * ways)
    tags = [OrderedDict() for _ in range(sets)]
    m = 0
    for a in addrs:
        b = a // line
        d = tags[b % sets]
        t = b // sets
        if t in d:
            d.move_to_end(t)
        else:
            m += 1
            if len(d) == ways:
                d.popitem(last=False)
            d[t] = 1
    return m
assert len(mm_trace(32, None)) == 2 * 32 ** 3 + 32 ** 2 and len(mm_trace(32, 8)) == 2 * 32 ** 3 + 32 ** 2 * 4, "Same reads of A and B; the blocked loop writes C once per k block."
n, b = misses(mm_trace(32, None), 2048, 64, 4), misses(mm_trace(32, 8), 2048, 64, 4)
assert b < 0.7 * n, "With three 8 × 8 tiles fitting in 2 KB, blocking cuts the misses by over 30%."
```

::: right
Right. The blocked loop does the same arithmetic in an order that keeps its tiles resident.
:::
:::

::: check
kind: python

## Write `fit_alpha(sizes, rates)`: the least-squares exponent α in $m \propto S^{-\alpha}$.

```python starter
def fit_alpha(sizes, rates):
    return 0.5
```

```python solution
import math

def fit_alpha(sizes, rates):
    xs = [math.log(s) for s in sizes]
    ys = [math.log(m) for m in rates]
    n = len(xs)
    mx, my = sum(xs) / n, sum(ys) / n
    return -sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sum((x - mx) ** 2 for x in xs)
```

```python tests
assert abs(fit_alpha([8, 16, 32, 64], [0.08, 0.057, 0.04, 0.028]) - 0.5055) < 1e-3, "These measurements follow the √2 rule: α ≈ 0.51."
assert abs(fit_alpha([1, 2, 4], [0.1, 0.05, 0.025]) - 1.0) < 1e-12, "Halving per doubling: α = 1."
```

::: right
Right. A straight line on log axes is the signature of a power law; its slope is the exponent.
:::
:::

::: explain
## How does simulating a fully associative cache of the same size separate capacity misses from conflict misses?

::: model
A fully associative cache can place any line anywhere, so the only reason it misses, after the first touch of each line, is that the program's working set doesn't fit and LRU had to evict something useful: those are capacity misses. The real set-associative cache has the same total size but restricts each line to one set, so it can also miss when too many active lines crowd into the same set while other sets sit idle. Its extra misses beyond the fully associative cache's are therefore due to the mapping alone, conflict misses, and they're the ones that more associativity or a different address mapping would remove.
:::
:::
