---
title: Cache and memory lab
heading: Measuring write policies, access order and DRAM rows in Python
eyebrow: C8 · Lesson 51 · Cache and memory lab
xp: 50
---

::: hook
The formulas of the last few lessons predict averages. Real programs have particular access patterns, and the surprises live in the particulars: a matrix whose size is a power of two, a counter updated a thousand times, two arrays that happen to land in the same DRAM bank. In this lab you'll write small simulators that replay address traces and count what the hardware would do, then use them to find those surprises.
:::

::: play
- A loop walks through a large array with a fixed stride (the distance between consecutive accesses). Each cache line holds L bytes.
- With a stride of 4 bytes, one access in L/4 misses. Once the stride reaches the line size, every access misses: each one lands in a new line.
- Summing a matrix by columns is a stride of one whole row. For any matrix wider than a few lines, that's a miss on every access unless the cache can hold every row's line until the next column comes back for it.
:::

```sim plot
view: graph
x: s = 4..256 bytes
y: t = 0..120
slider: L = 16..128 step 16 = 64
slider: P = 10..100 step 5 = 50
plot: 1 + P*(s/L - (s/L - 1)*step(s - L)) | label: cycles per access, no reuse
readout: stride 4 (row order) = 1 + P*4/L | digits: 3
readout: stride 256 (columns of 64 ints) = 1 + P*(256/L - (256/L - 1)*step(256 - L)) | digits: 3
```

::: predict
## A 64 × 64 matrix of ints (16 KiB) is summed column by column through a 4 KiB direct-mapped cache with 64-byte lines. How many misses?

- [ ] 64
- [ ] 256
- [ ] 1024
- [x] 4096

::: reveal
4096: every access misses. Rows are 256 bytes apart, four lines, so the 64 elements of a column fall into only 16 of the cache's 64 sets, four rows per set, and they evict one another before the next column returns for the same lines. Summed by rows, the same matrix misses only 256 times, once per line. You'll reproduce both numbers in the third task.
:::
:::

::: nameit
## Simulating a cache

A trace-driven simulator keeps, for each set, the tags it holds (and a dirty bit for write-back), and for each address computes

$$\text{block} = \lfloor a / L \rfloor, \qquad \text{set} = \text{block} \bmod S, \qquad \text{offset} = a \bmod L$$

A hit is a matching tag in that set. Everything else (traffic, AMAT, miss counts) is counting.

## What to count

- **Traffic**: bytes moved between cache and memory. Write-back moves whole lines, on misses and on dirty evictions, plus the dirty lines still in the cache at the end. Write-through without allocation moves each store's 4 bytes, and lines only for load misses.
- **AMAT**: add up the time of every access (each level's time when it's consulted) and divide by the number of accesses.
- **DRAM row hits**: with an open-row policy, each bank keeps its last row open; an access to that row is a hit.

## Power-of-two strides

Set indices come from the low bits of the block number. Addresses that differ by a multiple of the cache size (or of a large power of two) share low bits and so share a set. A matrix whose rows are a power of two bytes long sends a whole column into a handful of sets. Padding each row by a line or so spreads them out.
:::

::: example
## A counter at one address is loaded and stored 1000 times. How many bytes cross the bus with a write-back, write-allocate cache, and with a write-through, no-allocate cache (64-byte lines)?

::: solution
1. **Write-back, write-allocate.** The first load misses and reads the line, 64 bytes; every later access hits; at the end the dirty line is written back, 64 more: 128 bytes.
2. **Write-through, no-allocate.** The first load reads the line, 64 bytes, and every one of the 1000 stores sends 4 bytes:
   $$64 + 1000 \times 4 = 4064\ \text{bytes}$$
3. **Compare.** That's 32 times as much.

**Answer:** 128 bytes with write-back and 4064 bytes with write-through, 32 times as much.
:::
:::

::: example
## The 64 × 64 matrix above misses 4096 times when summed by columns. What happens if each row is padded from 64 to 80 ints?

::: solution
1. **The new row spacing.** Rows are now 320 bytes apart, 5 lines.
2. **Where each row's line lands.** Because 5 and 64 have no common factor, row i's line for a given column lands in set $(5i + c) \bmod 64$, which is different for each of the 64 rows.
3. **No more evictions.** The column's lines no longer evict each other, and the next 15 columns find them all still cached.
4. **The misses.** The sum misses 256 times, only the unavoidable first touch of each line.
5. **The cost.** The padding wastes 4 KiB of memory to save 3840 misses.

**Answer:** the sum misses 256 times instead of 4096.
:::
:::

::: check
given: a = 4660 | 74565 | 1193046; L = 16 | 64; S = 64 | 256
answer: floor(a/L) - S*floor(a/(L*S))
tolerance: 0

## Address {a} in a cache with {L}-byte lines and {S} sets. Which set?

