---
title: Advanced cache optimizations
heading: Faster hits, memory-level parallelism, prefetching, victim caches and blocking in software
eyebrow: S4 · Lesson 19 · Advanced cache optimizations
xp: 50
---

::: hook
The average memory access time has three terms, hit time, miss rate and miss penalty, and architects have a bag of tricks for each. Way prediction and pipelining shorten hits. Victim caches and prefetchers cut misses. Non-blocking caches let several misses overlap, so the penalty is paid once for many of them. And some of the largest gains come from software: restructuring a loop so it reuses data while it's still in the cache can cut a matrix multiply's memory traffic by a factor of thirty without changing the hardware at all.
:::

::: play
- Words moved between cache and memory for an N × N matrix multiply, divided by $N^3$, against the block size B of a blocked (tiled) version: about $2/B + 1/N$.
- The unblocked loop (B = 1) moves about 2 words per multiply-add. Blocking reuses each loaded block B times, cutting traffic by about B.
- B is limited by the cache: three B × B blocks must fit in C words, so $B \le \sqrt{C/3}$ (the marker).
:::
:::

```sim plot
view: graph
x: B = 1..128 log
y: q = 0.01..3 log
slider: N = 256..4096 = 1024 log
slider: C = 512..65536 = 4096 log
plot: 2/B + 1/N | samples: 300 | label: words moved per multiply-add
marker: x = sqrt(C/3) | label: largest block that fits
readout: largest block = sqrt(C/3)
readout: traffic reduction at that block = (2 + 1/N)/(2/sqrt(C/3) + 1/N)
```

::: predict
## A program misses 10 times in a stretch, each miss taking 200 cycles. If the cache can keep 4 misses outstanding at once and the core has enough independent work, about how many stall cycles do the 10 misses cost?

- [ ] 2000
- [x] About 500
- [ ] 200
- [ ] 50

::: reveal
About 500: overlapped four at a time, the ten misses take about 10 × 200 / 4 cycles. That's memory-level parallelism (MLP), and it needs a non-blocking cache with miss status holding registers (MSHRs) to track the outstanding misses, plus an out-of-order core or prefetcher to issue them early. A blocking cache would stall all 2000 cycles.
:::
:::

::: nameit
## Faster hits

- **Small, simple L1s** with low associativity; **way prediction** guesses which way will hit and reads only it. With prediction accuracy p, hit time = $p\,h_\text{fast} + (1 - p)h_\text{slow}$.
- **Pipelined** cache access raises bandwidth (and adds cycles of latency); **banks** let several accesses proceed at once.

## Fewer or cheaper misses

- **Victim cache:** a small fully associative buffer of recently evicted lines catches conflict misses of a direct-mapped cache.
- **Hardware prefetching:** stride and stream prefetchers detect regular patterns and fetch ahead. To hide a latency L with iterations taking t cycles, prefetch $\lceil L/t \rceil$ iterations ahead.
- **Critical word first** and **early restart** shorten the effective penalty.
- **Non-blocking caches:** with an average of MLP misses overlapped, the stall per miss is about penalty/MLP.
- **Merging write buffers** combine writes to the same line.

## Compiler and programmer optimizations

- **Loop interchange** walks arrays in the order they're stored.
- **Blocking (tiling)** works on sub-blocks that fit in the cache. For an N × N matrix multiply, the unblocked version moves about $2N^3 + N^2$ words in the worst case; with B × B blocks, about $\frac{2N^3}{B} + N^2$. Three blocks must fit: $3B^2 \le C$.
:::

::: example
## A 1024 × 1024 matrix multiply in doubles runs with a 32 KB cache (4096 doubles). What's the largest block, and how much traffic does blocking with B = 32 save?

::: solution
1. **Largest block.**
   $$\sqrt{4096/3} = 36.95$$
   so a power-of-two block of 32.
2. **Unblocked traffic.**
   $$\begin{aligned} W &= 2 \times 1024^3 + 1024^2 \\ &= 2.15 \times 10^9\ \text{words} \end{aligned}$$
3. **Blocked traffic.**
   $$\begin{aligned} W &= 2 \times 1024^3/32 + 1024^2 \\ &= 6.8 \times 10^7\ \text{words} \end{aligned}$$
