Module contents
Lesson 19 of 26Core 105 min

Memory hierarchy, locality and the roofline model

On modern hardware moving data costs far more than operating on it. Study the memory hierarchy, cache lines, array layout and tiling, and introduce the roofline model, which uses compute peak and bandwidth to determine whether a kernel is memory-bound or compute-bound. Measurements on the course's i9-14900HX use pointer-chasing latency and STREAM bandwidth microbenchmarks.

After this lesson you can

  • Describe the memory hierarchy with latency and bandwidth orders of magnitude and measure it on the local machine.
  • Predict how traversal order and memory layout affect an algorithm's time.
  • Apply tiling to matrix multiplication and explain data reuse.
  • Calculate arithmetic intensity of common kernels and place them on a roofline.
  • Measure latency and bandwidth with pointer-chasing and STREAM microbenchmarks using the m00 benchmarking methodology.

Before you start

Motivation: the same flops, ten times longer

Take a matrix of 4096×40964096 \times 4096 float64 numbers (128 MiB) and sum all its entries twice: first row by row, then column by column. Both loops perform exactly the same 409624096^2 additions on the same data with the same compiled code. Flop counting and asymptotic analysis say they cost the same. On this course’s i9-14900HX, in the lab’s reference run, row traversal took 20.0 ms and column traversal 213.3 ms: eleven times longer. In other runs, with different machine load, the ratio ranged from 6 to 14 but never approached 1.

No operation-count model can explain the difference, which lies in moving data. A floating-point addition costs a few clock cycles; fetching a number that is not near the processor costs around a hundred nanoseconds, hundreds of cycles. For decades processor speed grew much faster than main-memory latency, and Wulf and McKee named the consequence the memory wall in 1995: many programs’ time is dictated by memory access rather than computation. Hardware responds with a hierarchy of small, fast memories close to the core, and software performance depends on using it.

This lesson gives you models to reason about that with numbers:

  • The memory hierarchy and its orders of magnitude, measured on your own machine.
  • Cache lines and locality, explaining the factor of fourteen above, and array memory layout.
  • Tiling, the technique that turns memory-bound matrix multiplication into compute-bound multiplication, with the traffic lower bound showing how much can be gained.
  • Arithmetic intensity and the roofline model, which use two machine numbers to predict whether a kernel is memory-bound or compute-bound. This tool analyzes why LLM text generation is memory-bound and why FlashAttention exists.
  • Microbenchmarks measuring those two numbers: pointer chasing for latency and STREAM for bandwidth.

The memory hierarchy

A processor reads from a chain of memories that become larger, slower and cheaper per byte. Each level holds copies of some data from the next, and a read is served from the closest level containing the data.

Your CPU’s levels, according to the lab’s topology cell and documented i9-14900HX architecture (8 performance P-cores and 16 efficiency E-cores, with 32 threads):

LevelSizeShared byMeasured latency (pointer chasing)
Registers16 256-bit vector registers per thread (AVX2)one thread1 cycle or less
Data L148 KiB per P-core, 32 KiB per E-coreone coreabout 2 ns
L22 MiB per P-core, 4 MiB per group of 4 E-coresone core or group4 to 6 ns
L336 MiBwhole chipabout 19 ns with 4 MiB; noisy beyond
DRAM32 GiB DDR5-5600, two channelswhole system110 to 140 ns

The sizes match Windows’ listing: 384 KiB of data L1 summed over P-cores (8×488 \times 48), 512 KiB over E-cores (16×3216 \times 32), and 32 MiB total L2 (8×2+4×48 \times 2 + 4 \times 4). Theoretical DRAM bandwidth is transfers per second times bytes per transfer times channels: 5.6×109⋅8 B⋅2=89.65.6 \times 10^9 \cdot 8\ \text{B} \cdot 2 = 89.6 GB/s. You will see STREAM reaches a fraction of that.

InteractiveThe latency ladder
100 ps1 ns10 ns100 ns1 µs10 µs100 µs1 ms10 ms100 ms1 sRegister (1 cycle)1.00 sL1 cache10.3 sL2 cache18.5 sL3 cache1.55 minMain memory (DRAM)11.3 minSSD: random 4 KiB read8.68 daysNetwork: data-center round trip28.9 daysHard disk: one seek1.59 yearsNetwork: California to the Netherlands and back23.8 years
  • measured with pointer chasing (reference run or your values)
  • one clock cycle
  • classic Dean and Norvig figure (circa 2012)
  • classic figure for that cache level
From an L1 hit to a trip to DRAM is a factor of 66: on a human scale, from 10.3 s to 11.3 min. A random SSD read would take 8.68 days.
5.0 GHz
Your measured latencies (ns)
2.05 ns
3.70 ns
18.6 ns
136.1 ns
LevelMain memory (DRAM)
Latency136 ns
Cycles at 5.0 GHz680
If a cycle lasted 1 s11.3 min
Times L1 latency66
Each bar is a level's latency on a logarithmic scale from 100 ps to 1 s. Blue bars are pointer-chasing measurements from the lab's reference run (move the sliders to enter yours) and gray bars the classic numbers popularized by Jeff Dean and Peter Norvig around 2012; the circle marks the classic figure for the same cache level. Enable human scale: if one cycle lasted a second, how long would the core wait for DRAM? And for an SSD?

The ladder teaches the hierarchy’s shape rather than a particular number. Between L1 and DRAM are almost two orders of magnitude; between DRAM and an SSD, another three; between SSD and an intercontinental network, another three. At 5 GHz, DRAM’s 100 to 140 ns are 500 to 700 cycles: if a cycle lasted one second, each miss to main memory would mean eight to twelve minutes waiting. That is why a modern core does everything to avoid waiting: it executes out of order, keeps many misses in flight and predicts what data you will request.

Latency versus bandwidth, and Little’s law

Latency and bandwidth are different, related by Little’s law: in a stable system, the average number of requests in flight is arrival rate times the time each spends in the system. For memory, if each request brings a 64 B line and takes tt to serve, sustaining bandwidth BB requires

N=B⋅t64 BN = \frac{B \cdot t}{64\ \text{B}}

lines in flight at once. With the lab’s numbers, a single thread moving about 8 GB/s from DRAM at about 120 ns latency keeps 8⋅109⋅1.2⋅10−7/64≈158 \cdot 10^{9} \cdot 1.2 \cdot 10^{-7} / 64 \approx 15 lines in flight. The whole chip’s 54 GB/s requires about a hundred: one thread cannot, which is why STREAM uses all cores. Latency measures one journey; bandwidth measures how many fit at once.

Average access time

If fraction h1h_1 of accesses hits L1 at cost t1t_1 and the rest also pay the penalty of going to the next level, average memory access time (AMAT) is recursive:

AMAT=t1+(1−h1)(t2+(1−h2)(t3+(1−h3) tDRAM)),\text{AMAT} = t_1 + (1 - h_1)\big(t_2 + (1 - h_2)(t_3 + (1 - h_3)\,t_{\text{DRAM}})\big),

with hih_i the local hit rate at each level. With t1=2t_1 = 2 ns and tDRAM=130t_{\text{DRAM}} = 130 ns, 99% L1 hits with misses going directly to DRAM give 2+0.01⋅130=3.32 + 0.01 \cdot 130 = 3.3 ns per access; 90% gives 1515 ns. Lowering the hit rate nine points multiplies average time by more than four without changing any operation.

Cache lines and locality

A cache does not store individual bytes: it stores lines (aligned 64 B blocks on all current x86 and ARM CPUs). When reading an float64 not in cache, hardware fetches the 64 B line containing it, that number and its seven neighbors.

Addresses thus split into three fields: the low log⁡2L\log_2 L bits are the offset within the line, the next log⁡2S\log_2 S select the set and the remainder (tag) identifies the line within the set. An i9 P-core’s data L1 has 48 KiB and 12 ways: 48⋅1024/(64⋅12)=6448 \cdot 1024 / (64 \cdot 12) = 64 sets. Two addresses differing by a multiple of 64⋅64=409664 \cdot 64 = 4096 B fall in the same set, with consequences.