::: right
Right: set {answer}.
:::

::: misses
- [any] Not yet. Block number $\lfloor a/L \rfloor$, modulo {S}.
:::
:::

::: check
kind: python

## Write `split(addr, line, sets)`: return `(tag, index, offset)` for a cache with `line`-byte lines and `sets` sets (both powers of two).

```python starter
def split(addr, line, sets):
    return 0, 0, addr
```

```python solution
def split(addr, line, sets):
    offset_bits = line.bit_length() - 1
    index_bits = sets.bit_length() - 1
    return addr >> (offset_bits + index_bits), (addr >> offset_bits) & (sets - 1), addr & (line - 1)
```

```python tests
assert split(0x00012345, 16, 256) == (0x12, 0x34, 5), f"0x00012345 with 16-byte lines and 256 sets splits as (0x12, 0x34, 5), got {split(0x00012345, 16, 256)}."
assert split(0x12345678, 64, 128) == (37282, 89, 56), f"0x12345678 with 64-byte lines and 128 sets gives (37282, 89, 56), got {split(0x12345678, 64, 128)}."
assert split(0xFFFFFFFF, 32, 1024) == (131071, 1023, 31), "0xFFFFFFFF with 32-byte lines and 1024 sets gives (131071, 1023, 31)."
```

::: right
Right. Shifts and masks, exactly as the hardware wires it.
:::
:::

::: check
kind: python

## Write `traffic(trace, size, line, policy)`: the bytes moved between a direct-mapped cache and memory for a list of `(address, is_write)` pairs. Policy `'wb'` is write-back with write-allocate, counting dirty lines left at the end; `'wt'` is write-through with no write-allocate (each store moves 4 bytes; loads that miss fetch a line).

```python starter
def traffic(trace, size, line, policy):
    return line * len(trace)
```

```python solution
def traffic(trace, size, line, policy):
    lines = size // line
    tags = [None] * lines
    dirty = [False] * lines
    moved = 0
    for addr, write in trace:
        block = addr // line
        i = block % lines
        hit = tags[i] == block
        if policy == 'wt':
            if write:
                moved += 4
            elif not hit:
                moved += line
                tags[i] = block
        else:
            if not hit:
                if tags[i] is not None and dirty[i]:
                    moved += line
                moved += line
                tags[i] = block
                dirty[i] = False
            if write:
                dirty[i] = True
    if policy == 'wb':
        moved += line * sum(dirty)
    return moved
```

```python tests
stream = [(0x10000 + 4 * i, True) for i in range(1000)]
assert traffic(stream, 4096, 64, 'wb') == 8064, f"Storing 4000 bytes once through write-back: 63 lines in, 63 out = 8064, got {traffic(stream, 4096, 64, 'wb')}."
assert traffic(stream, 4096, 64, 'wt') == 4000, "Through write-through: just the 4000 bytes."
counter = [(0x2000, w) for _ in range(1000) for w in (False, True)]
assert traffic(counter, 4096, 64, 'wb') == 128, f"A counter loaded and stored 1000 times, write-back: 128 bytes, got {traffic(counter, 4096, 64, 'wb')}."
assert traffic(counter, 4096, 64, 'wt') == 4064, f"Write-through: one line plus 1000 stores = 4064, got {traffic(counter, 4096, 64, 'wt')}."
conflict = [(a, True) for _ in range(10) for a in (0x0, 0x1000)]
assert traffic(conflict, 4096, 64, 'wb') == 2560, f"Stores alternating between two addresses 4 KiB apart thrash one set: 2560 bytes, got {traffic(conflict, 4096, 64, 'wb')}."
```

::: right
Right. The same trace can favor either policy; the simulator settles it for a given program.
:::
:::

::: check
kind: python

## Write `matrix_misses(n, order, size, line)`: the misses of a direct-mapped cache (starting empty) when an n × n matrix of 4-byte ints, stored row by row from address 0, is read by rows (`'row'`) or by columns (`'col'`).

```python starter
def matrix_misses(n, order, size, line):
    return n * n * 4 // line
```

```python solution
def matrix_misses(n, order, size, line):
    lines = size // line
    tags = [None] * lines
    misses = 0
    for a in range(n):
        for b in range(n):
            i, j = (a, b) if order == 'row' else (b, a)
            block = (4 * (i * n + j)) // line
            s = block % lines
            if tags[s] != block:
                misses += 1
                tags[s] = block
    return misses
```