4. **Saving.** That's 31.5 times less traffic for identical arithmetic. Libraries block at several levels (registers, L1, L2) for the same reason.

**Answer:** B can be at most 36.95, so the largest power-of-two block is 32, and blocking with B = 32 cuts the traffic 31.5 times.
:::
:::

::: example
## A loop takes 25 cycles per iteration and memory latency is 200 cycles. How far ahead should it prefetch? And with way prediction 90% accurate, a 1-cycle fast hit and a 3-cycle mispredicted hit, what's the hit time?

::: solution
1. **Prefetch distance.**
   $$\lceil 200/25 \rceil = 8\ \text{iterations}$$
   ahead, so the data arrives just as it's needed (a little more allows for variation).
2. **Hit time with way prediction.**
   $$\begin{aligned} t &= 0.9 \times 1 + 0.1 \times 3 \\ &= 1.2\ \text{cycles} \end{aligned}$$
   against perhaps 2 cycles for reading every way of a set-associative cache in parallel.

**Answer:** prefetch 8 iterations ahead; way prediction gives a 1.2-cycle hit time.
:::
:::

::: example
## A program makes 10 last-level misses per thousand instructions, each costing 200 cycles. What stall CPI results if misses are serviced one at a time, and if four overlap on average?

::: solution
1. **One at a time.**
   $$10/1000 \times 200 = 2.0$$
   cycles per instruction.
2. **Four overlapping.** With memory-level parallelism of 4 the effective cost per miss is about 50 cycles:
   $$10/1000 \times 50 = 0.5$$
   cycles per instruction.
3. **The lesson.** Non-blocking caches and enough MSHRs turn a latency problem into a bandwidth problem.

**Answer:** 2.0 stall cycles per instruction one at a time, and 0.5 when four overlap.
:::
:::

::: check
given: N = 256 | 512 | 2048; B = 16 | 32 | 64
answer: (2*N^3 + N^2)/(2*N^3/B + N^2)
tolerance: 0.5%

## A {N} × {N} matrix multiply is blocked with {B} × {B} tiles. By what factor does the worst-case traffic, $2N^3 + N^2$ against $2N^3/B + N^2$, fall?

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

::: misses
- [any] Not yet. Ratio of the two traffic counts.
:::
:::

::: check
given: K = 16 | 32 | 64 | 256; e = 4 | 8
answer: floor(sqrt(K*1024/(3*e)) + 0.0001)
tolerance: 0

## A {K} KB cache holds {e}-byte elements. What's the largest whole B such that three B × B blocks fit?

::: right
Right. $\lfloor\sqrt{C/3}\rfloor$ = {answer}.
:::

::: misses
- [floor(sqrt(K*1024/e) + 0.0001)] Three blocks must fit, not one.
- [any] Not yet. Solve $3B^2 \le C$ in elements.
:::
:::

::: check
given: n = 8 | 20; L = 150 | 300; P = 2 | 5 | 8
answer: n*L/P
tolerance: 0.5%

## {n} independent misses of {L} cycles each overlap {P} at a time. About how many stall cycles do they cost?

::: right
Right. $nL/\text{MLP}$ = {answer}.
:::

::: misses
- [n*L] The misses overlap.
- [any] Not yet. Total latency divided by the overlap.
:::
:::

::: check
given: L = 120 | 250 | 400; t = 15 | 35 | 70
answer: ceil(L/t - 0.0001)
tolerance: 0

## Memory latency is {L} cycles and each loop iteration takes {t}. How many iterations ahead should the loop prefetch?

::: right
Right. $\lceil L/t \rceil$ = {answer}.
:::

::: misses
- [ceil(t/L - 0.0001)] Cover the latency with iterations.
- [any] Not yet. Iterations that fit in one latency, rounded up.
:::
:::

::: check
given: p = 0.85 | 0.95; f = 1 | 2; s = 3 | 4
answer: p*f + (1 - p)*s
tolerance: 0.5%

## Way prediction is {p} accurate; a correct guess hits in {f} cycle(s) and a wrong one in {s}. What's the average hit time?

::: right
Right. $p\,h_f + (1 - p)h_s$ = {answer}.
:::