Cache exploits two program regularities:

Cores also have prefetchers: circuits detecting access patterns (sequential, constant stride) and requesting subsequent lines before the program needs them, overlapping latency with computation. They work with regular traversal within a memory page; they cannot predict random accesses. Finally, x86 caches are write-back with write-allocate: writing a line not in cache requires fetching it first, modifying it in cache and writing it back on eviction. A “normal” write of a line not read therefore costs twice the traffic of a read, relevant when measuring bandwidth.

Why a cache misses: the three Cs

Hill proposed classifying misses into three types in 1987 (the classification used by Hennessy and Patterson in appendix B):

  • Compulsory: the first access to a line always misses. They can only be reduced with larger lines or prefetching.
  • Capacity: the line was cached but evicted because the simultaneously used data set does not fit. By definition these also miss in a fully associative LRU cache of the same size.
  • Conflict: the line was evicted despite room in the cache because too many active lines map to the same set. They disappear when associativity increases.
InteractiveCache simulator
0011223344556677Cache: 1 set × 4 waysset 0f4 c4-7f5 c4-7f6 c4-7f7 c4-7Usage order: least to most recent.evicted: f3 c4-7
access 64 / 64
  • hit
  • compulsory miss
  • capacity miss
  • conflict miss
  • line in cache
Access to cell (7, 7), in line “f7 c4-7”: capacity miss. The line is loaded and evicts “f3 c4-7”, the least recently used in its set.
Traversal
Cache capacity
Associativity
Accesses64
Hit rate0 %
Compulsory misses16
Capacity misses48
Conflict misses0
Final rate: rows · columns · tiles75 % · 0 % · 75 %
An 8 × 8 row-major matrix with 4-element lines (each row is two outlined lines), and an LRU cache. Start with the worst case: column traversal with 4 cache lines, where every access misses. Play it and watch lines load and evict; then switch to rows. Try 8 lines with 2 ways by columns: there is plenty of room and everything still misses. What kind of miss is this? In “Custom” mode, click cells to invent your traversal.

The simulator makes the factor-of-eleven mechanism explicit. By rows, each line is fetched once and serves four accesses: 16 compulsory misses and 48 hits, 75%, whatever the cache, because a used line is not needed again. By columns, between access (r,c)(r, c) and the next using its line, (r,c+1)(r, c + 1), the other seven column lines are touched; if the cache cannot retain all eight, each is evicted before reuse and the hit rate is zero. With 8 fully associative lines they fit and the rate returns to 75%. With 8 lines and 2 ways, everything misses again, and the counter identifies conflict misses; in the exercises you will explain a similar case.

In the real 4096×40964096 \times 4096 matrix the mechanism is the same at another scale, with two aggravating factors. One column touches 4096 distinct lines separated by 32 KiB, a multiple of 4 KiB: in 64-set L1 they all map to the same set, and in L2 to very few, so none survives in those levels until the next column and each element is served no sooner than L3. Also each access falls on a different 4 KiB page, and 4096 pages per column overflow the TLB, the cache holding virtual-to-physical address translations. By rows, the prefetcher brings each line before it is requested and each line serves eight successive additions.

Memory layout: rows, columns and strides

Memory is one-dimensional. An array of n0×n1n_0 \times n_1 is stored linearly, and convention decides the order.

Traversing an array in storage order (the smallest-stride index in the inner loop) gives contiguous access; the other order accesses with strides of n1sn_1 s bytes. NumPy strides need not be those of a contiguous array: stepped slicing, transposition or taking a diagonal creates views reinterpreting the same buffer with different strides, without copying.

[ ]Strides, views and contiguityBrowser
import numpy as np

A = np.arange(12, dtype=np.float64).reshape(3, 4).copy() # orden C (por filas), dueño de su buffer
F = np.asfortranarray(A)                                 # mismos valores, orden Fortran (por columnas)
vistas = {"A (C)": A, "F (Fortran)": F, "A.T": A.T, "A[:, ::2]": A[:, ::2], "A[1]": A[1]}
print(f"{'array':12s} {'forma':8s} {'strides (B)':12s} {'C-contig':9s} {'F-contig':9s} comparte memoria con A")
for nombre, M in vistas.items():
    print(f"{nombre:12s} {str(M.shape):8s} {str(M.strides):12s} {str(M.flags['C_CONTIGUOUS']):9s} "
          f"{str(M.flags['F_CONTIGUOUS']):9s} {np.shares_memory(M, A)}")

def desplazamiento(M, *idx):
    """Bytes desde el comienzo del buffer hasta M[idx]: producto escalar del índice con los strides."""
    return sum(i * s for i, s in zip(idx, M.strides))

print("\nA[1, 2] está en el byte", desplazamiento(A, 1, 2), "de su buffer;  F[1, 2], en el byte", desplazamiento(F, 1, 2))
print("orden en memoria de A:", A.ravel(order="K"))
print("orden en memoria de F:", F.ravel(order="K"))
T = A.T
print("\nA.T es una vista: ¿mismo buffer?", T.base is A, "  strides", T.strides)
Tc = np.ascontiguousarray(T)
print("np.ascontiguousarray(A.T) copia:", Tc.base is None, "  strides", Tc.strides)

Notice three things in the output. A.T has strides (8, 32): it is the same memory read by columns, so it is contiguous in Fortran order and shares the buffer with A; transposing is free, but traversing A.T by rows afterward traverses A by columns. A[:, ::2] is contiguous in neither order. And np.ascontiguousarray does copy, paying for the strided traversal once so later ones are contiguous.

Is spatial locality noticeable even in Pyodide, the Python compiled to WebAssembly that runs cells in your browser? Sum the same number of elements two ways: consecutively, or taking one in every 16 (one every 128 B, so each element is in a different line).

[ ]Spatial locality inside PyodideBrowser
import time
import numpy as np

x = np.ones(2**23)                     # 64 MiB: no cabe en ninguna caché
m = x.size // 16
contiguo = x[:m]                       # m elementos seguidos: m/8 líneas de 64 B
salteado = x[::16]                     # m elementos a 128 B de distancia: m líneas distintas

def mejor_de(f, rep=7):
    ts = []
    for _ in range(rep):
        t0 = time.perf_counter(); f(); ts.append(time.perf_counter() - t0)
    return min(ts)

t_c = mejor_de(lambda: contiguo.sum())
t_s = mejor_de(lambda: salteado.sum())
print(f"suma de {m} elementos contiguos:            {t_c*1e3:6.2f} ms")
print(f"suma de {m} elementos a saltos de 128 B:    {t_s*1e3:6.2f} ms   ({t_s / t_c:.1f} veces más)")

In this lesson’s test runs, strided summation took 8 to 12 times longer with the same number of elements and additions: each element fetches its own line and the other seven numbers are wasted. The exact ratio depends on your machine and browser; the order of magnitude does not.

Tiling: matrix multiplication without drowning in traffic

Matrix multiplication is where loop order and reuse change time most, and theory says exactly how much can be gained. Consider C=AB\mat{C} = \mat{A}\mat{B} with row-major matrices n×nn \times n, 2n32n^3 flops, and three orders of the triple loop cij+=aikbkjc_{ij} \mathrel{+}= a_{ik} b_{kj}:

  • ijk (naive): the inner loop over kk traverses a row of A\mat{A} (contiguous) and a column of B\mat{B} (with strides of 8n8n bytes). If cache cannot retain the nn lines of that column until the next jj iteration, every access to B\mat{B} misses: on the order of n3n^3 lines.
  • ikj (reordered): with aika_{ik} fixed, the inner loop over jj traverses a row of B\mat{B} and a row of C\mat{C}, both contiguous. Each fetched line serves eight accesses: on the order of 2n3/82n^3/8 lines if rows are not reused between iterations. The same computation by exchanging two loops.
  • Blocked: split each matrix into b×bb \times b blocks and multiply block by block, choosing bb so three blocks fit in cache at once.