```python tests
assert matrix_misses(64, 'row', 4096, 64) == 256, f"64 x 64 by rows: one miss per line, 256, got {matrix_misses(64, 'row', 4096, 64)}."
assert matrix_misses(64, 'col', 4096, 64) == 4096, f"64 x 64 by columns: every access misses, 4096, got {matrix_misses(64, 'col', 4096, 64)}."
assert matrix_misses(48, 'col', 4096, 64) == 144, f"48 x 48 by columns: rows 3 lines apart spread over every set, so only 144 misses, got {matrix_misses(48, 'col', 4096, 64)}."
assert matrix_misses(32, 'col', 4096, 64) == 64, "32 x 32 is 4 KiB and fits: 64 misses either way."
```

::: right
Right. Same matrix, same cache, sixteen times the misses, from the order of two loops.
:::
:::

::: check
kind: python

## Write `amat(trace, l1, l2, line, t1, t2, tmem)`: the average access time of a list of addresses through a direct-mapped L1 of `l1` bytes and a direct-mapped L2 of `l2` bytes (both starting empty, `line`-byte lines). Every access costs t1; an L1 miss adds t2; an L2 miss adds tmem as well. A miss fills both levels.

```python starter
def amat(trace, l1, l2, line, t1, t2, tmem):
    return t1
```

```python solution
def amat(trace, l1, l2, line, t1, t2, tmem):
    c1, c2 = [None] * (l1 // line), [None] * (l2 // line)
    total = 0
    for addr in trace:
        b = addr // line
        total += t1
        if c1[b % len(c1)] == b:
            continue
        total += t2
        if c2[b % len(c2)] != b:
            total += tmem
            c2[b % len(c2)] = b
        c1[b % len(c1)] = b
    return total / len(trace)
```

```python tests
seq = [4 * i for i in range(4096)]
assert abs(amat(seq, 1024, 16384, 64, 1, 10, 100) - 7.875) < 1e-9, f"One sweep of 16 KiB: (111 + 15)/16 = 7.875, got {amat(seq, 1024, 16384, 64, 1, 10, 100)}."
loop = [4 * i for i in range(1024)] * 8
assert abs(amat(loop, 1024, 16384, 64, 1, 10, 100) - 2.40625) < 1e-9, f"A 4 KiB loop, 8 passes: L2 catches the later passes, 2.40625, got {amat(loop, 1024, 16384, 64, 1, 10, 100)}."
small = [4 * i for i in range(256)] * 8
assert abs(amat(small, 1024, 16384, 64, 1, 10, 100) - 1.859375) < 1e-9, "A 1 KiB loop fits in L1: 1.859375."
```

::: right
Right. A measured AMAT includes the compulsory misses that the averages in formulas leave out.
:::
:::

::: check
kind: python

## Write `row_hit_rate(addresses, row_bytes, banks)`: the fraction of DRAM accesses that find their row open. Consecutive rows of `row_bytes` go to consecutive banks (row r of the address space is in bank r mod banks, as that bank's row r // banks), and each bank keeps its last row open.

```python starter
def row_hit_rate(addresses, row_bytes, banks):
    return 1.0
```

```python solution
def row_hit_rate(addresses, row_bytes, banks):
    open_row = [None] * banks
    hits = 0
    for a in addresses:
        r = a // row_bytes
        bank, row = r % banks, r // banks
        if open_row[bank] == row:
            hits += 1
        open_row[bank] = row
    return hits / len(addresses)
```

```python tests
seq = [64 * i for i in range(1024)]
assert abs(row_hit_rate(seq, 8192, 4) - 0.9921875) < 1e-9, f"64 KiB read in order: 8 row openings in 1024 accesses, 0.9921875, got {row_hit_rate(seq, 8192, 4)}."
same = [x for i in range(256) for x in (64 * i, 32768 + 64 * i)]
assert row_hit_rate(same, 8192, 4) == 0.0, f"Two streams 32 KiB apart share a bank and keep closing each other's rows: 0, got {row_hit_rate(same, 8192, 4)}."
diff = [x for i in range(100) for x in (64 * i, 8192 + 64 * i)]
assert abs(row_hit_rate(diff, 8192, 4) - 0.99) < 1e-9, f"Two streams in different banks: 0.99, got {row_hit_rate(diff, 8192, 4)}."
```

::: right
Right. Memory controllers map addresses to banks with care, often hashing bits together, to keep streams like these apart.
:::
:::

::: explain
## Why do trace-driven simulators find problems that average-based formulas miss?

::: model
Formulas like AMAT = hit time + miss rate × penalty take the miss rate as given, and that rate depends on exactly which addresses a program touches and in what order. Two programs with the same amount of data can have wildly different miss rates: summing a matrix by rows or by columns, or a matrix whose row length is a power of two against one that isn't, where the difference is conflicts in a handful of sets. A simulator replays the actual addresses through a model of the hardware's sets, tags and dirty bits, so it captures those effects exactly, including compulsory misses, conflicts between particular arrays and bank collisions in DRAM. That's why architects evaluate designs, and programmers diagnose slow loops, with traces rather than averages.
:::
:::
