Skip to content

Unit 4 · Memory Hierarchy and Caches

3 h contact · 7 h self study Prerequisites: Unit 3 CLO 2

1. Setting the scene

Scenario: Same work, twelve times slower

SensorGrid stores one day of readings as a matrix X[sensor][time]. Two team members write the same calibration step, adding an offset K to every value. Both loops perform exactly \(4096 \times 4096\) additions. One finishes in 0.01 s, the other in 0.12 s.

The only difference is the order of the two for loops.

Guiding questions

  1. If arithmetic is cheap, what is expensive?
  2. How does the hardware make a large, slow memory look fast?
  3. How must we lay out and traverse data so that the hardware can help us?

2. Intended learning outcomes

# Outcome Bloom CLO
ILO 4.1 Explain the Von Neumann bottleneck and the processor memory performance gap. UNDERSTAND 2
ILO 4.2 Describe the memory hierarchy and the trade off between speed, size and cost. UNDERSTAND 2
ILO 4.3 Compute the average memory access time (AMAT) for one and two cache levels. APPLY 2
ILO 4.4 Compare write through and write back, write allocate and no write allocate policies. ANALYSE 2
ILO 4.5 Decompose a memory address into tag, index and offset, and map blocks in a direct mapped cache. APPLY 2
ILO 4.6 Predict the cache behaviour of loops from temporal and spatial locality. ANALYSE 2

3. The Von Neumann bottleneck

Getting data from memory is slower than processing it.

  • Cause: CPU and memory share one data path, and its bandwidth is far below the rate at which the CPU can process data internally.
  • Impact: the CPU waits for data, and the waiting, not the arithmetic, limits speed.
flowchart LR
    CPU["CPU<br/>billions of operations per second"] <-->|"narrow shared bus"| MEM[("Main memory<br/>hundreds of cycles per access")]

The processor memory performance gap

Since 1980 processors became thousands of times faster, memory latency only a few times. A DRAM access that took one cycle in 1980 takes hundreds of cycles today. We cannot afford to stall the processor for that long.

xychart-beta
    title "Illustrative performance growth relative to 1980 (log scale idea)"
    x-axis "Year" [1980, 1985, 1990, 1995, 2000, 2005]
    y-axis "Relative performance (log10)" 0 --> 4
    line [0, 0.8, 1.6, 2.4, 3.2, 3.6]
    line [0, 0.15, 0.3, 0.45, 0.6, 0.75]

Upper line: processor; lower line: DRAM. The vertical distance is the gap.

Solutions

mindmap
  root((Beat the<br/>bottleneck))
    Caching
      hot data close
    Hierarchy
      several levels
    Parallelism
      work while waiting
    Multitasking
      switch on stalls

4. The memory hierarchy

No single memory can be both very fast and very large. Processors therefore use several levels.

flowchart TB
    R["<b>Registers</b><br/>bytes · ~1 cycle"]
    L1["<b>L1 cache</b><br/>tens of KB · ~4 cycles"]
    L2["<b>L2 cache</b><br/>hundreds of KB to MB · ~12 cycles"]
    L3["<b>L3 / shared cache</b><br/>tens of MB · ~40 cycles"]
    M["<b>Main memory (DRAM)</b><br/>GB · ~200 cycles"]
    D["<b>Disk / SSD</b><br/>TB · 10⁴ to 10⁷ cycles"]
    R --> L1 --> L2 --> L3 --> M --> D

Moving down: capacity increases, access becomes slower, cost per byte falls. The rule of the hierarchy: the cheaper the memory, the slower the access. Registers are managed by the compiler, caches by hardware, main memory and disk by the operating system.

Cache memory is a small, fast memory between two levels (CPU and RAM, or RAM and disk). It makes the system behave as if it had a large and fast memory.

5. Hits, misses and stalls

sequenceDiagram
    participant C as Core
    participant L as Cache
    participant M as Main memory
    C->>L: load address X
    alt hit
        L-->>C: data (fast, hit time)
    else miss
        L->>M: fetch the whole block containing X
        Note over C: stall, no useful work
        M-->>L: block (miss penalty)
        L-->>C: data
    end
Metric Meaning
Hit requested data is found in the cache
Miss data is not in the cache and must be fetched from slower memory
Hit ratio fraction of accesses that hit (higher is better)
Miss ratio \(1 - \text{hit ratio}\)
Hit time time to deliver data from the cache
Miss penalty extra time to fetch data from the slower level

