---
title: Core and cache lab
heading: A set-associative cache simulator, a pipeline hazard counter and two-level AMAT, in Python
eyebrow: S3 · Lesson 45 · Core and cache lab
xp: 60
---

::: hook
Lessons 41 to 43 built a processor's pipeline and caches in RTL. Before committing to sizes and policies, architects run traces through quick models: a cache simulator that counts hits for a real access pattern, a pipeline model that counts stalls and flushes, and the average memory access time of a two-level hierarchy. This lab writes all three and uses them to see a classic effect: walking a matrix down its columns can miss on every access in a cache that holds the whole column.
:::

::: play
- The line is the average memory access time of a two-level hierarchy against the L1 miss rate: $h_1 + m_1(h_2 + m_2t_\text{mem})$ with a 1-cycle L1, a 10-cycle L2 and a 100-cycle memory.
- The slider sets the L2's local miss rate. A good L2 flattens the curve: L1 misses then cost about 10 cycles, not 100.
- The lab computes the same quantity and simulates the hit rates that feed it.
:::

```sim plot
view: graph
x: m = 0..0.2
y: A = 0..25 cycles
slider: q = 0.05..1 = 0.2
plot: 1 + m*(10 + q*100) | label: AMAT
plot: 1 + m*100 + 0*q | dashed | label: no L2
```

::: predict
## A program reads a 256 × 256 matrix of 4-byte integers, stored row by row, once in row order and once column by column. The cache is 32 KB, 4-way, with 64-byte lines. What hit rates do the two walks get?

- [ ] About 94% both ways: the matrix's columns fit in the cache
- [x] About 94% in row order and 0% by columns
- [ ] 0% both ways: the matrix is 256 KB, eight times the cache
- [ ] About 50% both ways

::: reveal
Row order uses all 16 integers of each line before moving on: 15 hits per 16 accesses, 93.75%. Down a column, consecutive accesses are 1 KB apart, and with 128 sets each 1 KB step moves 16 sets on, so the 256 rows of a column fall into only 8 sets: 32 lines competing for 4 ways each. Every access misses, though the column's 256 lines (16 KB) would fit. The lab's simulator reproduces both numbers.
:::
:::

::: nameit
## The models

- **Cache:** an address's block number is address ÷ line size; the set is block mod (number of sets) and the tag is block ÷ (number of sets). Each set keeps up to W tags in least-recently-used order: a hit moves the tag to the most recent end; a miss evicts the least recent if the set is full.
- **Pipeline (five stages, forwarding, branches resolved in EX, predicted not taken):** $\text{cycles} = 4 + N + \text{load-use stalls} + 2 \times \text{taken branches}$, where a load-use stall happens when an instruction reads the register the load just before it wrote (x0 excepted).
- **Two-level AMAT:** $h_1 + m_1(h_2 + m_2t_\text{mem})$, with $m_2$ the L2's local miss rate (misses per L2 access).
:::

::: check
kind: python

## Write `cache_sim(addrs, size, line, ways)`: simulate an LRU set-associative cache of `size` bytes with `line`-byte lines and `ways` ways over a list of byte addresses, and return the hit rate.

```python starter
def cache_sim(addrs, size, line, ways):
    return 0.0
```

```python solution
def cache_sim(addrs, size, line, ways):
    sets = size // (line * ways)
    tags = [[] for _ in range(sets)]
    hits = 0
    for a in addrs:
        blk = a // line
        s, t = blk % sets, blk // sets
        st = tags[s]
        if t in st:
            hits += 1
            st.remove(t)
            st.append(t)
        else:
            if len(st) == ways:
                st.pop(0)
            st.append(t)
    return hits / len(addrs)
```