How much traffic does it save? Count in 8-byte words between slow memory and a fast memory of MM words, under an ideal model: you manage fast memory and there are no conflicts.

Proof

For each of the (n/b)2(n/b)^2 blocks CIJ\mat{C}_{IJ}: read it once (b2b^2 words), accumulate ∑KAIKBKJ\sum_K \mat{A}_{IK}\mat{B}_{KJ} into it by reading the n/bn/b pairs of blocks AIK\mat{A}_{IK}, BKJ\mat{B}_{KJ} (2b22b^2 words per pair), and write once (b2b^2). Since 3b2≤M3b^2 \le M, the three active blocks fit and nothing else moves. The total is (n/b)2(2b2+(n/b)⋅2b2)=2n2+2n3/b(n/b)^2\big(2b^2 + (n/b) \cdot 2b^2\big) = 2n^2 + 2n^3/b. With b=M/3b = \sqrt{M/3}, 2n3/b=23 n3/M2n^3/b = 2\sqrt{3}\,n^3/\sqrt{M}.

∎

The naive method moves on the order of n3n^3 words; tiling divides that by M\sqrt{M}. Can another order do better than n3/Mn^3/\sqrt{M}? For the classical algorithm (which computes the n3n^3 products aikbkja_{ik}b_{kj}, not Strassen), no: Hong and Kung proved it in 1981 with their red–blue pebble game, and Irony, Toledo and Tiskin gave a short geometric proof in 2004 based on the Loomis–Whitney inequality, also giving an explicit constant. We reproduce it with simple accounting, giving this constant:

The key tool is the discrete Loomis–Whitney inequality: if V⊂Z3V \subset \Z^3 is finite and Vxy,Vyz,VxzV_{xy}, V_{yz}, V_{xz} are its projections onto the three coordinate planes, then ∣V∣≤∣Vxy∣ ∣Vyz∣ ∣Vxz∣\abs{V} \le \sqrt{\abs{V_{xy}}\,\abs{V_{yz}}\,\abs{V_{xz}}}. A set of points with small shadows on all three planes cannot be large: the cube is the extreme case. The proof’s idea is geometric. Each product is a point (i,j,k)(i, j, k) in cube n×n×nn \times n \times n, and its three shadows are the entries aika_{ik}, bkjb_{kj} and cijc_{ij} it needs. In an execution segment with MM transfers only on the order of MM entries of each matrix are available, so by Loomis–Whitney only on the order of M3/2M^{3/2} products can be done; the n3n^3 require on the order of n3/M3/2n^3/M^{3/2} segments, each costing MM transfers. You will give the full proof with constants in the final guided exercise.

This proof’s constant is pessimistic: a factor of 12 separates it from tiling’s 232\sqrt{3}. Smith, Lowery, Langou and van de Geijn (2019) proved that the leading term of the tight bound is 2n3/M2n^3/\sqrt{M} and an algorithm attains it. Simple tiling with b=M/3b = \sqrt{M/3} moves 23 n3/M2\sqrt{3}\,n^3/\sqrt{M}, a factor 3≈1.7\sqrt{3} \approx 1.7 from optimal. In practice fast memory is not managed by hand (it is a cache with conflicts) and there are multiple levels: BLAS libraries block for each. Goto and van de Geijn (2008) organized multiplication around an A\mat{A} block packed in a contiguous L2 buffer, traversed by a kernel keeping a small C\mat{C} block in registers; you will study it in GEMM anatomy.

InteractiveMemory traffic in blocked matmul
ABCBytes fetched from main memory (log scale)10⁴ B10⁵ B10⁶ B10⁷ Bijk (naive)ikj (reordered)blocked
macrostep 1 / 64
  • line in cache
  • used by the current macrostep
  • compulsory minimum
  • blocked model (triangle)
Blocked: 81.8 KiB; model 16n3/b+8n216n^3/b + 8n^2 predicts 72.0 KiB if all three blocks fit without conflicts. Naive: 26.7 times the best.
Animated variant
Block size bb
Simulated cache
Associativity
Fetched so far (blocked)1.50 KiB
Total ijk2.13 MiB
Total ikj272 KiB
Blocked total (b = 8)81.8 KiB
Compulsory minimum 3n2⋅83n^2 \cdot 8 B24.0 KiB
FLOPs per byte fetched (at the end)0.78
C = AB with n = 32 in float64: three 8 KiB matrices consecutively in memory, with 64 B lines (each stripe is an 8-element line). Blue shows lines in the simulated cache; the box marks what the current macro-step uses. Bars count bytes fetched from memory by each variant on a logarithmic scale; the dashed line is the mandatory minimum of 24 KiB. Start with 4 KiB, 4 ways and blocks of 8. Compare naive with 4 ways and full associativity: why does it change so much? Find the b minimizing traffic for each cache size, and raise cache to 32 KiB.

The interactive reproduces the Python simulator’s numbers that you will write in the lab below. With 4 KiB and 4 ways, naive fetches 34952 lines, 2.1 MiB, to multiply matrices occupying 24 KiB together: almost a hundred times the minimum. But at the same fully associative capacity it fetches only 4352: the B\mat{B} column it traverses consists of 32 lines 256256 B apart, which in a 16-set cache fall into only 4 sets, so those are conflict misses. Reordered ikj eliminates the issue without blocks (4352 lines in both cases). Blocking with b=8b = 8 and full associativity fetches 1152 lines, exactly what the theorem predicts counted in lines: 2n3/(8b)+n2/8=1024+1282n^3/(8b) + n^2/8 = 1024 + 128. With b=16b = 16 the three blocks occupy 6 KiB and do not fit in 4 KiB, but ikj order within a block needs only one B\mat{B} block and two row segments at once, falling to 768 with full associativity; with 4 ways it rises to 2652. With 32 KiB everything fits: all three variants fetch the 384 compulsory lines and order no longer matters.

Lab: a Python cache simulator

Implement the simulator from scratch: a set-associative cache with LRU replacement, where each set is an OrderedDict ordered from least to most recent. All three multiplication variants call acceso with the byte address of each element they read or write.

[ ]A set-associative LRU cache simulatorBrowser
from collections import OrderedDict

class Cache:
    """Caché asociativa por conjuntos con reemplazo LRU. Las direcciones son en bytes."""
    def __init__(self, capacidad, linea=64, vias=4):
        assert capacidad % (linea * vias) == 0
        self.linea, self.vias = linea, vias
        self.nconj = capacidad // (linea * vias)
        self.conj = [OrderedDict() for _ in range(self.nconj)]   # por conjunto: bloque -> None, de menos a más reciente
        self.accesos = self.fallos = 0

    def acceso(self, dir_byte):
        bloque = dir_byte // self.linea        # número de línea de memoria
        c = self.conj[bloque % self.nconj]     # conjunto: bits bajos del número de línea
        self.accesos += 1
        if bloque in c:
            c.move_to_end(bloque)              # acierto: pasa a ser el más reciente
            return True
        self.fallos += 1
        if len(c) == self.vias:
            c.popitem(last=False)              # conjunto lleno: expulsa el menos reciente (LRU)
        c[bloque] = None
        return False

# tres matrices n x n de float64 en orden C, una detrás de otra
def direcciones(n):
    A, B, C = 0, 8 * n * n, 16 * n * n
    return (lambda i, j: A + 8 * (i * n + j), lambda i, j: B + 8 * (i * n + j), lambda i, j: C + 8 * (i * n + j))

def mm_ijk(n, cache):
    a, b, c = direcciones(n)
    for i in range(n):
        for j in range(n):
            for k in range(n):                 # C[i,j] += A[i,k] * B[k,j]: B se recorre por columnas
                cache.acceso(a(i, k)); cache.acceso(b(k, j))
            cache.acceso(c(i, j))

