---
title: Computer organization lab
heading: Simulating a cache, a branch predictor and a pipeline in Python
eyebrow: C8 · Lesson 49 · Computer organization lab
xp: 50
---

::: hook
Architects don't build a processor to find out whether a bigger cache or a better predictor is worth it. They write simulators: programs that replay the addresses and branch outcomes of real software through a model of the hardware and count the misses and stalls. In this lab you'll write the three classic ones, an LRU set-associative cache, 1-bit and 2-bit branch predictors, and a cycle counter for the five-stage pipeline, and check each against the numbers worked out by hand in lessons 40, 25 and 27.
:::

::: play
- A loop sweeps an array of W KiB again and again, P times, through a fully associative LRU cache with 64-byte lines, reading 4-byte words. The curve is the miss rate against the cache size.
- Once the cache holds the whole array, only the first pass misses. Shrink the cache below W and the rate jumps to one miss per line on every pass: LRU always throws out exactly the line the sweep needs next.
- Your cache simulator will reproduce this cliff, at 17 KiB against 15 KiB in a 16 KiB cache.
:::
:::

```sim plot
view: graph
x: C = 1..64 KiB
y: m = 0..0.07
slider: W = 2..60 step 1 = 24
slider: P = 2..20 step 1 = 10
plot: 4/64*(step(W - C) + (1 - step(W - C))/P) | label: miss rate
readout: miss rate with a cache bigger than the array = 4/64/P | digits: 3
readout: miss rate with a cache smaller than the array = 4/64 | digits: 3
```

::: predict
## A 16 KiB fully associative LRU cache with 64-byte lines. A loop reads every word of a 17 KiB array, three times over. How many misses?

- [ ] 272: only the first pass misses
- [ ] 288: the first pass, plus one line per later pass
- [x] 816: every line misses on every pass
- [ ] 13,056: every word misses

::: reveal
816. The array is 272 lines and the cache holds 256. When the sweep comes back to the start, LRU has evicted exactly the oldest lines, the ones about to be read, and each miss evicts the next one needed. All 272 lines miss on each of the three passes. A 15 KiB array would miss only 240 times, all on the first pass.
:::
:::

::: nameit
## A cache simulator

For each address: the **block** is address // line, the **set** is block % sets (sets = size / (line × ways)), and each set is a list of blocks in order of use. A hit moves the block to the most recently used end; a miss appends it, first evicting the least recently used block if the set is full.

## A predictor simulator

Keep one state per branch (here, a single branch). A 1-bit predictor's state is the last outcome. A 2-bit counter runs from 0 to 3, predicts taken at 2 or 3, and moves one step toward each outcome. Start the 1-bit predictor at not taken and the 2-bit counter at 1, weakly not taken.

## A pipeline cycle counter

For a five-stage pipeline with forwarding, predicting branches not taken: N instructions take 4 + N cycles, plus 1 for each load whose result the very next instruction uses, plus 2 for each taken branch. A trace entry here is `(kind, dest, sources, taken)`, with kind one of `'alu'`, `'load'`, `'store'` or `'branch'`.
:::

::: example
## Trace a 2-way LRU set through the blocks 1, 2, 1, 3, 2.

::: solution
1. **Block 1.** It misses: [1].
2. **Block 2.** It misses: [1, 2].
3. **Block 1 again.** It hits and becomes most recent: [2, 1].
4. **Block 3.** It misses and evicts 2, the least recent: [1, 3].
5. **Block 2 again.** It misses and evicts 1: [3, 2].

**Answer:** four misses and one hit, leaving [3, 2] in the set.
:::
:::

::: example
## Count the cycles for: `lw t0, 0(a0)`; `add t1, t0, t2`; a taken branch; `addi t3, t3, 1` (the branch target).

::: solution
1. **Fill the pipeline.** Four instructions take 4 + 4 = 8 cycles.
2. **The load-use pair.** It adds 1.
3. **The taken branch.** It adds 2.
4. **The total.**
   $$8 + 1 + 2 = 11\ \text{cycles}$$
   a CPI of 2.75 over this short stretch.
5. **Why so high.** Most of that is the pipeline filling; over thousands of instructions the 4 disappears into the average.