```python tests
rows = [(r * 256 + c) * 4 for r in range(256) for c in range(256)]
cols = [(r * 256 + c) * 4 for c in range(256) for r in range(256)]
assert abs(cache_sim(rows, 32768, 64, 4) - 0.9375) < 1e-9, "Row order: 15 of every 16 hit."
assert cache_sim(cols, 32768, 64, 4) == 0.0, "Column order: every access conflicts."
pp = [0, 32768] * 1000
assert cache_sim(pp, 32768, 64, 1) == 0.0 and cache_sim(pp, 32768, 64, 2) == 0.999, "Two addresses in one set: direct-mapped thrashes, 2-way holds both."
```

::: right
Right. Conflict misses depend on how addresses map to sets, not on whether the data would fit: padding each row by one line fixes the column walk.
:::
:::

::: check
kind: python

## Write `pipe_cycles(prog)`: prog is a list of (op, rd, srcs, taken) tuples; count cycles on the five-stage pipeline with forwarding, one stall when an instruction uses the register a load ('lw') wrote in the instruction just before it (rd ≠ 0), and two flush cycles for each taken 'beq'.

```python starter
def pipe_cycles(prog):
    return len(prog)
```

```python solution
def pipe_cycles(prog):
    stalls = flushes = 0
    for i, (op, rd, srcs, taken) in enumerate(prog):
        if i > 0:
            pop, prd, _, _ = prog[i - 1]
            if pop == 'lw' and prd != 0 and prd in srcs:
                stalls += 1
        if op == 'beq' and taken:
            flushes += 2
    return 4 + len(prog) + stalls + flushes
```

```python tests
prog = [('lw', 6, [5], False), ('add', 7, [6, 6], False), ('beq', 0, [7, 0], True), ('add', 8, [1, 2], False)]
assert pipe_cycles(prog) == 11, "Lesson 42's sequence: 11 cycles."
assert pipe_cycles([('add', 1, [2, 3], False)] * 10) == 14, "Ten independent instructions: 14 cycles."
assert pipe_cycles([('lw', 0, [5], False), ('add', 7, [0, 0], False)]) == 6, "x0 never causes a stall."
```

::: right
Right. The 4 is the pipeline filling; every stall and flush adds directly to the count.
:::
:::

::: check
kind: python

## Write `amat2(h1, m1, h2, m2, mem)`: the two-level average memory access time, and `l1_miss_for(target, h1, h2, m2, mem)`: the largest L1 miss rate that meets a target AMAT.

```python starter
def amat2(h1, m1, h2, m2, mem):
    return h1

def l1_miss_for(target, h1, h2, m2, mem):
    return 0.0
```

```python solution
def amat2(h1, m1, h2, m2, mem):
    return h1 + m1 * (h2 + m2 * mem)

def l1_miss_for(target, h1, h2, m2, mem):
    return (target - h1) / (h2 + m2 * mem)
```

```python tests
assert abs(amat2(1, 0.05, 10, 0.2, 100) - 2.5) < 1e-12, "5% L1 misses, 20% of them missing L2: 2.5 cycles."
assert abs(l1_miss_for(2.5, 1, 10, 0.2, 100) - 0.05) < 1e-12, "And back again."
assert amat2(1, 0.05, 10, 0.2, 100) < amat2(1, 0.05, 0, 1, 100), "An L2 beats going straight to memory."
```

::: right
Right. The L2's job is to turn the L1's misses from memory trips into short detours.
:::
:::

::: explain
## How can a cache that is big enough to hold a matrix column still miss on every access when walking down that column?

::: model
A set-associative cache doesn't let a line go anywhere: its address picks one set, and each set holds only a few lines. When the matrix's rows are a power of two bytes long, stepping down a column advances the address by that stride, and the set index, which is taken from low address bits, repeats after only a few rows. Hundreds of the column's lines then crowd into a handful of sets, each with room for only four, so each line is evicted before it's reused. These are conflict misses: the total capacity is ample, but the mapping concentrates the data. Padding each row or changing the loop order spreads the accesses across all the sets.
:::
:::