Average memory access time

\[ \text{AMAT} = \text{Hit time} + \text{Miss rate} \times \text{Miss penalty} \]

Worked example

Hit time 2, miss rate 10 %, miss penalty 50 time units:

\[ \text{AMAT} = 2 + 0.1 \times 50 = 7 \text{ time units} \]

Halving the miss rate to 5 % gives \(2 + 2.5 = 4.5\): a 36 % faster memory system without faster hardware.

With two cache levels, the L1 miss penalty is itself an average access time of L2:

\[ \text{AMAT} = HT_{1} + MR_{1}\big(HT_{2} + MR_{2} \times MP_{2}\big) \]

Worked example: two levels

\(HT_1 = 1\), \(MR_1 = 0.05\), \(HT_2 = 10\), \(MR_2 = 0.2\) (local), \(MP_2 = 200\) cycles:

\[ \text{AMAT} = 1 + 0.05\,(10 + 0.2 \times 200) = 1 + 0.05 \times 50 = 3.5 \text{ cycles} \]

Without any cache every access would cost 200 cycles: the hierarchy gives a 57× improvement.

Prefetching loads data into the cache before the processor asks for it. It requires accurately predicting future accesses, which works well for sequential patterns.

6. Reads and writes

flowchart LR
    C["CPU requests address"] --> Q{"In cache?"}
    Q -->|"yes"| R["Return data from cache"]
flowchart TB
    C["CPU requests address"] --> Q{"In cache?"}
    Q -->|"no"| F["Fetch block from memory"] --> P["Place block in a cache line"] --> R["Return data"]

Write hit: two policies

sequenceDiagram
    participant C as CPU
    participant L as Cache
    participant M as Memory
    Note over C,M: Write through
    C->>L: write X
    L->>M: write X immediately
    Note over C,M: Write back
    C->>L: write X (line marked dirty)
    Note over L: ...later, when the line is replaced...
    L->>M: write the dirty line
  • Write through: data is written to cache and main memory immediately. Analogy: saving a document locally and to the cloud at the same moment.
  • Write back: data is written to the cache only; memory is updated later, when the block is replaced. Analogy: saving locally now, uploading to the cloud later.

A write back cache tracks a dirty bit per line:

stateDiagram-v2
    [*] --> Invalid
    Invalid --> Clean : read miss, block loaded
    Clean --> Dirty : write hit
    Dirty --> Dirty : further writes
    Dirty --> Invalid : evicted, block written to memory
    Clean --> Invalid : evicted, nothing to write

Write miss

  • Write allocate: load the block into the cache first, then write (usually paired with write back).
  • No write allocate: write directly to main memory (usually paired with write through).

7. Locality: why caches work

for (i = 0; i < M; i++)
    for (j = 0; j < N; j++)
        X[i][j] = X[i][j] + K;      /* each element is a double: 8 bytes */

The loop body runs \(M \times N\) times and updates every element exactly once:

