Log inStart free
LESSON 26.01 · 6 STAGES · 2 CONTROLS · 3 CHECKS

The CPU memory hierarchy

Watch two vector passes pull data through three caches.


EXPLAINER · 26.01 · MEMORY BAY
01
Stage 1 of 6 · Vectors in RAM
RAM holds a and b and room for c and d, 4 KB each. The add c = a + b reads 2 floats and writes 1.
Explain it simply

The bottom row is RAM, the computer's main memory. It holds the inputs a and b in teal and room for the results. Each small cell is 64 bytes, which is 16 numbers. Next to it, one cell is opened up.

RAM holds vectors a and b, 1,024 floats each, and room for c and d. One 64-byte line of a opens next to it: 16 floats, among them a₀ = 3.46.

inputs a, bresults c, dcachesRAM tripsempty line
Toy: 1,024-float vectors, caches shrunk to fit
HOVER OR TAP A SHAPE TO SEE ITS NUMBERS
In order
The order the loop visits the elements.
Medium: L1 4 KB
Each cache is 4 times the one above.
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
ci=ai+bi\sy{c}{out}{c_i} = \sy{a}{data}{a_i} + \sy{b}{data}{b_i}
3×1,024×4 B=12 KB3 \times 1{,}024 \times 4\,\text{B} = 12\,\text{KB}

Each result adds one float of a to one float of b.

Show the code ▾Hide the code ▴ · Try it yourself · Python 3
# 26.01 The CPU memory hierarchy: c = a + b, then d = a * b, through three LRU caches and RAM
from collections import OrderedDict

def mulberry32(seed):  # the lesson's seeded random numbers
    s = seed & 0xFFFFFFFF
    def rnd():
        nonlocal s
        s = (s + 0x6D2B79F5) & 0xFFFFFFFF
        t = ((s ^ (s >> 15)) * (1 | s)) & 0xFFFFFFFF
        t = ((t + (((t ^ (t >> 7)) * (61 | t)) & 0xFFFFFFFF)) & 0xFFFFFFFF) ^ t
        return (t ^ (t >> 14)) / 4294967296
    return rnd

N, LINE, WAYS = 1024, 64, 8                       # floats, bytes a line, lines a set
LATENCY = {"L1": 4, "L2": 12, "L3": 40, "RAM": 200}  # cycles for one access served there
BANDWIDTH = {"L1": 64, "L2": 32, "L3": 16, "RAM": 8}  # bytes a cycle to the level above
SIZES = {"L1": 4096, "L2": 16384, "L3": 65536}  # bytes: medium caches
ORDER = "in"  # "in" or "random"
BASE = {"a": 0x0000, "b": 0x1000, "c": 0x2000, "d": 0x3000}  # 4 KB a vector

rnd = mulberry32(2601)
a = [int(rnd() * 1000) / 100 for _ in range(N)]
b = [int(rnd() * 1000) / 100 for _ in range(N)]

class Cache:  # set-associative, least recently used line leaves first
    def __init__(self, size):
        self.n_sets = size // LINE // WAYS
        self.sets = [OrderedDict() for _ in range(self.n_sets)]
    def lookup(self, line):
        s = self.sets[line % self.n_sets]
        if line in s:
            s.move_to_end(line)
            return True
        return False
    def fill(self, line):
        s = self.sets[line % self.n_sets]
        s[line] = True
        if len(s) > WAYS:
            s.popitem(last=False)

caches = {name: Cache(size) for name, size in SIZES.items()}

def access(vec, i):  # returns the level that served it; copies the line into each level that missed
    line = (BASE[vec] + 4 * i) // LINE
    missed, level = [], "RAM"
    for name, cache in caches.items():
        if cache.lookup(line):
            level = name
            break
        missed.append(name)
    for name in missed:
        caches[name].fill(line)
    return level

def order(p):
    idx = list(range(N))
    if ORDER == "random":
        rnd = mulberry32(2601 + 1 + p)
        for k in range(N - 1, 0, -1):
            j = int(rnd() * (k + 1))
            idx[k], idx[j] = idx[j], idx[k]
    return idx

for p, out in enumerate(["c", "d"]):
    served = dict.fromkeys(LATENCY, 0)
    result = [0.0] * N
    for i in order(p):
        for vec in ("a", "b", out):
            served[access(vec, i)] += 1
        result[i] = a[i] + b[i] if out == "c" else a[i] * b[i]
    wait = sum(served[l] * LATENCY[l] for l in LATENCY) / (3 * N)
    up = {"L1": 3 * N * 4, "L2": (served["L2"] + served["L3"] + served["RAM"]) * LINE,
          "L3": (served["L3"] + served["RAM"]) * LINE, "RAM": served["RAM"] * LINE}
    cycles = max([N] + [up[l] // BANDWIDTH[l] for l in up])  # 1 add or multiply a cycle
    print(out, served)  # c {'L1': 2880, 'L2': 0, 'L3': 0, 'RAM': 192}  then  d {'L1': 2880, 'L2': 128, 'L3': 0, 'RAM': 64}
    print(round(wait, 2), cycles)  # 16.25 1536  then  8.42 1024

Copy it into a file and run it. Change SIZES and ORDER to match the controls.

Common mix-ups

MYTHReading one float from RAM moves only 4 bytes.

FIXRAM sends a whole 64-byte line. The next 15 floats of that line then hit L1.

MYTHThe read order does not change the time.

FIXIf the data does not fit, random reads mostly miss L1. With medium caches, the add waits 21.91 cycles an access, not 16.25.

Predict, then reveal
0 / 3 REVEALED
Q01In order, with small caches, which level refills a and b for the multiply?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q02In order, with large caches, does the add pass finish sooner?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q03With large caches, does random order slow the add pass?
1 · GUESS2 · TRY IT IN THE DIAGRAM

Takeaways

  1. Each level is bigger and slower: registers, L1, L2, L3, RAM.
  2. RAM sends whole 64-byte lines, so reads in order mostly hit L1.
  3. A vector add waits on memory bandwidth, not on the core.