def mm_ikj(n, cache):
    a, b, c = direcciones(n)
    for i in range(n):
        for k in range(n):
            cache.acceso(a(i, k))
            for j in range(n):                 # C[i,:] += A[i,k] * B[k,:]: todo por filas
                cache.acceso(b(k, j)); cache.acceso(c(i, j))

def mm_bloques(n, bs, cache):
    a, b, c = direcciones(n)
    for ii in range(0, n, bs):
        for jj in range(0, n, bs):
            for kk in range(0, n, bs):         # C[ii, jj] += A[ii, kk] B[kk, jj], cada bloque en orden ikj
                for i in range(ii, min(ii + bs, n)):
                    for k in range(kk, min(kk + bs, n)):
                        cache.acceso(a(i, k))
                        for j in range(jj, min(jj + bs, n)):
                            cache.acceso(b(k, j)); cache.acceso(c(i, j))

n, cap = 32, 4096                              # tres matrices de 8 KiB y una caché de 4 KiB
print(f"n = {n}, caché de {cap} B con líneas de 64 B; cada matriz ocupa {8*n*n} B")
print(f"fallos obligatorios (cada línea una vez): {3 * 8 * n * n // 64}\n")
print(f"{'variante':14s} {'4 vías':>9s} {'totalmente asociativa':>22s}")
for nombre, f in [("ijk", lambda c: mm_ijk(n, c)), ("ikj", lambda c: mm_ikj(n, c))] + \
                 [(f"bloques b={bs}", (lambda bs: lambda c: mm_bloques(n, bs, c))(bs)) for bs in (4, 8, 16)]:
    c4, cf = Cache(cap, 64, 4), Cache(cap, 64, cap // 64)
    f(c4); f(cf)
    print(f"{nombre:14s} {c4.fallos:9d} {cf.fallos:22d}")

The table confirms what you saw in the figure and adds miss classification. The fully associative column has no conflict misses: anything beyond the 384 compulsory ones is capacity. The difference between columns is conflict misses: almost 31000 of naive’s 34952. The best block with 4 ways is b=8b = 8 (1308 misses, 3.4 times minimum); with full associativity, b=16b = 16 (768, twice minimum). Optimal block size depends on capacity, associativity and loop order inside the block, so libraries tune it per architecture. In the code exercise you will apply the same idea to transposition.

Arithmetic intensity

To decide whether a kernel is memory-bound, compare how much it computes with how much it moves.

The classical convention counts bytes read plus written, each datum once (mandatory traffic), giving an upper bound on II for any implementation. On an x86 CPU, each normal write also fetches the line first (write-allocate): writing ss bytes moves 2s2s. With ss-byte elements (s=8s = 8 in float64, 44 in float32, 22 in float16):

KernelFlopsBytes (classical)II (classical)With write-allocate
Triad ai=bi+q cia_i = b_i + q\,c_i2n2n3ns3ns2/(3s)2/(3s)2/(4s)2/(4s)
Dot product x⊤y\vb{x}\T\vb{y}2n2nexerciseexercisesame
Matrix–vector Ax\mat{A}\vb{x}2n22n^2≈n2s\approx n^2 s2/s2/ssame
5-point stencil66 per point2s2s per point3/s3/s2/s2/s
Fused softmax≈5\approx 5 per element2s2s per element≈2.5/s\approx 2.5/s≈5/(3s)\approx 5/(3s)
Matmul n×nn \times n (ideal)2n32n^3ejercicioejercicion/(2s)n/(2s)

You will calculate cells marked exercise at the end of the lesson. Some observations hidden by the table:

  • Matrix–vector only reuses the vector: each entry of A\mat{A} is used once, for one multiplication and addition. No loop order or tiling can raise its intensity above 2/s2/s, which in float64 is a quarter flop per byte. This is the kernel of an LLM’s batch-1 decoding phase.
  • The stencil vij=c0uij+c1(ui−1,j+ui+1,j+ui,j−1+ui,j+1)v_{ij} = c_0 u_{ij} + c_1(u_{i-1,j} + u_{i+1,j} + u_{i,j-1} + u_{i,j+1}) reads five values per point, but each uiju_{ij} neighbors four other points: if three rows of uu fit in cache, each value is fetched once. The table’s intensity assumes this reuse; without it each point reads five values from memory and II falls to a third (with write-allocate, to 3/73/7).
  • Softmax yi=exi−m/∑jexj−my_i = e^{x_i - m} / \sum_j e^{x_j - m} counts one comparison for the maximum, subtraction, exponential, addition and division per element (the exponential costs more than one flop in practice, but is counted as one operation). Implemented as three separate kernels (maximum, exponentials and sum, normalization), input is read three times and an intermediate written: more than twice the bytes. Fusion is the idea of online softmax and FlashAttention.
  • Matmul is the only table entry whose intensity grows with size: 2n32n^3 flops over 3n23n^2 data. But this growth materializes only if implementation reuses data, using tiling. Naive ijk matmul of 4096×40964096 \times 4096 in float64 refetches all B\mat{B} (128 MiB) from DRAM for each of 4096 rows of C\mat{C}: about 8n38n^3 bytes for 2n32n^3 flops, actual intensity one quarter flop per byte, that of matrix–vector multiplication.

The roofline model

Two machine numbers, compute peak PP (flops per second) and memory bandwidth BB (bytes per second), and one kernel number, intensity II, yield a performance bound that explains practice surprisingly well. This is the Williams, Waterman and Patterson model (2009).

Proof

In time TT the machine cannot perform more than PTPT flops, so T≥W/PT \ge W/P, or move more than BTBT bytes, so T≥Q/BT \ge Q/B. Thus T≥max⁡(W/P,Q/B)T \ge \max(W/P, Q/B), and W/T≤min⁡(P, WB/Q)=min⁡(P, IB)W/T \le \min(P,\ W B/Q) = \min(P,\ I B). The bound is reached only if the limiting resource (compute or memory) works at its maximum rate throughout while the other is completely overlapped.

∎

A kernel with I<I∗I < I^* is memory-bound: even if the CPU computed infinitely fast, data would not arrive. One with I>I∗I > I^* is compute-bound. The balance point is a machine property and has grown over the years: flops become cheaper faster than bytes. In other units (flops per word), it is what McCalpin called machine balance in the 1995 paper introducing STREAM.

InteractiveRoofline builder
1/321/81/2283212851220480.010.101101001.0 Tarithmetic intensity I (FLOPs per DRAM byte)GFLOP/sP/B = 2.6dotmatvecstenciln=32n=64n=128n=256n=512n=1024n=2048n=4096triaddotsoftmaxmatvec, stencilmatmul 32
  • memory ceiling I⋅BI \cdot B
  • compute ceiling PP
  • measured in the lab (CPU, float64)
Matmul n × n performs 2.0 FLOPs per byte, below the balance point: it is memory-bound and reaches at most 78.0% of peak compute.
Machine
Data type
Kernel
32
Peak PP164 GFLOP/s
Bandwidth BB64 GB/s
Balance point P/BP/B2.56 flops/B
Intensity of matmul (n = 32)2.0 flops/B
Ceiling for this kernel128 GFLOP/s
Minimum time max⁡(W/P, Q/B)\max(W/P,\ Q/B)512.0 ns
The memory roof (blue) and compute roof (orange), with P and B measured in the lab's reference run for CPU (np.matmul and triad with its actual traffic) and GPU (PyTorch matmul and triad). Points are table kernels placed by intensity; magenta diamonds are kernels measured on CPU. Move n in matmul and see where it crosses the balance point; switch to float32 or float16 and GPU. With “Custom” you set P and B.

Some roofline readings to internalize:

  • On the reference CPU the balance point is a few flops per byte (164 GFLOP/s divided by 64 GB/s, 2.5 flops/B, in the reference run with the machine shared with other processes; peak varies considerably between runs). Dot product, matrix–vector, stencils and softmax are all far below: memory-bound regardless of arithmetic optimization.
  • On the GPU the balance point is over ten times larger in float32 (about 30 flops/B) and even more with tensor cores in float16 (about 140). A GPU performs well only with high-intensity kernels (large matmuls, convolutions), and otherwise waits for memory. This is why kernels are fused and algorithms such as FlashAttention are designed around the GPU memory hierarchy.
  • Changing data type moves kernels: going from float32 to float16 halves bytes and doubles II. For a memory-bound kernel this doubles attainable performance even if arithmetic does not change.
  • Batch-1 LLM decoding is a sequence of matrix–vector products: each generated token reads all weights once and performs two flops per weight. With float16 weights, I=1I = 1 flop per byte, far below any GPU’s balance point: speed is set by bandwidth, not TFLOP/s. This is the inference-engine project’s decoding roofline analysis.

The roofline is a bound, not a prediction. A kernel can fall far below its roof for reasons the two-number model cannot see: it does not use SIMD (vectorization multiplies actual compute roof by 4 or 8), does not use all cores, has more actual traffic than the table, or spends time in calls and synchronization. Williams and coauthors propose drawing additional roofs below PP (without SIMD, without FMA, single core) to diagnose the cause. A kernel whose data fit in cache is not DRAM-bound: its memory roof is the corresponding cache bandwidth, much greater.

Memory microbenchmarks

The two roofline numbers and each level’s latency are measured with tiny programs designed to stress one thing. These are memory microbenchmarks: pointer chasing for latency and STREAM for bandwidth.

Pointer chasing: latency

Measuring latency requires preventing the processor from overlapping accesses and the prefetcher from predicting them. The solution is to chain them: an array sig where each position stores the next index, and a loop i = sig[i]. Each load address depends on the previous result, so the core cannot issue the next until receiving the current one, and time per iteration is the latency of the level holding the array. Three design details:

  1. One random cycle. The traversal must visit every array line before repeating, so the working set is the entire array, in random order so the prefetcher cannot predict it. Random permutation π\pi of lines linked as π0→π1→⋯→πm−1→π0\pi_0 \to \pi_1 \to \cdots \to \pi_{m-1} \to \pi_0 gives a uniform cycle among all of length mm (also constructed by Sattolo’s algorithm).
  2. One jump per line. Each node occupies its own 64 B line, so each load accesses a different line and spatial locality is not exploited.
  3. Sweep size. Repeating the measurement with working sets from 8 KiB to 256 MiB makes latency form steps where the cycle no longer fits in each level. Beyond a few megabytes address translation cost also appears: with 4 KiB pages, random traversal of hundreds of megabytes also misses in the TLB, the translation cache, and each access pays a page-table lookup. The “DRAM latency” measured this way includes that cost; with huge pages it falls.

STREAM: bandwidth

McCalpin proposed four simple vector kernels in 1995 to measure sustainable bandwidth seen by a real program, and STREAM has since remained the reference for comparing machines. According to official documentation, they count these bytes and flops per iteration:

KernelOperationBytesFlops
Copyai=bia_i = b_i160
Scaleai=q bia_i = q\,b_i161
Addai=bi+cia_i = b_i + c_i241
Triadai=bi+q cia_i = b_i + q\,c_i242

The rules: each array must occupy at least four times the sum of last-level caches (here, more than 144 MiB per array), each kernel is repeated (typically 10 times), and the best result is reported. STREAM counts bytes requested by the program without write-allocate: if a write first fetches the line, triad actually moves 32 B per iteration, not 24, and physical bandwidth is 4/3 of that reported.

Benchmarking methodology on a laptop

The tools’ benchmarking methodology applies here with pitfalls specific to a hybrid-CPU laptop:

  • Variable frequency: turbo raises frequency for a few seconds and temperature lowers it afterward. Warm up before measuring (the latency cell busy-waits half a second), repeat and inspect dispersion rather than one value.
  • Different cores: P-cores and E-cores have different caches and latencies. Pin the process to a core (psutil.Process().cpu_affinity) so the system does not migrate it mid-measurement.
  • Data in or out of cache: repeating a measurement on the same data may leave them cached the second time. To measure DRAM use working sets much larger than L3 or flush caches by traversing another large buffer between repetitions.
  • Other processes: the shared reference machine had other processes using CPU, memory and L3 simultaneously. L3 is shared by all cores and is the noisiest level.
  • Statistic: STREAM uses best time, estimating what the machine can do; the median estimates what it usually does. State which you use.

Lab 1: measuring the memory hierarchy

This lab runs on your machine (runtime=local), with NumPy and Numba. The pointer-chasing loop is compiled with Numba so the Python interpreter does not obscure what you measure: how Numba does this is the subject of JIT compilation; here it suffices that @njit turns the function into machine code. The first cell prints cache topology (from /sys on Linux and WMI on Windows) and sweeps pointer-chasing cycle size.

[ ]Topology and latencies with pointer chasingLocal GPU
import os, platform, subprocess, time
import numpy as np
from numba import njit

def topologia():
    print(platform.processor() or platform.machine(), "|", os.cpu_count(), "hilos lógicos")
    sysfs = "/sys/devices/system/cpu/cpu0/cache"
    if os.path.isdir(sysfs):                                        # Linux
        for d in sorted(x for x in os.listdir(sysfs) if x.startswith("index")):
            leer = lambda f: open(os.path.join(sysfs, d, f)).read().strip()
            print(f"  L{leer('level')} {leer('type'):12s} {leer('size'):>7s}  línea {leer('coherency_line_size')} B, "
                  f"{leer('ways_of_associativity')} vías (núcleo 0)")
    elif platform.system() == "Windows":
        ps = ("Get-CimInstance Win32_CacheMemory | ForEach-Object { '{0} {1}' -f ($_.Level - 2), $_.InstalledSize };"
              "Get-CimInstance Win32_PhysicalMemory | ForEach-Object { 'RAM {0} {1}' -f $_.Capacity, $_.ConfiguredClockSpeed }")
        out = subprocess.run(["powershell", "-NoProfile", "-Command", ps], capture_output=True, text=True).stdout
        niveles, ram = {}, []
        for linea in out.strip().splitlines():
            p = linea.split()
            if p[0] == "RAM": ram.append(f"{int(p[1]) / 2**30:.0f} GiB a {p[2]} MT/s")
            else: niveles.setdefault(f"L{p[0]}", []).append(int(p[1]))
        for k, v in sorted(niveles.items()):
            print(f"  {k}: {' + '.join(map(str, v))} KiB (suma sobre todos los núcleos)")
        print("  módulos de memoria:", ", ".join(ram))
topologia()

@njit
def perseguir(sig, pasos):
    i = 0
    for _ in range(pasos):
        i = sig[i]                       # cada carga depende de la anterior: no se pueden solapar
    return i

def ciclo_aleatorio(n_lineas, rng):
    """Un único ciclo aleatorio que visita n_lineas líneas de 64 B (un int64 útil por línea)."""
    orden = rng.permutation(n_lineas)
    sig = np.zeros(n_lineas * 8, dtype=np.int64)
    sig[orden * 8] = np.roll(orden, -1) * 8           # orden[0] -> orden[1] -> ... -> orden[-1] -> orden[0]
    return sig

try:                                                   # fija el proceso a un núcleo: sin migraciones entre P y E
    import psutil
    proc = psutil.Process(); afinidad = proc.cpu_affinity(); proc.cpu_affinity([0])
except Exception:
    proc = None
rng = np.random.default_rng(0)
perseguir(ciclo_aleatorio(64, rng), 10)                # compila
t0 = time.perf_counter()
while time.perf_counter() - t0 < 0.5: pass             # calienta el núcleo para que suba de frecuencia

latencias = {}
print("\ntamaño del ciclo   latencia por carga (mediana de 7; mín y máx)")
for kib in [8, 16, 32, 48, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 262144]:
    n_lineas = kib * 1024 // 64
    sig = ciclo_aleatorio(n_lineas, rng)
    pasos = 4_000_000 if kib <= 16384 else 1_500_000
    perseguir(sig, n_lineas)                           # una vuelta completa: el ciclo entra en las cachés que quepa
    ts = []
    for _ in range(7):
        t0 = time.perf_counter(); perseguir(sig, pasos); ts.append((time.perf_counter() - t0) / pasos * 1e9)
    latencias[kib] = float(np.median(ts))
    print(f"  {kib:>7d} KiB      {np.median(ts):7.2f} ns   ({min(ts):.2f} a {max(ts):.2f})")
if proc is not None: proc.cpu_affinity(afinidad)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Read the reference run’s steps this way: up to 48 KiB, about 2 ns (a P-core’s 48 KiB L1); 64 KiB to 2 MiB, 3.7 to 5.6 ns (2 MiB L2); at 4 MiB, 18.6 ns (L3); and from 8 MiB, 99 to 136 ns. The 36 MiB L3 ceasing to be apparent already at 8 MiB has two probable causes: L3 is shared by all cores, and on a machine with other processes the cycle loses lines long before filling it; and beyond a few megabytes each random jump also misses in TLB, so latency includes the page-table lookup. The L1-to-L2 step is clear and repeats across runs; L3 is most sensitive to load: repeat the cell with the machine free and compare.

The second cell measures spatial locality directly. It reads one of every ss elements of a 256 MiB array, clearing caches before each measurement, and divides time by elements read. Then it compares four possible matrix traversals: rows and columns in C and Fortran arrays.

[ ]Stride and traversal orderLocal GPU
import time
import numpy as np
from numba import njit

def mejor(f, rep=5):
    f()                                                    # calentamiento (y compilación)
    ts = []
    for _ in range(rep):
        t0 = time.perf_counter(); f(); ts.append(time.perf_counter() - t0)
    return min(ts), float(np.median(ts))

@njit(fastmath=True)          # fastmath permite reasociar la suma: varios acumuladores, sin esperar a cada suma
def suma(v):
    acc = 0.0
    for k in range(v.size):
        acc += v[k]
    return acc

x = np.ones(2**25)                                         # 256 MiB
basura = np.ones(2**24)                                    # 128 MiB para vaciar las cachés antes de cada medida

def en_frio(f, rep=5):
    ts = []
    for _ in range(rep):
        suma(basura)                                       # expulsa x de L1, L2 y L3 (no se cronometra)
        t0 = time.perf_counter(); f(); ts.append(time.perf_counter() - t0)
    return float(np.median(ts))

suma(x); suma(x[::2])                                      # compila las versiones contigua y a saltos
print("stride (en elementos de 8 B)   ns por elemento leído, con las cachés vacías")
for s in [1, 2, 4, 8, 16, 32, 64, 512]:
    v = x[::s]                                             # una vista: un elemento de cada s, sin copiar
    t = en_frio(lambda: suma(v))
    print(f"  {s:5d} ({8*s:5d} B)              {t / v.size * 1e9:6.2f}")
del basura
del x

@njit(fastmath=True)
def suma_filas(A):
    acc = 0.0
    for i in range(A.shape[0]):
        for j in range(A.shape[1]):
            acc += A[i, j]
    return acc

@njit(fastmath=True)
def suma_columnas(A):
    acc = 0.0
    for j in range(A.shape[1]):
        for i in range(A.shape[0]):
            acc += A[i, j]
    return acc

n = 4096
Ac = np.ones((n, n)); Af = np.asfortranarray(Ac)
print(f"\nsumar las {n*n} entradas de una matriz {n} x {n} float64 (128 MiB): mismos flops")
tiempos = {}
for nombre, A in (("C", Ac), ("Fortran", Af)):
    for orden, f in (("filas", suma_filas), ("columnas", suma_columnas)):
        _, tmed = mejor(lambda: f(A))
        tiempos[(nombre, orden)] = tmed
        print(f"  array {nombre:8s} recorrido por {orden:9s} {tmed*1e3:7.1f} ms")
print(f"cociente columnas / filas en el array C: {tiempos[('C', 'columnas')] / tiempos[('C', 'filas')]:.0f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Up to s=8s = 8 (64 B), time per element grows with stride, from 1.2 ns to 5.5 ns in the reference run: with s=1s = 1 one line serves eight elements and with s=8s = 8 each needs its own. Growth is somewhat under fivefold, not eightfold, because with regular strides the prefetcher still requests lines ahead and several travel at once. Beyond 64 B each element already occupies its own line and cost levels off between 5 and 7 ns, until 4 KiB strides put each access on a different page: the prefetcher does not cross page boundaries, each access misses in the TLB and cost jumps above 15 ns. The traversal table is the motivating experiment: in a C array, rows are contiguous and columns stride 32 KiB; in a Fortran array, the reverse. Code is the same; only whether the inner loop follows storage order changes.

Lab 2: your CPU’s roofline

The third cell runs STREAM with Numba in parallel over all threads (prange), with 256 MiB arrays, then sweeps triad working-set size on one thread to see each level’s bandwidth.

[ ]STREAM: memory bandwidthLocal GPU
import time
import numpy as np
import numba
from numba import njit, prange

def mejor(f, rep=10):
    f()
    ts = []
    for _ in range(rep):
        t0 = time.perf_counter(); f(); ts.append(time.perf_counter() - t0)
    return min(ts)

@njit(parallel=True)
def copy(a, c):
    for i in prange(a.size): c[i] = a[i]
@njit(parallel=True)
def scale(b, c, q):
    for i in prange(b.size): b[i] = q * c[i]
@njit(parallel=True)
def add(a, b, c):
    for i in prange(a.size): c[i] = a[i] + b[i]
@njit(parallel=True)
def triad(a, b, c, q):
    for i in prange(a.size): a[i] = b[i] + q * c[i]

N = 2**25                                   # 256 MiB por array: más de 4 veces los 36 MiB de L3
a, b, c = np.full(N, 1.0), np.full(N, 2.0), np.zeros(N)
print(f"N = {N}, tres arrays de {8*N/2**20:.0f} MiB, {numba.get_num_threads()} hilos")
print("kernel   bytes/elem (STREAM)   GB/s (mejor de 10)")
bw = {}
for nombre, f, nbytes in (("copy", lambda: copy(a, c), 16), ("scale", lambda: scale(b, c, 3.0), 16),
                          ("add", lambda: add(a, b, c), 24), ("triad", lambda: triad(a, b, c, 3.0), 24)):
    bw[nombre] = nbytes * N / mejor(f) / 1e9
    print(f"  {nombre:6s}  {nbytes:5d}                 {bw[nombre]:6.1f}")
print(f"triad con el tráfico real (32 B/elem, la escritura trae antes la línea): {bw['triad'] * 32 / 24:.1f} GB/s")
del a, b, c

@njit
def triad_reps(a, b, c, q, reps):           # un hilo; el bucle de repeticiones dentro de Numba
    for _ in range(reps):
        for i in range(a.size):
            a[i] = b[i] + q * c[i]

print("\ntriad en un hilo según el conjunto de trabajo (3 arrays)")
for kib in [24, 48, 96, 384, 1536, 3072, 6144, 24576, 98304, 393216]:
    m = kib * 1024 // 24
    a2, b2, c2 = np.ones(m), np.ones(m), np.ones(m)
    reps = max(2, int(4e8 // (24 * m)))
    t = mejor(lambda: triad_reps(a2, b2, c2, 3.0, reps), rep=5)
    print(f"  {kib:>7d} KiB   {24 * m * reps / t / 1e9:6.1f} GB/s")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In the reference run, the four kernels gave 32 to 43 GB/s by STREAM’s convention, and triad 40.7 GB/s, or 54.3 GB/s physical traffic counting write-allocate: 61% of theoretical 89.6 GB/s. The difference from theoretical peak is normal, not a measurement failure: DRAM loses cycles opening and closing rows and alternating reads and writes, and other processes used memory simultaneously. The single-thread sweep shows bandwidth hierarchy: 127 GB/s when all three arrays fit in L1, about 53 in L2, 22 to 44 in L3 and about 8 GB/s from DRAM. One thread cannot saturate memory, and Little’s law explains why.

The fourth cell measures practical peak with np.matmul (OpenBLAS, all cores) and places measured kernels from the intensity table on the roofline: NumPy dot product and matrix–vector, the Numba 5-point stencil, and matmul of growing size. Intensities use actual CPU traffic: stencil and matmul write, and each byte written counts twice.

[ ]Practical peak, measured kernels and rooflineLocal GPU
import time
import numpy as np
from numba import njit, prange

def mejor(f, rep=7):
    f()
    ts = []
    for _ in range(rep):
        t0 = time.perf_counter(); f(); ts.append(time.perf_counter() - t0)
    return min(ts)

pico, kernels = {}, []                      # kernels: (nombre, flops, bytes de DRAM según el modelo, segundos)
for n in (32, 64, 128, 256, 512, 1024, 2048, 4096):        # primero lo que usa OpenBLAS
    A, B = np.ones((n, n)), np.ones((n, n))
    k = max(1, 2**27 // n**3)               # repite los productos pequeños para medir algo más que el reloj
    def f():
        for _ in range(k): A @ B
    kernels.append((f"matmul {n}", 2 * n**3 * k, 32 * n * n * k, mejor(f)))   # A y B leídas, C escrita (x2)
for dt in (np.float64, np.float32):
    n = 4096
    A, B = np.ones((n, n), dtype=dt), np.ones((n, n), dtype=dt)
    pico[np.dtype(dt).name] = 2 * n**3 / mejor(lambda: A @ B, rep=5) / 1e9
    print(f"pico práctico np.matmul {np.dtype(dt).name}, n = {n}: {pico[np.dtype(dt).name]:6.0f} GFLOP/s")
del A, B
N = 2**25
a, b, c = np.ones(N), np.ones(N), np.ones(N)
kernels.insert(0, ("dot", 2 * N, 16 * N, mejor(lambda: b @ c, rep=10)))
n = 8192
M, xv = np.ones((n, n)), np.ones(n)
kernels.insert(1, ("matvec", 2 * n * n, 8 * n * n, mejor(lambda: M @ xv, rep=10)))
del M

@njit(parallel=True)                        # después, lo que usa los hilos de Numba
def triad(a, b, c, q):
    for i in prange(a.size): a[i] = b[i] + q * c[i]
B_mem = 32 * N / mejor(lambda: triad(a, b, c, 3.0)) / 1e9      # tráfico real de triad: 32 B por elemento
print(f"ancho de banda (triad, 32 B/elem): {B_mem:.0f} GB/s;  punto de equilibrio: {pico['float64'] / B_mem:.1f} flops/B\n")
del a, b, c

@njit(parallel=True, fastmath=True)
def stencil(u, v, c0, c1):
    for i in prange(1, u.shape[0] - 1):
        for j in range(1, u.shape[1] - 1):
            v[i, j] = c0 * u[i, j] + c1 * (u[i - 1, j] + u[i + 1, j] + u[i, j - 1] + u[i, j + 1])
U = np.ones((n, n)); V = np.zeros_like(U)
p = (n - 2) ** 2
kernels.insert(2, ("stencil", 6 * p, 24 * p, mejor(lambda: stencil(U, V, 0.5, 0.125))))
del U, V
print(f"{'kernel':12s} {'I (flops/B)':>11s} {'GFLOP/s':>9s} {'techo':>9s} {'% techo':>8s}")
for nombre, w, q, t in kernels:
    I = w / q
    techo = min(pico["float64"], I * B_mem)
    print(f"{nombre:12s} {I:11.3f} {w / t / 1e9:9.1f} {techo:9.1f} {100 * w / t / 1e9 / techo:7.0f}%")

import matplotlib.pyplot as plt                # el roofline con los kernels medidos encima
Is = np.logspace(-4, 10, 200, base=2)
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.loglog(Is, np.minimum(pico["float64"], Is * B_mem), "k-", lw=2, label="techo: min(P, I·B)")
for nombre, w, q, t in kernels:
    ax.loglog(w / q, w / t / 1e9, "o", label=nombre)
ax.set_xlabel("intensidad aritmética (flops por byte de DRAM)")
ax.set_ylabel("GFLOP/s")
ax.legend(fontsize=7, ncol=2)
plt.show()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

What the reference-run table says:

  • The three low-intensity kernels are near their memory roof (80 to 91%): optimizing arithmetic offers nothing; only moving fewer bytes helps, for example with a smaller type or fusion with the next kernel.
  • Small matmuls fall far below any roof, and not because of memory: with n=32n = 32 all three matrices (24 KiB) fit in L1, so the DRAM roof does not apply. Up to n=128n = 128 they reach 6 to 8% of the roof: fixed per-call cost dominates (checking arguments, preparing blocks, distributing work among threads), not amortized by 2⋅323=655362 \cdot 32^3 = 65536 flops per call. These are also the noisiest sizes across runs.
  • From n=256n = 256 matmul rises toward peak (38% of roof with n=256n = 256, 70% at 512, 99% at 4096), with variation across runs: in the reference, n=1024n = 1024 remained at 51%. Its intensity (with mandatory traffic, n/16n/16 flops/B) far exceeds the balance point, and OpenBLAS turns theoretical intensity into real reuse through multilevel tiling.

The last cell does the same on GPU, if you have CUDA, with PyTorch: triad in float32 for bandwidth and matmul in float64, float32 and float16 for peaks. On the reference machine (RTX 4060 Laptop, 8 GB GDDR6), triad gave 204 GB/s and matmul 0.2 TFLOP/s in float64, 6.1 in float32 and 28.5 in float16. The ratio above one hundred between float16 and float64 is a consumer-GPU design decision, dedicating almost all compute silicon to low precision. The balance point goes from 1 flop per byte in float64 to 30 in float32 and 140 in float16.

[ ]The GPU roofline (if CUDA is available)Local GPU
import torch

if not torch.cuda.is_available():
    print("No hay GPU con CUDA: esta celda no mide nada.")
else:
    dev = torch.device("cuda")
    print(torch.cuda.get_device_name(0))
    def mejor_gpu(f, rep=20):
        f(); torch.cuda.synchronize()
        ts = []
        for _ in range(rep):
            e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
            e0.record(); f(); e1.record(); torch.cuda.synchronize()
            ts.append(e0.elapsed_time(e1) / 1e3)
        return min(ts)
    M = 2**26                                                  # 256 MiB por array en float32
    a, b, c = (torch.ones(M, device=dev) for _ in range(3))
    bw = 12 * M / mejor_gpu(lambda: torch.add(b, c, alpha=3.0, out=a)) / 1e9
    print(f"triad float32: {bw:.0f} GB/s")
    del a, b, c
    torch.backends.cuda.matmul.allow_tf32 = False             # float32 de verdad, sin TF32
    for dt in (torch.float64, torch.float32, torch.float16):
        n = 4096 if dt != torch.float64 else 2048
        A, B = torch.ones(n, n, device=dev, dtype=dt), torch.ones(n, n, device=dev, dtype=dt)
        P = 2 * n**3 / mejor_gpu(lambda: A @ B, rep=10) / 1e9
        print(f"matmul {str(dt):14s} n = {n}: {P:8.0f} GFLOP/s   punto de equilibrio {P / bw:6.1f} flops/B")
        del A, B
    torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In tools

  • Measure from Python: time.perf_counter with warm-up and repetitions, as in the cells, or timeit; on GPU, CUDA events and torch.cuda.synchronize (seen in benchmarking methodology). np.show_config() says which BLAS your NumPy uses (official NumPy wheels use OpenBLAS), and threadpoolctl limits its threads to measure one core.
  • Inspect topology: on Linux, lscpu, lscpu --caches and /sys/devices/system/cpu/cpu0/cache/; on Windows, WMI (Win32_CacheMemory) or Sysinternals Coreinfo; on either, hwloc’s lstopo draws the core and cache tree.
  • Performance counters: cores count cache misses, TLB misses and memory bytes in hardware. On Linux, perf stat -e cache-references,cache-misses,LLC-load-misses ./programa reads them without changing the program, LIKWID (likwid-perfctr) measures flops and memory data volume per code region with them, and Intel Advisor draws rooflines from your own kernel measurements. On Windows the equivalent is Intel VTune. They let you measure traffic rather than infer it from the intensity table.
  • Real STREAM: official C and Fortran code compiled with OpenMP gives figures comparable across machines; the cell’s Numba version is a teaching reproduction.

Common mistakes

Exercises

NumericDot-product intensity
What is the arithmetic intensity of dot product x⊤y\vb{x}\T\vb{y} of two float64 vectors of large length nn, in flops per byte read from memory?
NumericIdeal matmul intensity
What is the ideal arithmetic intensity of product C=AB\mat{C} = \mat{A}\mat{B} of n×nn \times n matrices in float32 if each of A\mat{A}, B\mat{B} and C\mat{C} is read or written once, with n=4096n = 4096? Give flops per byte.
QuizColumns versus rows
You traverse a C-order NumPy array of 10000×1000010000 \times 10000 float64 values, summing entries once by rows and once by columns with a compiled loop. They perform exactly the same operations. Why is column traversal much slower?
QuizSame capacity, fewer ways
An 8×88 \times 8 row-major matrix with 4 elements per line (16 lines; row rr occupies lines 2r2r and 2r+12r + 1) is traversed by columns with an 8-line, 4-way LRU cache: 2 sets, and line ℓ\ell maps to set ℓ mod 2\ell \bmod 2. With 8 fully associative lines the hit rate is 75%. What happens with this cache?
NumericThe block that fits in L2
You want to multiply float64 matrices in b×bb \times b blocks so the three active blocks (of A\mat{A}, B\mat{B} and C\mat{C}) fit at once in a 2 MiB L2, assuming perfect cache filling. What is the largest integer bb?
NumericWhat STREAM does not count
An x86 CPU reports 45 GB/s on STREAM's triad kernel (ai=bi+q cia_i = b_i + q\,c_i, counted as 24 bytes per iteration). If each write first fetches the line into cache (write-allocate), how many GB/s actually move between DRAM and chip?
NumericLines in flight
A core can have at most 16 cache misses in flight, each a 64 B line, and DRAM latency is 100 ns. By Little's law, what maximum DRAM bandwidth can that core sustain alone, in GB/s?
NumericTokens per second with batch 1
You generate text with a 7000-million-parameter float16 model, batch 1, on a GPU with 256 GB/s bandwidth. Every token requires reading all weights once and other traffic is negligible. What is the maximum tokens per second?
QuizWhich are memory-bound?
A CPU has a float64 peak of 340 GFLOP/s and 60 GB/s DRAM bandwidth. All data are float64 and hundreds of megabytes unless stated otherwise. Which kernels are DRAM bandwidth-bound?

More than one answer may be correct.

ProofThe matmul traffic lower bound
Prove: With fast memory of MM words, every classical n×nn \times n matrix multiplication computing each of the n3n^3 products once moves at least n3/(23M)−Mn^3/(2\sqrt{3}\sqrt{M}) - M words between slow and fast memory.
0
Split execution into consecutive segments of exactly MM transfers (the last may have fewer). Use the Loomis–Whitney inequality: ∣V∣≤∣Vxy∣ ∣Vyz∣ ∣Vxz∣\abs{V} \le \sqrt{\abs{V_{xy}}\,\abs{V_{yz}}\,\abs{V_{xz}}} for every finite V⊂Z3V \subset \Z^3.

Step 1 of 4. How many distinct entries of A\mat{A} can participate in products in one segment?

CodeBlocked transpose
Naive transposition reads A\mat{A} by rows and writes B=A⊤\mat{B} = \mat{A}\T by columns, so each write touches a different line. Rewrite transponer to traverse the matrix in b×bb \times b blocks and cause, in a 4 KiB cache with 4 ways and 64 B lines, fewer than half the misses of the naive version with n=64n = 64. Record every A[i][j] read with leer_A and every B[j][i] write with escribir_B exactly once per element, and return the correct transpose for any nn (including when bb does not divide nn).
from collections import OrderedDict

class Cache:
  """Caché LRU asociativa por conjuntos (direcciones en bytes)."""
  def __init__(self, capacidad, linea=64, vias=4):
      self.linea, self.vias = linea, vias
      self.nconj = capacidad // (linea * vias)
      self.conj = [OrderedDict() for _ in range(self.nconj)]
      self.accesos = self.fallos = 0

  def acceso(self, dir_byte):
      bloque = dir_byte // self.linea
      c = self.conj[bloque % self.nconj]
      self.accesos += 1
      if bloque in c:
          c.move_to_end(bloque)
          return True
      self.fallos += 1
      if len(c) == self.vias:
          c.popitem(last=False)
      c[bloque] = None
      return False

def leer_A(cache, n, i, j):          # A en orden por filas desde el byte 0, float64
  cache.acceso(8 * (i * n + j))

def escribir_B(cache, n, i, j):      # B justo detrás de A
  cache.acceso(8 * n * n + 8 * (i * n + j))

def transponer(A, cache, b=8):
  """Devuelve B = A traspuesta (listas de listas) registrando los accesos en la caché."""
  n = len(A)
  B = [[0.0] * n for _ in range(n)]
  for i in range(n):
      for j in range(n):
          leer_A(cache, n, i, j)
          escribir_B(cache, n, j, i)
          B[j][i] = A[i][j]
  return B
Shift+Enter to run

Summary

Key idea
On modern hardware moving data costs much more than operating on it: performance is determined by the hierarchy level holding data and how often they are reused, and roofline summarizes this as a bound, min⁡(P, I⋅B)\min(P,\ I \cdot B).
  • The hierarchy goes from registers (one cycle) and L1 (a few nanoseconds) to DRAM (over a hundred) and SSD (tens or hundreds of microseconds). DRAM latency barely improves; bandwidth is sustained by many accesses in flight, by Little’s law.
  • Caches move 64 B lines and retain recently used data. Misses are compulsory, capacity or conflict; conflict misses appear with power-of-two strides.
  • Traversing an array in storage order (smallest strides inside) uses each line; strided traversal wastes it. NumPy transpose is a view: cost appears during traversal.
  • Tiling multiplies reuse: blocked matmul moves O(n3/M)\bigO(n^3/\sqrt{M}) words, and Hong and Kung’s bound says classical multiplication cannot move less up to a constant.
  • Arithmetic intensity I=W/QI = W/Q compared with machine balance point P/BP/B says whether a kernel is memory- or compute-bound. Dot product, matrix–vector, stencils, softmax and LLM decoding are memory-bound; large matmul is compute-bound.
  • The two numbers are measured with pointer chasing (latency) and STREAM (bandwidth), with warm-up, repetitions, out-of-cache data and a stated statistic.

In the next lesson, vectorization in depth, you will raise the compute roof with SIMD, measure NumPy expression traffic and open up a high-performance GEMM. False sharing, parallelism fighting over one cache line, appears in the CPU parallelism lesson, and GPU shared-memory tiling is the same tiling one level lower. Later, roofline analyzes LLM training and inference: memory-bound decoding motivates techniques such as prefill–decode disaggregation, and FlashAttention is designed around the memory hierarchy.