\[ X' = \begin{pmatrix} x_{00}+K & x_{01}+K & \cdots & x_{0,N-1}+K \\ \vdots & & \ddots & \vdots \\ x_{M-1,0}+K & \cdots & & x_{M-1,N-1}+K \end{pmatrix} \]
  • Temporal locality: recently used items are used again soon. The loop code, i, j and K are reused in every iteration and stay in cache and registers.
  • Spatial locality: items near a recently used item are used soon. X[i][j] and X[i][j+1] are neighbours in memory; loading one block brings in several of them.

Cache lines

On every miss a fixed block (a cache line, typically 64 bytes) is transferred, more than the processor asked for. Transfers between memory and cache are in blocks; between cache and registers in words (4 bytes on a 32 bit CPU, 8 bytes on a 64 bit CPU).

block-beta
  columns 8
  a0["x[0]"] a1["x[1]"] a2["x[2]"] a3["x[3]"] a4["x[4]"] a5["x[5]"] a6["x[6]"] a7["x[7]"]
  space:8
  L["one 64 byte cache line = 8 doubles, loaded together"]:8

Row wise versus column wise

C stores matrices in row major order: X[i][j] and X[i][j+1] are adjacent.

flowchart TB
    subgraph RW["Row wise: stride 1"]
      direction LR
      r1["X[0][0]"] --> r2["X[0][1]"] --> r3["X[0][2]"] --> r4["X[0][3]"]
    end
    subgraph CW["Column wise: stride N"]
      direction LR
      c1["X[0][0]"] --> c2["X[1][0]"] --> c3["X[2][0]"] --> c4["X[3][0]"]
    end
    RW ~~~ CW

With 8 doubles per line, row wise access misses once every 8 elements; column wise access with a large \(N\) may miss on every element:

\[ MR_{\text{row}} \approx \frac{8\ \text{bytes}}{64\ \text{bytes}} = \frac{1}{8} = 12.5\,\%, \qquad MR_{\text{column}} \approx 100\,\% \]
/* 4096 × 4096 doubles, gcc -O2, measured on a typical x86 server */
for (int i = 0; i < N; i++)        /* row wise:    0.010 s */
    for (int j = 0; j < N; j++)
        X[i][j] += K;

for (int j = 0; j < N; j++)        /* column wise: 0.120 s, about 12x slower */
    for (int i = 0; i < N; i++)
        X[i][j] += K;

This answers the scenario: same arithmetic, twelve times the time, only because of the memory access pattern.

8. Cache design

Design questions every cache must answer:

  • Block placement: where can a block be stored?
  • Mapping function: how do memory blocks map to cache lines?
  • Block replacement: which block is evicted when the cache is full (for example, least recently used)?
  • Write policy: how are writes handled (Section 6)?

Splitting an address

With blocks of \(B\) bytes, the lowest \(b = \log_2 B\) bits of an address select a byte within the block (the offset). For \(B = 64\): \(b = \log_2 64 = 6\) bits.

\[ \text{block number} = \left\lfloor \frac{\text{address}}{B} \right\rfloor, \qquad \text{offset} = \text{address} \bmod B \]

For a direct mapped cache with \(L\) lines, the next \(s = \log_2 L\) bits are the index, and the rest is the tag:

 | ←──────── tag ────────→ | ←── index (s bits) ──→ | ←─ offset (b bits) ─→ |
\[ t = A - s - b \]

Worked example

32 bit addresses, 64 byte lines, 256 lines: \(b = 6\), \(s = \log_2 256 = 8\), \(t = 32 - 8 - 6 = 18\) bits.

Address 0x0000_1234 = 4660: block number \(\lfloor 4660/64 \rfloor = 72\), offset \(4660 \bmod 64 = 52\), index \(72 \bmod 256 = 72\), tag \(\lfloor 72/256 \rfloor = 0\).

Mapping functions

Type A memory block may go to Hardware cost Conflict misses
Direct mapped exactly one line lowest highest
Set associative any line of one set medium medium
Fully associative any line highest lowest

Direct mapping

Each cache line stores three things: the data block, a tag (which of the many blocks mapping to this line is present) and a valid bit (whether the line holds a valid, up to date block).

\[ \text{cache line} = \text{block number} \bmod L \]
flowchart LR
    B0["Block 0"] --> C0["Line 0"]
    B4["Block 4"] --> C0
    B8["Block 8"] --> C0
    B1["Block 1"] --> C1["Line 1"]
    B5["Block 5"] --> C1
    B2["Block 2"] --> C2["Line 2"]
    B3["Block 3"] --> C3["Line 3"]
    B7["Block 7"] --> C3

Worked example: 4 lines, access sequence 0, 4, 0, 8, 1, 5, 1

Access Line (\(b \bmod 4\)) That line before Result
0 0 empty miss (compulsory)
4 0 block 0 miss (compulsory), evicts 0
0 0 block 4 miss (conflict), evicts 4
8 0 block 0 miss (compulsory), evicts 0
1 1 empty miss (compulsory)
5 1 block 1 miss (compulsory), evicts 1
1 1 block 5 miss (conflict), evicts 5

Seven accesses, seven misses, although only 5 distinct blocks are used and the cache has 4 lines. A 2 way set associative cache would keep 0 and 4 together and hit on the third access. This is why set associativity exists.

9. Data movement is the real cost

flowchart LR
    A["Arithmetic<br/>~1 unit of energy"] --> B["Cache access<br/>~10 units"] --> C["DRAM access<br/>~100 units and more"]

The farther data travels, the more time and energy it costs, and the longer the processor may stall. Practical rule: reduce unnecessary data movement before adding more cores.

For data science and AI this is central: tables, matrices, tensors, embeddings and model parameters are processed again and again. When recently used data stays in cache, the processor computes; when every access goes to DRAM, the execution units mostly wait.

10. Parallel execution inside one chip

When one core is limited by dependencies, stalls and power, the chip offers three other ways to keep hardware busy.

flowchart TB
    subgraph MC["1 · Multicore"]
      direction LR
      c1["Core 1<br/>stream A"]
      c2["Core 2<br/>stream B"]
      c3["Core 3<br/>stream C"]
      c4["Core 4<br/>stream D"]
    end
    subgraph SI["2 · SIMD / vector"]
      direction LR
      v["one ADD<br/>instruction"] --> l1["lane 0"] & l2["lane 1"] & l3["lane 2"] & l4["lane 3"]
    end
    subgraph HT["3 · Hardware threads"]
      direction LR
      h1["thread 1 waits<br/>for memory"] -.-> h2["thread 2 runs<br/>meanwhile"]
    end
    MC ~~~ SI ~~~ HT

From a sequential loop to data parallelism

for (int i = 0; i < N; i++)
    y[i] = sin(x[i]);

The loop describes one ordered instruction stream, \(y_0 \to y_1 \to y_2 \to \cdots\). Even with many cores, nothing runs in parallel until the program exposes independent work. Because each iteration is independent, the array can be split into chunks:

flowchart LR
    X["x[0..15]"] --> K1["Core 1<br/>x[0..3]"] & K2["Core 2<br/>x[4..7]"] & K3["Core 3<br/>x[8..11]"] & K4["Core 4<br/>x[12..15]"]
    K1 & K2 & K3 & K4 --> Y["y[0..15]"]
\[ \text{chunk size} = \left\lceil \frac{N}{P} \right\rceil, \qquad \text{core } p \text{ handles } i \in \big[p \cdot \tfrac{N}{P},\; (p+1)\cdot\tfrac{N}{P}\big) \]

In data science the same idea appears as splitting a dataset by rows: every worker applies the same feature transformation to its own rows, and the results are combined. Unit 9 does exactly this with OpenMP.

11. Classwork

Cache arithmetic (25 min)

  1. Hit time 1 ns, miss penalty 80 ns. What miss rate gives an AMAT of 3 ns?
  2. A direct mapped cache has 16 lines of 32 bytes and 16 bit addresses. How many offset, index and tag bits? To which line does address 1000 map?
  3. For double A[1024][1024], how many misses (approximately) does a column wise sum cause with 64 byte lines, if the cache is much smaller than one column's worth of lines?
Solutions
  1. \(3 = 1 + MR \times 80 \Rightarrow MR = 2.5\,\%\).
  2. \(b = 5\), \(s = 4\), \(t = 7\). Block \(= \lfloor 1000/32 \rfloor = 31\), line \(= 31 \bmod 16 = 15\).
  3. Every access misses: about \(1024^2 \approx 10^6\) misses, versus about \(10^6/8 \approx 1.3 \times 10^5\) row wise.

12. Check your understanding

Why does a cache line contain more than the requested word?

To exploit spatial locality: neighbouring data is likely to be used soon, and transferring a block costs little more than transferring a word.

When is write back better than write through?

When the same data is written many times before eviction: write back sends one memory write per eviction instead of one per store.

Why can adding cores fail to speed up a memory bound loop?

All cores share the same memory bandwidth. If the loop is limited by data movement, more cores just wait in a longer queue.

13. Key takeaways

  • The Von Neumann bottleneck: memory is far slower than the processor.
  • The hierarchy (registers, L1, L2, L3, DRAM, disk) trades speed for size; caches hide latency.
  • \(\text{AMAT} = HT + MR \times MP\); small changes in miss rate matter a lot.
  • Caches work because of temporal and spatial locality; traverse data in memory order.
  • Direct mapped caches are simple but suffer conflict misses; associativity reduces them.
  • Before adding cores, reduce data movement.

Portfolio experiments must include at least one memory access pattern comparison (for example row wise versus column wise, or array of structs versus struct of arrays), with measured times and an AMAT based explanation.

Further reading

  • S. Dandamudi, Fundamentals of Computer Organization and Design, Springer, 2003, ch. 17.
  • J. L. Hennessy, D. A. Patterson, Computer Architecture: A Quantitative Approach, ch. 2.
  • U. Drepper (2007), What Every Programmer Should Know About Memory.