**Answer:** 11 cycles, a CPI of 2.75.
:::
:::

::: check
given: n = 3 | 4 | 6
answer: 4 + n + 1 + 2
unit: cycles
tolerance: 0

## A trace of {n} instructions has one load-use pair and one taken branch. How many cycles does the five-stage pipeline take?

::: right
Right. 4 + {n} + 1 + 2.
:::

::: misses
- [n + 3] Add the 4 cycles it takes the first instruction to fill the pipeline.
- [any] Not yet. 4 + N + stalls.
:::
:::

::: check
given: k = 2 | 5 | 10
answer: 2*k
tolerance: 0

## A branch's outcome alternates taken, not taken, for {k} pairs. How many times does a 2-bit counter that starts at 1 mispredict it?

::: right
Right. Every one: it never gets two outcomes in a row to settle on.
:::

::: misses
- [k] The counter moves between 1 and 2 and guesses wrong each time.
- [any] Not yet. Trace a few steps from state 1.
:::
:::

::: check
kind: python

## Write `cache_misses(addresses, size, line, ways)`: the number of misses for a list of byte addresses in an LRU set-associative cache of `size` bytes, with `line`-byte lines and `ways` lines per set, starting empty.

```python starter
def cache_misses(addresses, size, line, ways):
    return len(addresses)
```

```python solution
def cache_misses(addresses, size, line, ways):
    sets = size // (line * ways)
    cache = [[] for _ in range(sets)]
    misses = 0
    for a in addresses:
        block = a // line
        s = cache[block % sets]
        if block in s:
            s.remove(block)
        else:
            misses += 1
            if len(s) == ways:
                s.pop(0)
        s.append(block)
    return misses
```

```python tests
seq = list(range(0, 1024, 4))
assert cache_misses(seq, 256, 64, 1) == 16, f"Reading 1024 bytes in order with 64-byte lines should miss 16 times, got {cache_misses(seq, 256, 64, 1)}."
ab = [x for i in range(64) for x in (0x1000 + 4 * i, 0x2000 + 4 * i)]
assert cache_misses(ab, 4096, 16, 1) == 128, f"a[i] and b[i] 4 KiB apart in a direct-mapped 4 KiB cache should miss every time (128), got {cache_misses(ab, 4096, 16, 1)}."
assert cache_misses(ab, 4096, 16, 2) == 32, f"With 2 ways they fit together: 32 misses, got {cache_misses(ab, 4096, 16, 2)}."
sweep = lambda kb, p: [a for _ in range(p) for a in range(0, kb * 1024, 4)]
assert cache_misses(sweep(17, 3), 16384, 64, 256) == 816, "Three sweeps of 17 KiB through a 16 KiB LRU cache should miss 816 times."
assert cache_misses(sweep(15, 3), 16384, 64, 256) == 240, "Three sweeps of 15 KiB should miss only on the first pass: 240."
assert cache_misses([0, 64, 0, 128, 64], 128, 64, 2) == 4, "Blocks 0, 1, 0, 2, 1 in one 2-way set: four misses (LRU)."
```

::: right
Right. The same 30 lines of logic, scaled up, are how cache designs are evaluated.
:::
:::

::: check
kind: python

## Write `mispredictions(outcomes, bits)`: the number of wrong guesses a predictor makes on a list of outcomes (1 taken, 0 not taken). `bits` is 1 (start at not taken) or 2 (a counter from 0 to 3, starting at 1, predicting taken at 2 or 3).

```python starter
def mispredictions(outcomes, bits):
    return 0
```

```python solution
def mispredictions(outcomes, bits):
    state = 0 if bits == 1 else 1
    wrong = 0
    for t in outcomes:
        guess = state if bits == 1 else (1 if state >= 2 else 0)
        if guess != t:
            wrong += 1
        if bits == 1:
            state = t
        else:
            state = min(3, state + 1) if t else max(0, state - 1)
    return wrong
```