::: misses
- [any] Not yet. Weighted average.
:::
:::

::: check
given: m = 0.04 | 0.08; c = 0.3 | 0.5; v = 0.4 | 0.7
answer: 100*m*(1 - c*v)
unit: %
tolerance: 0.5%

## A direct-mapped cache misses {m} of the time; {c} of its misses are conflicts, and a victim cache catches {v} of those. What's the new miss rate?

::: right
Right. $m(1 - cv)$ = {answer}%.
:::

::: misses
- [100*m*(1 - v)] The victim cache only catches conflict misses.
- [any] Not yet. Remove the caught share of the conflict misses.
:::
:::

::: check
kind: parts
given: N = 512 | 1024 | 2048; B = 16 | 32 | 64

## An N × N matrix multiply (N = {N}) is blocked into {B} × {B} tiles.

::: part
answer: 2*N^3 + N^2
unit: words
tolerance: 0.5%

### About how many words does the unblocked version move in the worst case?

::: misses
- [any] $2N^3 + N^2$.
:::
:::

::: part
answer: 2*N^3/B + N^2
unit: words
tolerance: 0.5%

### And the blocked version?

::: misses
- [any] $2N^3/B + N^2$.
:::
:::

::: part
answer: 3*B^2*8/1024
unit: KB
tolerance: 0.5%

### How much cache do three tiles of doubles need?

::: misses
- [B^2*8/1024] All three tiles must fit together.
- [any] $3B^2$ doubles.
:::
:::
:::

::: check
kind: parts
given: L = 150 | 300; t = 10 | 25 | 40; p = 0.8 | 0.95; a = 1 | 2; b = 3 | 4

## A loop takes {t} cycles per iteration against {L} cycles of memory latency. Way prediction is {p} accurate, with {a}-cycle predicted hits and {b}-cycle mispredicted ones.

::: part
answer: ceil(L/t)
unit: iterations
tolerance: 0

### How far ahead should the loop prefetch?

::: misses
- [any] $\lceil L/t\rceil$.
:::
:::

::: part
answer: p*a + (1 - p)*b
unit: cycles
tolerance: 0.5%

### What is the average hit time?

::: misses
- [any] $p\,h_\text{fast} + (1 - p)h_\text{slow}$.
:::
:::
:::

::: check
kind: derivation
vars: k = 0.001..0.1, P = 50..500, M = 1..16

## A program misses k times per instruction, each costing P cycles, with M misses overlapped on average.

::: step
answer: k*P

### What stall CPI does it see with blocking misses?
:::

::: step
answer: k*P/M

### And with the overlap?
:::

::: right
Right. Memory-level parallelism divides the cost of each miss, as long as misses are independent.
:::
:::

::: explain
## Why does blocking a matrix multiply cut its memory traffic without changing how many arithmetic operations it does?

::: model
A plain triple loop walks a whole row of one matrix and a whole column of another for every element it computes, and when the matrices are bigger than the cache, those rows and columns have been evicted by the time they're needed again, so the same data is fetched from memory over and over. Blocking reorders the loops so the computation works on small square tiles, three of which fit in the cache together. Each element of a tile is loaded once and then used B times while it's still cached before the code moves on. The multiply-adds are the same ones in a different order, but each word fetched from memory now does B times as much work, so the traffic drops by about that factor.
:::
:::

::: practice

::: check
given: N = 512 | 1024; B = 8 | 48
answer: (2*N^3 + N^2)/(2*N^3/B + N^2)
tolerance: 0.5%

## Traffic reduction: N = {N}, B = {B}?

::: misses
- [any] $(2N^3 + N^2)/(2N^3/B + N^2)$.
:::
:::

::: check
given: n = 12 | 30; L = 200 | 350; P = 3 | 6
answer: n*L/P
tolerance: 0.5%

## Stall: {n} misses of {L} cycles, MLP {P}?

::: misses
- [any] $nL/\text{MLP}$.
:::
:::

::: check
given: L = 180 | 320; t = 20 | 45
answer: ceil(L/t - 0.0001)
tolerance: 0

## Prefetch distance: latency {L}, {t} cycles per iteration?

::: misses
- [any] $\lceil L/t \rceil$.
:::
:::
:::
