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 float64 numbers (128 MiB) and sum all its entries twice: first row by row, then column by column. Both loops perform exactly the same 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):
| Level | Size | Shared by | Measured latency (pointer chasing) |
|---|---|---|---|
| Registers | 16 256-bit vector registers per thread (AVX2) | one thread | 1 cycle or less |
| Data L1 | 48 KiB per P-core, 32 KiB per E-core | one core | about 2 ns |
| L2 | 2 MiB per P-core, 4 MiB per group of 4 E-cores | one core or group | 4 to 6 ns |
| L3 | 36 MiB | whole chip | about 19 ns with 4 MiB; noisy beyond |
| DRAM | 32 GiB DDR5-5600, two channels | whole system | 110 to 140 ns |
The sizes match Windows’ listing: 384 KiB of data L1 summed over P-cores (), 512 KiB over E-cores (), and 32 MiB total L2 (). Theoretical DRAM bandwidth is transfers per second times bytes per transfer times channels: GB/s. You will see STREAM reaches a fraction of that.
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 to serve, sustaining bandwidth requires
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 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 of accesses hits L1 at cost and the rest also pay the penalty of going to the next level, average memory access time (AMAT) is recursive:
with the local hit rate at each level. With ns and ns, 99% L1 hits with misses going directly to DRAM give ns per access; 90% gives 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 bits are the offset within the line, the next 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: sets. Two addresses differing by a multiple of 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.
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 and the next using its line, , 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 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 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 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.
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).
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 with row-major matrices , flops, and three orders of the triple loop :
- ijk (naive): the inner loop over traverses a row of (contiguous) and a column of (with strides of bytes). If cache cannot retain the lines of that column until the next iteration, every access to misses: on the order of lines.
- ikj (reordered): with fixed, the inner loop over traverses a row of and a row of , both contiguous. Each fetched line serves eight accesses: on the order of lines if rows are not reused between iterations. The same computation by exchanging two loops.
- Blocked: split each matrix into blocks and multiply block by block, choosing 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 words, under an ideal model: you manage fast memory and there are no conflicts.
Proof
For each of the blocks : read it once ( words), accumulate into it by reading the pairs of blocks , ( words per pair), and write once (). Since , the three active blocks fit and nothing else moves. The total is . With , .
∎The naive method moves on the order of words; tiling divides that by . Can another order do better than ? For the classical algorithm (which computes the products , 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 is finite and are its projections onto the three coordinate planes, then . 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 in cube , and its three shadows are the entries , and it needs. In an execution segment with transfers only on the order of entries of each matrix are available, so by Loomis–Whitney only on the order of products can be done; the require on the order of segments, each costing 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 . Smith, Lowery, Langou and van de Geijn (2019) proved that the leading term of the tight bound is and an algorithm attains it. Simple tiling with moves , a factor 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 block packed in a contiguous L2 buffer, traversed by a kernel keeping a small block in registers; you will study it in GEMM anatomy.
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 column it traverses consists of 32 lines 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 and full associativity fetches 1152 lines, exactly what the theorem predicts counted in lines: . With the three blocks occupy 6 KiB and do not fit in 4 KiB, but ikj order within a block needs only one 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.
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 (1308 misses, 3.4 times minimum); with full associativity, (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 for any implementation. On an x86 CPU, each normal write also fetches the line first (write-allocate): writing bytes moves . With -byte elements ( in float64, in float32, in float16):
| Kernel | Flops | Bytes (classical) | (classical) | With write-allocate |
|---|---|---|---|---|
| Triad | ||||
| Dot product | exercise | exercise | same | |
| Matrix–vector | same | |||
| 5-point stencil | per point | per point | ||
| Fused softmax | per element | per element | ||
| Matmul (ideal) | ejercicio | ejercicio |
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 is used once, for one multiplication and addition. No loop order or tiling can raise its intensity above , which in
float64is a quarter flop per byte. This is the kernel of an LLM’s batch-1 decoding phase. - The stencil reads five values per point, but each neighbors four other points: if three rows of 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 falls to a third (with write-allocate, to ).
- Softmax 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: flops over data. But this growth materializes only if implementation reuses data, using tiling. Naive ijk matmul of in
float64refetches all (128 MiB) from DRAM for each of 4096 rows of : about bytes for flops, actual intensity one quarter flop per byte, that of matrix–vector multiplication.
The roofline model
Two machine numbers, compute peak (flops per second) and memory bandwidth (bytes per second), and one kernel number, intensity , yield a performance bound that explains practice surprisingly well. This is the Williams, Waterman and Patterson model (2009).
Proof
In time the machine cannot perform more than flops, so , or move more than bytes, so . Thus , and . 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 is memory-bound: even if the CPU computed infinitely fast, data would not arrive. One with 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.
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 infloat16(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
float32tofloat16halves bytes and doubles . 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
float16weights, 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 (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:
- 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 of lines linked as gives a uniform cycle among all of length (also constructed by Sattolo’s algorithm).
- 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.
- 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:
| Kernel | Operation | Bytes | Flops |
|---|---|---|---|
| Copy | 16 | 0 | |
| Scale | 16 | 1 | |
| Add | 24 | 1 | |
| Triad | 24 | 2 |
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.
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)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 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.
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}")npm run lab and open the connection link.Up to (64 B), time per element grows with stride, from 1.2 ns to 5.5 ns in the reference run: with one line serves eight elements and with 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.
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")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.
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()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 all three matrices (24 KiB) fit in L1, so the DRAM roof does not apply. Up to they reach 6 to 8% of the roof: fixed per-call cost dominates (checking arguments, preparing blocks, distributing work among threads), not amortized by flops per call. These are also the noisiest sizes across runs.
- From matmul rises toward peak (38% of roof with , 70% at 512, 99% at 4096), with variation across runs: in the reference, remained at 51%. Its intensity (with mandatory traffic, 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.
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()npm run lab and open the connection link.In tools
- Measure from Python:
time.perf_counterwith warm-up and repetitions, as in the cells, ortimeit; on GPU, CUDA events andtorch.cuda.synchronize(seen in benchmarking methodology).np.show_config()says which BLAS your NumPy uses (official NumPy wheels use OpenBLAS), andthreadpoolctllimits its threads to measure one core. - Inspect topology: on Linux,
lscpu,lscpu --cachesand/sys/devices/system/cpu/cpu0/cache/; on Windows, WMI (Win32_CacheMemory) or Sysinternals Coreinfo; on either, hwloc’slstopodraws 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 ./programareads 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
float64 vectors of large length , in flops per byte read from memory?float32 if each of , and is read or written once, with ? Give flops per byte.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?float64 matrices in blocks so the three active blocks (of , and ) fit at once in a 2 MiB L2, assuming perfect cache filling. What is the largest integer ?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?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.
Step 1 of 4. How many distinct entries of can participate in products in one segment?
transponer to traverse the matrix in 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 . 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 (including when does not divide ).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 BSummary
- 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 words, and Hong and Kung’s bound says classical multiplication cannot move less up to a constant.
- Arithmetic intensity compared with machine balance point 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.