```python tests
loop = ([1] * 9 + [0]) * 5
assert mispredictions(loop, 1) == 10, f"A 10-iteration loop run 5 times: the 1-bit predictor misses twice a run (10), got {mispredictions(loop, 1)}."
assert mispredictions(loop, 2) == 6, f"The 2-bit counter misses twice in the first run and once in each later one (6), got {mispredictions(loop, 2)}."
assert mispredictions([1, 0] * 10, 2) == 20, "Alternating outcomes defeat a 2-bit counter that starts at 1: 20 misses."
assert mispredictions([1] * 20, 2) == 1, "Always taken: one miss while the counter warms up."
assert mispredictions([0] * 7, 1) == 0, "Never taken, starting at not taken: no misses."
```

::: right
Right. Real predictors add history: they index the counters with the outcomes of recent branches, which learns patterns like the alternating one.
:::
:::

::: check
kind: python

## Write `pipeline_cycles(trace)`: the cycles a five-stage pipeline with forwarding takes for a list of `(kind, dest, sources, taken)` entries. N instructions take 4 + N cycles, plus 1 when a `'load'` is followed at once by an instruction whose sources include its dest, plus 2 for each taken `'branch'`.

```python starter
def pipeline_cycles(trace):
    return len(trace)
```

```python solution
def pipeline_cycles(trace):
    cycles = 4 + len(trace)
    for i, (kind, dest, srcs, taken) in enumerate(trace):
        if kind == 'load' and i + 1 < len(trace) and dest in trace[i + 1][2]:
            cycles += 1
        if kind == 'branch' and taken:
            cycles += 2
    return cycles
```

```python tests
tr = [('load', 't0', ('a0',), False), ('alu', 't1', ('t0', 't2'), False), ('alu', 't3', ('t1',), False),
      ('branch', None, ('t3', 'zero'), True), ('load', 't4', ('a1',), False), ('store', None, ('t4', 'a1'), False)]
assert pipeline_cycles(tr) == 14, f"Two load-use pairs and a taken branch over 6 instructions: 4 + 6 + 2 + 2 = 14, got {pipeline_cycles(tr)}."
assert pipeline_cycles([('alu', 't0', ('t1',), False)] * 10) == 14, "Ten independent ALU instructions: 14 cycles."
sep = [('load', 't0', ('a0',), False), ('alu', 't5', ('t6',), False), ('alu', 't1', ('t0',), False)]
assert pipeline_cycles(sep) == 7, "With an independent instruction between the load and its use, there's no stall: 7 cycles."
assert pipeline_cycles([('branch', None, ('t0',), False)] * 3) == 7, "Untaken branches cost nothing extra when predicted not taken."
```

::: right
Right. The second test is the compiler's trick: move an independent instruction into the load's shadow and the stall disappears.
:::
:::

::: explain
## Why does an LRU cache do so badly when a loop sweeps an array just slightly larger than the cache?

::: model
LRU evicts the line that was used longest ago. In a repeated sweep, the line used longest ago is always the one the sweep will need soonest, because the sweep returns to lines in the same order it left them. So when the array doesn't quite fit, every new line evicts the next line to be read, and that line then misses and evicts the one after it, all the way round. The cache keeps the wrong lines at every moment and the hit rate collapses from nearly perfect to nothing. Random replacement, which sometimes keeps old lines, does much better in exactly this case.
:::
:::

::: practice

::: check
given: W = 4 | 32; L = 32 | 64; P = 2 | 5
answer: W*1024/L
tolerance: 0

## A {W} KiB array is swept {P} times through a bigger cache with {L}-byte lines. How many misses?

::: misses
- [any] Only the first pass misses, once per line.
:::
:::

::: check
given: N = 5 | 12; u = 1 | 2; b = 0 | 1 | 3
answer: 4 + N + u + 2*b
unit: cycles
tolerance: 0

## {N} instructions with {u} load-use pairs and {b} taken branches: how many pipeline cycles?

::: misses
- [any] 4 + N + u + 2b.
:::
:::

::: check
given: n = 4 | 10 | 25; r = 3 | 8
answer: r + 1
tolerance: 0

## An {n}-iteration loop is run {r} times. How many times does a 2-bit counter starting at 1 mispredict its closing branch?

::: misses
- [any] Twice in the first run, once in each later one.
:::
:::
:::
