CComputer Science, Built

Act II · Making It Fast

Part 9 of 61

The Memory Hierarchy

Degreestarts at this level43 min of film17 chaptersprerequisites: Part 6, Part 7, Part 8

If memory is hundreds of times slower than the processor, why are programs not hundreds of times slower?

The part opens on a scale: if one processor cycle took a second, the pointer-chase times measured on this machine would stretch from seconds to minutes. Wulf and McKee's memory wall says why that matters, and locality says why it is survivable: the Job's address trace revisits a few lines again and again. A direct-mapped cache is built from an address's tag, index and offset, then given associativity and a replacement policy; misses are sorted into three kinds, and the average access time is nested across levels. The host's latency staircase and bandwidth are measured, and loop order, tiling and data layout are timed. The part turns from tuning to theory: cache-oblivious recursion needs no cache parameters, and Hong and Kung's red-blue pebble game bounds how much data a classical matrix multiply must move, a scale of n cubed over the square root of M that tiling approaches. External memory, B-trees, prefetching and the inside of a DRAM chip follow. The Job's table scans miss about 88% of the time in a 32 KiB LRU cache, yet the ledger row barely moves under the model's free prefetching, and the frontier asks how close a learned replacement policy can come to Belady's MIN.

What you need. Programming, powers of two and logarithms. The pebble-game bound is given as a proof idea.

Mathematics, ideas and history
locality, caches, the 3C model, AMAT, cache-oblivious algorithms, the red–blue pebble game, external memory
What we build or compute
a cache simulator; this machine's latency staircase

What you will be able to do

Degree

  • Split an address into tag, index and offset for a given cache, and trace hits and misses in a small direct-mapped or set-associative cache.
  • Compute an average memory access time across two levels, stating what the miss penalty includes.
  • Reorder a loop nest or change a data layout so that the innermost loop walks memory in order.

Graduate

  • Compute reuse (stack) distances for a trace, and read the miss ratio of every LRU capacity from them.
  • Classify misses against a fully associative LRU reference, and explain why the conflict count can come out negative.
  • Play the red-blue pebble game on a small graph, and state the movement bound for classical matrix multiplication with its assumptions.

Research

  • State the ideal-cache and external-memory models, and say which assumptions (tall cache, optimal replacement, no recomputation) each bound depends on.
  • Compare an online replacement policy with Belady's MIN under matching capacity, start state and insertion rules, on held-out traces.

Industry

  • Measure a machine's dependent-load latency and its sequential throughput, and say what a bend in the staircase does and does not prove.
  • Decide when prefetch hints, huge pages or a structure-of-arrays layout are worth trying, and verify the effect on a representative workload.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 21 min · Graduate 41 min · Research 43 min · Industry 28 min.

  1. 0A second for every cycleDegree2 min
  2. 1The memory wallDegree2 min
  3. 2LocalityDegree2 min
  4. 3A direct-mapped cacheDegree3 min
  5. 4Associativity and replacementDegree4 min
  6. 5Three kinds of missGraduate2 min
  7. 6Average memory access timeDegree2 min
  8. 7This machine's staircaseIndustry3 min
  9. 8Programming for cachesDegree3 min
  10. 9Cache-oblivious algorithmsGraduate2 min
  11. 10The red-blue pebble gameGraduate3 min
  12. 11External memory and B-treesGraduate2 min
  13. 12PrefetchingIndustry2 min
  14. 13Inside DRAMIndustry2 min
  15. 14The Job meets memoryGraduate3 min
  16. 15Frontier: learning to replaceResearch2 min
  17. Recap, problems, and where this comes backAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

A second for every cycleDegree2 min

Start with the measured pointer-chase times on this host. To make them tangible, scale them using a two-point-eight-gigahertz reference clock. Small working sets usually find nearby cache storage. Larger sets expose further changes in effective access time. The largest random walks can include cache misses, address translation and other system effects. Their timing alone cannot separate those causes. The storage-device rows are rough access-latency examples, not measurements from this host. Read the labels and units before comparing the scaled times.

The corpus model gives an apparent puzzle. Its abstract word table grows to nearly fifty-eight thousand entries, about six hundred seventy-eight kibibytes. Prefix scans over the recorded corpus imply about two point eight billion table-line visits. A cold, fully associative thirty-two-kibibyte LRU cache misses about eighty-eight percent of these table-only visits. This excludes interleaved letters and writes. A separate fitted cost projection combines sampled cache events with short core benchmarks. Its small displayed slowdown depends strongly on idealized prefetching and the chosen clock. It is not a full-corpus execution through a realistic hardware memory system. We will build each model and see what it can establish.

Here is the route through the part. Build address fields, sets, ways and replacement decisions. Compare miss classifications under explicit reference models. Measure dependent-load time and sequential throughput, while keeping system attribution separate from observation. Then use the red-blue pebble game to reason about data movement for a specified classical matrix-multiplication computation. Fast multiplication algorithms and different graph rules need different bounds. Finally, combine corpus counts, sampled events and simplified core experiments into a conditional ledger projection.

1The memory wallDegree2 min

These curves illustrate a historical divergence. Processor performance improved rapidly in the selected era, with changes in clocks, parallel execution and other design choices. DRAM access latency improved more slowly. The red curve represents improvement in latency, so rising means shorter access time, not increasing delay. Compounding different rates creates a widening ratio. The precise gap depends on the interval, workload and definitions. Wulf and McKee's 1995 memory-wall argument explains why memory stalls can consume an increasing share of execution.

Nanoseconds become core cycles only after a clock is specified. The displayed small-set and large-set times come from this host's dependent random walks. They are effective access times, not isolated SRAM-cell and DRAM-chip timings. Multiply nanoseconds by the assumed Pebble frequency to obtain its cycle budget. The hierarchy model assigns capacities and uses selected timing points as calibration proxies. A faster illustrative reference clock turns the same nanoseconds into more cycles. Caches and overlap can reduce exposed waiting, but dependencies, throughput and memory-system limits determine how much. A single latency ratio does not predict program speedup.

A hierarchy trades capacity, access time, bandwidth, energy and cost. Registers sit near execution units; caches commonly use SRAM. Six-transistor cells are a familiar SRAM example, not a universal implementation rule. DRAM commonly uses a transistor and capacitor per cell; flash and magnetic storage offer other capacity and persistence tradeoffs. Package placement, stacked memory, controllers and interfaces affect performance. Retail prices change with date, capacity and product class. The goal is to keep useful data close enough for the workload. Neither a fixed cost ratio between layers nor a single pyramid describes every computer.

2LocalityDegree2 min

The plot samples the Job's chapter-1 data-access trace. Horizontal position is instruction count, and vertical position is byte address. Device reads and instruction fetches are excluded. The table scans produce repeated rising strokes as entries are visited. The lower region holds letters, revisited during comparisons and written when new words are copied. The legend states the sampling stride. Spatial locality means nearby addresses are used near each other in time; temporal locality means previously accessed data is reused. Denning's working-set model concerns pages used within a recent reference window. Working sets can change abruptly, and locality is a workload property to measure.

For a repeated line, count distinct other cache lines accessed since its previous reference. This is reuse distance, also called LRU stack distance. First touches are classified separately. The histogram shows the distribution on this chapter's trace, under its stated line size. Repeated accesses to the same line have distance zero. Starting empty, a fully associative LRU cache holding C lines hits exactly repeated references with distance less than C. This property gives miss ratios at many capacities from one distance trace. It does not directly describe set mapping, alternative replacement, prefetching or coherence invalidations.

These two curves describe different reference streams. Chapter 1's full data trace touches ninety-two distinct lines. With a large enough fully associative LRU cache, only its first touches miss. The corpus curve instead models table-only prefix-line visits and omits interleaved pool accesses and writes. Its larger abstract table keeps the miss ratio high at small capacities. The compared event definitions must stay visible. A sharp drop can indicate that a useful working set fits. Other workloads can show several drops, gradual changes or no single cliff, and capacity alone does not determine application runtime.

3A direct-mapped cacheDegree3 min

The first caches appeared in the 1960s; Maurice Wilkes described the idea in 1965 as a slave memory, and IBM's System/360 Model 85 shipped one in 1968. The simplest design is direct-mapped: every address has exactly one place in the cache it can go. Take a sixteen-kilobyte cache of two hundred fifty-six lines, each sixty-four bytes. An address is cut into three fields. The lowest six bits are the offset: which byte within the sixty-four-byte line. The next eight bits are the index: which of the two hundred fifty-six lines of the cache this address must live in. The rest is the tag. Many addresses share an index, so the cache stores the tag beside each line, and on every access compares it: same tag, a hit; different tag or an empty line, a miss.

A direct-mapped lookup combines an indexed data array with metadata checks. The index selects one row containing data, a tag and a valid bit. Real implementations may also have protection and coherence state. Compare the stored and requested tags, and require the row to be valid before declaring a hit. The byte offset selects the requested portion of the line. Array access, tag comparison, selection, wiring and address translation constrain timing. Their overlap and pipelining depend on the design; this block diagram does not derive a four-cycle L1 latency from one cycle of gates.

Here is a toy cache to watch: eight lines of sixteen bytes, and eight-bit addresses, so one bit of tag, three of index and four of offset. The first access, hex fourteen, has index one: the line is empty, a miss, and the line is filled. The second, hex eighteen, falls in the same sixteen-byte line: a hit, by spatial locality. Watch hex ninety-four. Its index is also one, but its tag is different, so it throws out the line that hex fourteen brought in, and when hex fourteen comes back, it misses again. Two busy addresses that share an index fight over one line even when the rest of the cache is empty. That is the weakness of direct mapping, and the next chapter's subject.

The chapter-1 trace also shows mapping conflicts. Its table starts at hexadecimal ten thousand and its letter pool at hexadecimal eighty thousand. Those aligned bases can select the same sets at the illustrated capacities. Which live lines actually collide depends on their offsets and access order; the base addresses alone do not prove continuous eviction. Replay the entire chapter trace through the direct-mapped eight-kibibyte cache and count the displayed misses. Two ways at the same total capacity reduce the count to ninety-two in this experiment. Increasing ways reduces the number of sets, so the complete mapping changes too. This is a trace result rather than a universal monotonic rule.

4Associativity and replacementDegree4 min

Set associativity gives a line several eligible locations. One way per set is direct mapping. Two ways allow two lines with the same set index to coexist. Put every line in one set and the cache is fully associative. More ways require additional tag checks or other lookup machinery, with design-dependent latency and energy costs. At fixed total capacity the index changes as the number of sets falls. Actual associativities vary by core and cache level, and more ways do not guarantee fewer misses under every replacement policy and mapping.

A miss to a full set requires a victim. LRU evicts the least recently referenced resident line, using past recency as a heuristic. Tree pseudo-LRU maintains a small direction tree; it approximates recency but does not reproduce exact LRU. Hardware also uses other policies. FIFO tracks insertion order; random replacement chooses a resident victim according to its random generator. Belady's MIN evicts the resident line whose next reference is farthest away. Its optimality assumes a fixed trace, capacity, initially specified state, uniform miss cost and the same forced-insertion rules. A fully associative MIN result is not a like-for-like replacement-only comparison with a set-associative cache.

A four-way set can represent approximate recency with three tree bits. Each bit points toward a subtree to consider for replacement. Touching a way updates its path to point away from that way. Follow the shown accesses to ways zero, two and one. Unvisited ways still need valid-bit and free-slot handling. Once the set is full, follow the tree to its candidate victim. It need not be the exact least recently used way. An arbitrary exact order of sixteen ways has sixteen factorial possibilities, requiring at least forty-five bits to encode; a tree uses fifteen direction bits. Real implementation state and update costs depend on the chosen encoding.

Replay the same chapter-1 data references from an empty four-kibibyte cache. The LRU, pseudo-LRU and FIFO bars use eight-way sets. The seeded random policy has fewer misses on this trace. A single seed is not a distribution-wide performance guarantee. The MIN bar has the same capacity but is fully associative, so it also removes set-placement restrictions. Repeated scans slightly longer than a cache can punish LRU: each next reference finds its line just evicted. Random replacement sometimes preserves useful lines. Performance still depends on scan lengths, intervening accesses, mapping and policy; measured miss ratios do not directly give execution-time speedups.

Stores add propagation and allocation choices. Write-through sends a store toward the next level, often through a buffer. It does not by itself make every copy or DRAM instantly current. Write-back marks a line dirty and propagates it on eviction or another required action, such as a flush or coherence request. Repeated updates can be combined while the line remains resident. Write-allocate brings a missed store's line into the cache; no-write-allocate can send the store onward instead. Partial stores and coherence ownership complicate real traffic. Our single-cache simulator counts dirty evictions and write-through events. The hierarchy's demand-latency model does not price complete write-back, coherence or bandwidth traffic.

5Three kinds of missGraduate2 min

Miss categories depend on a reference model. A first reference to a line is compulsory for an initially empty demand-only cache with this line size; prior prefetching or a different line size changes the comparison. A fully associative LRU reference of the same capacity supplies a capacity-miss baseline after first touches. Capacity is one possible remedy; locality transformations and replacement changes can also help. For an individual target-cache miss, a hit in that reference suggests a placement conflict. The numerical table uses a signed aggregate difference instead. That accounting can be negative, so it must not be presented as a partition of individual misses into three nonnegative groups.

The table compares the same chapter trace, line size and cold initial state. Ninety-two distinct lines give ninety-two first-touch events. The capacity column comes from a fully associative LRU reference, regardless of the target's number of ways. At eight kibibytes, the two-way target has only first touches, while the direct-mapped target suffers many additional misses. The displayed conflict entry is target misses minus first touches minus reference capacity misses. A negative value means the target had fewer total misses than the fully associative LRU reference. Set partitioning can protect some lines from scans; this signed difference is useful comparison accounting, not a negative number of physical miss events.

6Average memory access timeDegree2 min

Define hit time and miss penalty before calculating an average. In this serial one-level model every demand access pays the hit lookup time, and a fraction m also pays an additional miss penalty. Four cycles plus five percent of an additional two hundred cycles gives fourteen cycles. The miss-penalty contribution is ten cycles per access, compared with four cycles of lookup cost on every access. If two hundred already included the lookup, the arithmetic would need a different definition. Capacity, associativity and organization can trade miss ratio, latency, area and energy. AMAT summarizes this access model; it does not by itself predict execution time when misses overlap or bandwidth becomes limiting.

The serial formula nests across levels when lower-level miss ratios are conditional on reaching that level. The displayed timing illustration starts from cumulative pointer-chase samples, then takes nonnegative increments between them. Adding each cumulative latency again would double-count earlier lookup time. We choose the miss ratios for illustration; they are not measured typical rates for this host. The resulting weighted average can be much smaller than the largest delay when few requests reach that delay. The sample points do not isolate hardware cache levels, and this simple expectation omits overlap, queuing, prefetch costs and write traffic. Use it to reason about assumptions, then test actual workloads.

7This machine's staircaseIndustry3 min

Measure a dependent random walk through a chosen working-set size. Place one pointer in each sixty-four-byte line and link the lines into a randomly permuted cycle. Each next address comes from the previous load. The benchmark warms the cycle, repeats twenty million steps and reports the best of three timed trials. This serial dependency suppresses overlap between the measured loads, and the irregular order reduces ordinary stride-prefetch opportunities. It does not defeat every possible temporal prefetcher. Loop overhead, address translation, cache placement, virtualized scheduling and interference can still affect the result. The time per step is an effective dependent-access measurement, not an isolated component delay.

Read the host identity and the measured points together. The current data come from the processor named above the plot. Small working sets have the lowest measured delay. Increasing the footprint exposes further plateaus and transitions. A selected point is a sample at that footprint, not proof of one exact cache-level boundary. The largest walks can combine last-level misses, translation effects, system placement and interference. Timing alone does not identify their individual contributions. The lscpu strings describe reported cache totals and instances, not guaranteed private capacity available to this process. Use controlled experiments and performance events to investigate a transition's cause.

Address translation can affect a large dependent walk, so compare two allocation treatments. The first uses the default allocation; the second requests transparent huge pages with madvise. A translation-cache miss can require a page-table walk, but its entries may hit other caches; not every access necessarily walks all the way to memory. A two-mebibyte page covers five hundred twelve times the address range of a four-kibibyte page. That can increase translation reach. Our benchmark records timings and the kernel's advice mode, but does not verify actual backing-page sizes. The displayed difference therefore compares default and advised allocations, not proven small-page and huge-page populations or an isolated translation cost.

Sequential throughput measures a different workload from the dependent random walk. This C loop sums a repeatedly reused array, with several independent accumulators, and reports the best of five trials. The bars show bytes read per second at each array footprint on this host. Multiplying a compatible throughput by a compatible latency estimates required average concurrency by Little's law. These separate workloads do not directly count outstanding hardware requests or prove that a particular prefetcher caused the throughput. Latency, available parallelism and sustainable bandwidth all constrain performance; measure the workload you intend to optimize.

8Programming for cachesDegree3 min

Loop order changes the address stream even when the intended matrix product is unchanged. With row-major doubles, walking a column of B separates successive elements by a row stride. In the shown sizes that spreads accesses across lines and can create set conflicts. Interchanging the inner loops makes the innermost traversal contiguous in B and C, giving several nearby elements per sixty-four-byte line. Floating-point order, vectorization and compiler transformations still deserve attention. The miss counts below come from a small explicit address-trace simulation with its stated capacity, associativity and line size. They count allocation misses, not total physical traffic or a measured cache-only explanation of the C benchmark's speedup.

These are host-dependent timings of the shown C kernels, compiled with optimization and native instruction selection. The work estimate uses two n-cubed floating-point operations. The i-j-k kernel is measured only through size one thousand twenty-four; there is no measured point at two thousand forty-eight for that curve. The interchanged loop and the fixed-tile kernel have their own curves. Their rankings and slopes are observations from these runs, not universal size trends. Each C variant is timed once, and zero initialization is included in some variants. NumPy's BLAS result uses a separate library implementation and timing path.

Tiling tries to reuse a small set of matrix values before moving on. Three square tiles give a useful first capacity estimate, with T squared values per tile. A C tile accumulates products from matching A and B tiles. The actual loop nesting determines which tile stays resident across the reduction loop; not every tile is necessarily retained or reused T times in the same way. Three T-squared values fitting is a sufficient storage sketch for a simple blocked scheme, not a complete performance condition. Associativity, line layout, registers, vector instructions, write traffic and other data also consume resources. Under the classical multiplication model, suitable blocking reduces the leading movement scale to n cubed over T, with constants depending on the schedule.

Layout determines which fields share a line. An array of structures groups one object's fields; a structure of arrays groups corresponding fields from many objects. Neither is universally better. This loop reads only the x field. The structure has sixty-four bytes per object, while the compact float array stores x values consecutively, reducing the address footprint and unused fields brought in. The displayed best-of-five times come from the same specified summation and compiler options. Workloads that use several fields together may favor a different layout or a blocked hybrid.

9Cache-oblivious algorithmsGraduate2 min

Cache-oblivious algorithms avoid explicit cache parameters in their code. The ideal-cache model specifies a fully associative fast memory of M words, B-word transfers and optimal replacement. Analysis counts transfers under that model and stated initial/output conditions. A recursive algorithm can discover useful subproblem sizes without testing M or B directly. Bounds for specific algorithms may require a tall-cache assumption and regularity conditions. They can extend across suitably modeled memory levels, and LRU can have related guarantees with appropriate resource comparisons. None of this promises the exact fewest misses at every real cache level, where mapping, prefetching and instruction overhead matter.

The experiment transposes a row-major matrix and simulates a cold fully associative LRU cache. Each output element contributes two address references, one to the input and one to the output. The vertical axis is allocation misses per reference; it excludes dirty write-backs. The row-by-row traversal has poor output locality at small capacities. A fixed thirty-two-by-thirty-two block changes the curve, reaching the cold line-fill floor from four kibibytes in this experiment. The recursive traversal reaches that floor across all displayed capacities. One eighth here means one fill per eight references, or one quarter of a fill per output element.

A static search layout can use recursive clustering too. For a balanced binary tree, the van Emde Boas layout stores a recursively arranged top tree, followed by recursively arranged lower subtrees. Under the usual block-transfer assumptions, a root-to-leaf search uses order one plus log base B of n block transfers. The extra one handles even a tree that fits in a block. This is a layout bound, not a claim about arbitrary unbalanced trees, dynamic updates or physical search latency. A B-tree instead chooses node capacity with the block size in mind. Both approaches organize related search steps to reduce data movement, under their respective models.

10The red-blue pebble gameGraduate3 min

The pebble game asks about a specified computation graph. Hong and Kung introduced this framework in 1981. Nodes hold inputs or computed values; arrows identify required operands. Red pebbles represent values in fast memory, with a limit of M. Blue pebbles represent stored slow-memory values. A value may have both colors at once. Loading adds a red copy, storing adds a blue copy, and computing places a new red pebble when all predecessor values are red. Removing a red pebble is free; our illustration does not overwrite an input pebble during a compute move. Count loads and stores. The graph, initial/output conditions and recomputation rules are part of the problem, so changing them can change its optimum.

Compute y equals a plus b, times a plus c, under the place-new-pebble rules with four red slots. Inputs begin in slow memory and y must finish there. Load a and b, compute their sum, drop b, then load c. Computing the second sum temporarily needs four red pebbles: a, c and both sums. The occupancy counter makes that peak explicit. Drop a and c, compute y and store it. Three input loads and one output store give four transfers, the minimum possible. Independent shortest-path search confirms it. With three red slots the same graph needs six transfers, spilling and reloading a partial result. Two slots cannot execute a binary compute move under these non-overwrite rules.

Consider classical matrix multiplication with its n-cubed scalar products, distinct matrices and the stated no-recomputation model. This is not a bound on every possible multiplication algorithm. Divide a valid schedule into segments with a limited number of transfers. Values already in fast memory and values brought in constrain what one segment can use. The Loomis-Whitney argument bounds how many distinct index triples can be supported by the available A, B and partial-output values. That yields the leading movement scale n cubed over square root M. A sharper argument gives the displayed constant and lower-order term when all outputs must end in slow memory. Read-only bounds and total read-plus-write bounds have different lower-order terms; the short sketch does not derive the sharp constant by itself.

Compare classical sixty-four-by-sixty-four address traces with a total fast-data budget of one thousand twenty-four words. Eight slots are reserved for scalar operands and accumulators; the rest form a fully associative LRU cache. The displayed lower bound counts both reads and writes and requires outputs in slow memory. The untiled bars now count line fills, dirty evictions and a final dirty-line drain. Counting fills alone would understate movement. The tile sizes give the other bars; their ratios are calculated from these counters. This is a specified trace-and-cache experiment, with zero-initialization setup excluded. It illustrates how blocking can approach the movement scale. Registers, physical write protocols, vectorization, arithmetic throughput and different algorithms require additional analysis before predicting actual GPU or CPU runtime.

11External memory and B-treesGraduate2 min

The external-memory model counts block transfers between a limited fast memory and a larger slow store. It can describe more than a physical spinning disk. Memory holds M items and a transfer moves B items. Scanning requires order one plus N over B transfers, with ceilings for short inputs. The comparison-based, indivisible-record sorting bound includes a scan term and a logarithm with base M over B, under the usual memory-size assumptions. This is not a lower bound for every possible integer-sorting model. In this example M is one billion items, not one gigabyte. Ten initial runs fit into one merge round: two passes, each reading and writing the data, rather than two individual transfers per block.

External merge sort separates run generation from merging. Read an in-memory batch, sort it and write a run. Ceilings and workspace determine the actual number of initial runs. During merging, reserve input blocks and an output buffer. A simple fan-in is floor M over B minus one, with more room potentially needed for metadata and computation. Refill an input block when consumed and flush output blocks when full. Count one run-generation pass plus enough merge rounds for the number of runs and chosen fan-in. Each complete pass reads and writes the data. Whether two passes suffice depends on these quantities, not simply on memory being large in absolute terms.

B-trees organize search around blocks. Bayer and McCreight's work appeared in 1972. A node groups many ordered keys and child pointers, with a node size chosen for a page or other useful transfer unit. With maintained occupancy and fan-out on the order of B, search height is on the order of one plus log base B of N. Cached upper nodes can reduce slow-store reads, while variable-size records, updates and concurrency add design choices. B-tree relatives are common in databases and file systems, alongside hash indexes, log-structured merge trees and other structures.

12PrefetchingIndustry2 min

Prefetching tries to request useful data before a demand needs it. It can help when there is enough prediction lead time and transfer capacity. A next-line rule considers the following line; our simulator triggers it on every demand access, not only a miss. Its stride rule tracks line differences within each four-kibibyte page and immediately inserts predicted lines. That simplified model charges neither prefetch latency nor bandwidth. Software can also issue hints for addresses it can compute early. Real designs must manage accuracy, coverage, timeliness, pollution and metadata cost. The 2026 Streamline study, for example, organizes temporal-prefetch correlations as streams to use metadata storage more effectively. Our stride experiment does not reproduce that design or its evaluation.

Replay a synthetic scan on the functional core, with a table larger than its assigned L2 but still within the assigned third-level capacity. The ideal-memory bar is the core's default load model. The next bar adds immediate, uncharged stride-prefetch fills. A similar result therefore shows what these assumptions can hide, not what a finite hardware prefetch engine will always hide. The third bar disables that prefetch rule. The warm estimate subtracts a one-pass execution from a three-pass execution and divides by two passes. The cold-pass labels include initialization and startup effects; not every miss necessarily reaches DRAM. Queuing, bandwidth and prefetch traffic remain outside this model.

This host benchmark sums randomly indexed elements of a two-hundred-fifty-six-mebibyte array. The index array is available in advance, so the guarded hint can request sixteen iterations ahead without reading past its end. The displayed values are the best of three trials for each variant. Whether the hinted version is faster or slower depends on the actual run; the narration does not assume an old result. Independent accesses may already overlap, but these timings do not count outstanding misses or isolate the cause of a difference. Instruction overhead, pollution, cache state and hint timing can matter. A single dependent pointer chain usually cannot know a distant future address. Useful software lookahead needs available address information, independent work or a different algorithm; test it under representative conditions.

13Inside DRAMIndustry2 min

A DRAM bank contains arrays of cells and sense amplifiers that hold an open row. This diagram uses an eight-kibibyte row and assigned timing values. Activation senses a row's small charge differences and restores the cells while holding their values in the sense amplifiers. A read command selects columns for transfer, subject to the device and interface timings. To switch rows, the controller observes minimum active-time and other constraints, closes the row and precharges the bitlines before a new activation. Precharge itself is not simply a delayed cache-style write-back. Refresh restores charge periodically, with intervals depending on device, temperature and mode. The fourteen-nanosecond numbers and sixty-four-millisecond example are teaching choices, not universal end-to-end memory timings.

The open row makes access history matter inside DRAM. This toy model has eight banks, fixed eight-kibibyte rows and a specified address-to-bank mapping, and leaves the last row open. Sequential line addresses give the first hit fraction. A four-kibibyte stride gives the second. Seeded random addresses give the third. These are simulated row-buffer hits, not measured cache hits on the host. A row hit can avoid closing and activating a different row, but real time also depends on bank parallelism, controller scheduling, bus transfers, refresh and timing constraints.

Memory interfaces and packaging change while the basic charge-storage idea remains. A common non-ECC DDR5 DIMM has two thirty-two-bit subchannels; widths, bank organizations and error-protection overhead depend on the device and module. High-bandwidth memory stacks dies near a processor and uses a wide interface, with details varying by HBM generation and package. Many accelerators use HBM; others use different memory systems. Systems with virtual memory translate virtual addresses to physical addresses and cache translation information in TLBs. Bare-metal and other addressing modes need not perform the same translation. The measured staircase motivates a translation investigation, but does not alone prove its causes. Part 32 develops those mechanisms.

14The Job meets memoryGraduate3 min

The table-only prefix model allows exact LRU counting without expanding billions of visits. A scan touches lines zero through its end index. This is an abstract line stream, excluding letter traffic and stores. Between two references to line l, let e be the end index of the latest earlier scan that reached l. Exactly e distinct other lines intervene. A repeated reference therefore hits a fully associative C-line LRU cache if e is less than C, equivalently if that earlier covering scan had at most C lines. The cached-prefix method evaluates this model over all recorded scan ends. The green comparator pins C minus one front lines and uses one transient slot. Its achievable miss count upper-bounds MIN under matching forced-insertion rules; it is not MIN's exact miss count.

Here is a deliberately serialized waiting-budget calculation. Assign the selected large-working-set delay to every abstract table-line visit, convert it at the Pebble clock, and allow no overlap. The product is the displayed number of minutes. It is neither a measured no-cache corpus execution nor a general lower or upper bound for actual runtime: real transfer size, reuse, bandwidth, parallelism and instruction work all matter. Compare it with the fitted ledger only as an illustration of how assumptions change the apparent cost.

This projection combines four sampled corpus windows with synthetic scan and first-letter benchmarks on the functional core. The abstract corpus table and pool are relocated into disjoint regions; this is not a full execution of the unchanged Pebble memory image. The fractions describe coalesced table events and first-letter pool events in those windows. Later matching bytes, target reads and stores are omitted from that sampling model. Weight the measured model increments at the Pebble clock to obtain the displayed extra cycles. Disabling the immediate free prefetch rule gives a separate projection. Bandwidth, prefetch lead time, queuing and complete write traffic are absent, so small fitted overheads are conditional model results, not hardware guarantees.

Row three adds the modeled memory increments to Part 8's fitted corpus cycle estimate and divides by the same assumed clock. It remains a projection from counts, samples and short benchmarks, without a full-corpus run or an error bound. The abstract table-only stream still exposes a large amount of scanning work. Caching, overlap and prefetching affect the cost of that work under different assumptions; they do not change how many table entries the algorithm examines. Better data structures can reduce the work itself, which later parts investigate. Pointer-heavy programs, different clocks and finite-bandwidth memory systems require their own models and measurements. The near-equal ledger rows should motivate that investigation, not a conclusion that real memory is generally free.

15Frontier: learning to replaceResearch2 min

This experiment replays an approximate line-event stream from the first six thousand corpus words in a cold fully associative one-hundred-twenty-eight-line cache. It is not the full instruction-level memory trace. The LRU and seeded-random bars use that same stream and capacity. Bimodal insertion usually places a newly fetched line at the LRU end, promoting a fraction of new lines to the MRU end. Here that fraction is one in thirty-two in expectation, not an exact periodic schedule. Hits update recency. MIN supplies the offline comparison under the same forced-insertion miss model. A reduced gap on this stream says nothing universal about other workloads; changing locality phases, training information or available state can change the result.

Learning-based replacement policies make different predictions. Hawkeye uses OPTgen to reconstruct cache-friendly behavior from sampled historical accesses, then trains a program-counter predictor. Historical feedback is not knowledge of the future. Glider analyzes an offline attention-based LSTM and uses the insights to design a much cheaper online predictor with an unordered history of load-instruction identities. It does not simply copy a few hundred trained LSTM weights into hardware. Mockingjay's 2022 study instead predicts reuse-distance classes and orders candidates by predicted reuse time. Its empirical gains depend on the evaluated platform, workloads and prefetch conditions. These primary studies motivate mechanisms; our chapter's small BIP experiment reproduces none of their complete hardware evaluations.

Define the model before asking how close an online policy can get to MIN. Paging has established competitive bounds under explicit cache-size and adversary assumptions. Predicting which learned policy wins on a particular changing workload remains an empirical and theoretical question. Communication bounds exist for many computation graphs; tightness depends on graph structure, allowed algorithms, sparsity and recomputation rules. It is too broad to say that bounds beyond matrix multiplication are simply unknown. CXL-attached and pooled memory introduce topology, protocol, locality and scheduling tradeoffs, with no single universal extra latency. Processing near or inside memory changes where operations and data move, but adds its own precision, capacity, programming and transfer constraints. The research exercise asks for a reproducible, model-matched policy comparison.

Recap, problems, and where this comes backAll tracks3 min

We built cache lookup and replacement models, examined signed miss-accounting comparisons, and measured this host's dependent-access times and sequential throughput. Loop ordering and tiling changed data reuse, while recursive layouts illustrated cache-oblivious ideas under explicit assumptions. The red-blue pebble example now checks its fast-memory occupancy, and the classical multiplication comparison counts fills and dirty write-backs. The Job's ledger combines a relocated abstract event model with short core benchmarks. Its small projected overhead belongs to those assumptions; the billions of table-line visits are not billions of physical DRAM misses. These distinctions let us connect a visualization to a calculation without claiming more than either establishes.

These ideas return in several layers of the course. Coherence in Part 10 controls how cached copies interact across cores; it is separate from the memory-ordering model. Part 32 develops virtual addressing and translation caches. B-trees, external sorting and column-oriented layouts reappear with their own storage and update assumptions. Later Job algorithms reduce the amount of searching rather than only its per-access cost. Distributed caching adds network latency, consistency and eviction choices across machines. Accelerator design adds arithmetic intensity, local storage and transfer scheduling. At every layer, specify the event being counted, the resource limit and the observations needed to test the model.

Practical optimization starts with a representative workload and a controlled measurement. Compare useful layout variants, inspect compiler and library settings, and check correctness before attributing a speedup. Distinguish dependent latency from throughput and logical bytes processed from actual memory traffic. Roofline reasoning needs the relevant memory boundary and arithmetic intensity. Huge-page advice, NUMA placement and prefetch hints require verification under the operating system and hardware in use. Cache simulators can isolate mechanisms under chosen rules; hardware counters and repeated benchmarks help test whether those mechanisms explain a real application. Record uncertainty and setup so someone else can reproduce the result.

The exercises distinguish address arithmetic, serial access expectations, replacement policies and movement bounds. State the cache's initial state and insertion rules before comparing a cyclic scan with MIN. Keep read-only counts separate from total read-plus-write transfers, and include output-buffer space in external-memory examples. The build problem asks you to implement and evaluate insertion variants with explicit seeds and event definitions. For the research problem, use a feasible same-capacity comparator, separate training from heldout evaluation, and never encode future trace outcomes in an online predictor. A proof for a structured trace and an empirical result on a sampled workload are different deliverables.

Next, parallel machines. Power and scaling constraints slowed the earlier pace of clock-frequency growth, while multicore designs and vector units became increasingly important. Part 10 studies SIMD, shared-memory execution, coherence and GPU organization, and evaluates parallel versions of the Job under stated workloads and resource limits. The memory models from this part give us a starting point for measuring those tradeoffs.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. Cached copies on several cores become cache coherence in Part 10; address translation and the TLB are built in Part 32; B-trees and external sorting return in Parts 17 and 35; later versions of the Job cut the searching itself instead of its cost per access.

Key results

The part's results in one place, for revision.

Address fields\(\displaystyle \text{offset }\allowbreak \text{bits}=\log_2(\text{line}),\quad\allowbreak \text{index }\allowbreak \text{bits}=\log_2(\text{sets}),\quad\allowbreak \text{tag}=\text{the }\allowbreak \text{rest}\)
Stack distance (LRU)\(\displaystyle \text{hit }\allowbreak \text{in }\allowbreak \text{a } C\text{-line }\allowbreak \text{LRU }\allowbreak \text{cache}\iff 0\le d<C\)
Average access time\(\displaystyle \text{AMAT}=t_1+m_1\bigl(t_2+m_2\,t_3\bigr)\)
Matrix multiply must move\(\displaystyle \Omega\!\left(\frac{n^3}{\sqrt{M}}\right)\ \text{words }\allowbreak \text{(classical }\allowbreak \text{algorithm)}\)
External sorting\(\displaystyle \Theta\!\left(\frac{N}{B}\log_{M/B}\frac{N}{B}\right)\ \text{block }\allowbreak \text{transfers}\)
Search in blocks\(\displaystyle O\bigl(1+\log_B N\bigr)\ \text{transfers }\allowbreak \text{(B-tree, }\allowbreak \text{van }\allowbreak \text{Emde }\allowbreak \text{Boas }\allowbreak \text{layout)}\)

Try it

Lab 9 · Loop order, stack distance and the scan that defeats LRU

Write down the address trace of an n x n matrix multiply in three loop orders, and check Mattson's rule on each: a fully associative LRU cache of C lines hits exactly the references whose stack distance is below C. Then run a cyclic scan of C + 1 lines, where LRU misses every reference and Belady's MIN misses one in C.

Figure produced by Lab 9: Loop order, stack distance and the scan that defeats LRU
Produced by the lab below, seed 0, in 0.5 s.
python -m videos.cs.labs 9 needs numpy, scipy, matplotlib · download lab09.py · source on GitHub
n = 20, ijk: LRU misses of 24,000 references    9,240 in 8 lines   1,110 in 32 lines   (MIN in 32: 854; first touches 150)
n = 20, ikj: LRU misses of 24,000 references    1,100 in 8 lines   1,100 in 32 lines   (MIN in 32: 567; first touches 150)
n = 20, tiled: LRU misses of 24,000 references  2,006 in 8 lines   528 in 32 lines   (MIN in 32: 326; first touches 150)
cyclic scan of 13 lines, cache of 12: LRU       156 misses of 156 references
cyclic scan of 13 lines, cache of 12: MIN       24 misses   (C + ceil((R - C)/C) = 24)

The same multiplications in a different order touch the same lines at different stack distances, so each order has its own miss curve and none wins at every capacity; a scan one line longer than the cache is LRU's worst case and nearly free for MIN.
The code (88 lines; it asserts its own result)
"""Lab 9: replay three loop orders of a matrix multiply through Pebble's cache model, LRU against the optimal policy."""

from videos.coursekit import labs

import math

import numpy as np

from explainer.cs.pebble.cache import SetAssoc, belady, miss_curve, stack_distances

TITLE = "Loop order, stack distance and the scan that defeats LRU"
GOAL = ("Write down the address trace of an n x n matrix multiply in three loop orders, and check Mattson's rule on "
        "each: a fully associative LRU cache of C lines hits exactly the references whose stack distance is below C. "
        "Then run a cyclic scan of C + 1 lines, where LRU misses every reference and Belady's MIN misses one in C.")
TASKS = [
    "Make the cache 2-way (SetAssoc(cap * 64, ways=2)) and count the misses of each order again. Which order suffers from conflicts?",
    "Change the tile from 8 to 4 and to 16. At which cache capacity does each tile size stop missing?",
    "Scan C + 2 and 2C lines cyclically instead of C + 1. How do the LRU and MIN miss fractions change?",
]


def matmul_lines(n, order, tile=8):
    """Line numbers (64-byte lines, 8-byte doubles, row-major) touched by C[i][j] += A[i][k] * B[k][j]."""
    if order == "tiled":
        idx = [(i, j, k) for i0 in range(0, n, tile) for k0 in range(0, n, tile) for j0 in range(0, n, tile)
               for i in range(i0, min(i0 + tile, n)) for k in range(k0, min(k0 + tile, n))
               for j in range(j0, min(j0 + tile, n))]
        i, j, k = np.array(idx).T
    else:
        a, b, c = (g.ravel() for g in np.meshgrid(*[np.arange(n)] * 3, indexing="ij"))
        i, j, k = (a, b, c) if order == "ijk" else (a, c, b)  # ikj: the innermost loop walks a row of B and of C
    base = n * n * 8
    addr = np.stack([(i * n + k) * 8, base + (k * n + j) * 8, 2 * base + (i * n + j) * 8], axis=1).ravel()
    return addr // 64


def lru_misses(lines, capacity):
    cache = SetAssoc(capacity * 64, line=64, ways=capacity)  # one set: fully associative, LRU
    for ln in lines:
        cache.access(int(ln) * 64)
    return cache.misses


def run(seed=0):
    rng = np.random.default_rng(seed)
    n = int(rng.choice([16, 18, 20]))
    lab = labs.Lab()
    dist, miss = {}, {}
    for order in ("ijk", "ikj", "tiled"):
        lines = matmul_lines(n, order)
        d = dist[order] = stack_distances(lines)
        for cap in (8, 32):
            miss[order, cap] = lru_misses(lines, cap)
            assert miss[order, cap] == int(((d < 0) | (d >= cap)).sum()), "LRU hits exactly the stack distances below C"
        opt, first = belady(lines, 32), int((d < 0).sum())
        lab.row(f"n = {n}, {order}: LRU misses of {len(lines):,} references",
                f"{miss[order, 8]:,} in 8 lines   {miss[order, 32]:,} in 32 lines   (MIN in 32: {opt:,}; first touches {first})")
        assert first <= opt <= miss[order, 32], "no policy beats MIN, and nothing avoids the first touches"
    assert miss["ikj", 8] < 0.5 * miss["ijk", 8], "in a small cache, walking B by columns misses far more than by rows"
    assert miss["tiled", 32] < min(miss["ijk", 32], miss["ikj", 32]), "three 8 x 8 tiles fit in 32 lines"

    C = int(rng.choice([8, 12, 16]))
    R = 12 * (C + 1)
    scan = np.arange(R) % (C + 1)
    lru, opt = lru_misses(scan, C), belady(scan, C)
    formula = C + math.ceil((R - C) / C)
    lab.row(f"cyclic scan of {C + 1} lines, cache of {C}: LRU", f"{lru} misses of {R} references")
    lab.row(f"cyclic scan of {C + 1} lines, cache of {C}: MIN", f"{opt} misses   (C + ceil((R - C)/C) = {formula})")
    assert lru == R and opt == formula
    lab.note = ("The same multiplications in a different order touch the same lines at different stack distances, so "
                "each order has its own miss curve and none wins at every capacity; a scan one line longer than the "
                "cache is LRU's worst case and nearly free for MIN.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    fine = [2 ** e for e in range(1, 11)]
    for order, color in (("ijk", labs.RED), ("ikj", labs.BLUE), ("tiled", labs.GREEN)):
        ax[0].plot(fine, miss_curve(dist[order], fine), "o-", color=color, ms=4, label=order)
    ax[0].set(xscale="log", title=f"{n} x {n} multiply: LRU miss ratio by loop order", xlabel="cache capacity (lines of 64 bytes)",
              ylabel="misses per reference")
    ax[0].legend()
    for policy, color, name in ((None, labs.RED, "LRU"), ("min", labs.GREEN, "MIN")):
        cum = [lru_misses(scan[:t], C) if policy is None else belady(scan[:t], C) for t in range(0, R + 1, C + 1)]
        ax[1].plot(range(0, R + 1, C + 1), cum, "o-", color=color, ms=4, label=name)
    ax[1].plot([0, R], [0, R], ls=":", color=labs.MUTED, label="every reference misses")
    ax[1].set(title=f"Cyclic scan of {C + 1} lines in a cache of {C}", xlabel="references", ylabel="misses so far")
    ax[1].legend()
    lab.fig = fig
    return lab

Now change it

  1. Make the cache 2-way (SetAssoc(cap * 64, ways=2)) and count the misses of each order again. Which order suffers from conflicts?
  2. Change the tile from 8 to 4 and to 16. At which cache capacity does each tile size stop missing?
  3. Scan C + 2 and 2C lines cyclically instead of C + 1. How do the LRU and MIN miss fractions change?

Problems, with solutions

Try each problem before opening its solution.

  1. Address fields. For a 32 KiB, eight-way cache with 64-byte lines and 48-bit byte addresses, find the fields and the set of 0x7f3a12345678.

    Solution

    There are 512 lines and 64 sets: six offset bits, six index bits and 36 tag bits. The example has offset 56, set 25 and tag 0x7f3a12345.

  2. Serial AMAT. L1 costs four cycles, with miss rate 0.05. L2 adds 12 cycles, and 0.2 of L2 accesses add a further 200 cycles. Compute AMAT and the L1 miss rate that doubles it.

    Solution

    4 + 0.05*(12 + 0.2*200) = 6.6 cycles. Doubling requires m=(13.2-4)/52, about 17.69%. This concerns the modeled average access cost; it does not by itself halve whole-program performance.

  3. A cyclic adversary. In an initially empty, fully associative C-line cache (C >= 2), access C+1 distinct lines cyclically with forced insertion. Compare LRU and MIN, including startup.

    Solution

    LRU misses every reference. After initially filling C slots, MIN evicts the resident line used farthest in the future. With R >= C references, its count is C + ceil((R-C)/C), approaching miss fraction 1/C. A fixed pinned-front comparator is feasible but need not achieve this. Compare identical startup and insertion rules.

  4. Complete movement. For classical n=64 multiplication and M=1,024 fast words, evaluate 2*n^3/sqrt(M)-2*M under the all-output-in-slow-memory assumptions.

    Solution

    The bound is 14,336 words. Our 127-line LRU plus eight scalar words moves 274,432 words for either untiled order, about 19.1 times the bound. T=16 moves 64,000 words, about 4.5 times. These totals include fills, dirty evictions and final dirty lines; the old fills-only comparison understated movement. A three-tile schedule with 3*T^2 <= M has O(n^3/T + n^2) movement. Tight leading constants require a schedule and storage proof; they do not follow merely from the asymptotic big-O expression.

  5. External merge. Let N=10^10 records, B=10^5 records/block and M=10^9 records of fast storage. Reserve an output buffer. How many whole-file read/write passes does simple run generation plus merging need?

    Solution

    Ten initial runs fit a fan-in of 9,999. One generation pass and one merge pass suffice: approximately 2*2*ceil(N/B)=400,000 block transfers, excluding metadata and temporary setup. M counts records, not bytes.

  6. Build and research. Compare LRU, LIP/BIP and MIN on the scaled prefix trace. Then change the workload's phase or entry order. Keep capacities, warmup, insertion and random seeds comparable. Tune on one segment and evaluate on heldout segments; a fitted winner on a growing table need not track a changing working set. For the full prefix stream, distinguish a feasible upper-bound policy from exact offline MIN. Derive a compressed-state algorithm or validate a proposed bound against expanded small traces before scaling up.

Notes and sources

Sources

Canon: Belady (1966); Denning (1968); Mattson et al. (1970); Bayer and McCreight (1972); Hong and Kung (1981); Aggarwal and Vitter (1988); Wulf and McKee (1995); Frigo et al., Cache-Oblivious Algorithms (1999). Textbook context: Hennessy and Patterson, Computer Architecture; Bryant and O'Hallaron, CS:APP; Jacob, Ng and Wang, Memory Systems. Qureshi et al. (ISCA 2007) motivates adaptive insertion.

Primary research checked for the repaired claims:

The evidence packet records which primary sections were actually read. Sampled preview QA is separate from continuous listening, Chinese speech/listening, whole-video native production review and a runtime decision at an approved narration pace. Those production release gates remain open.

About this partfrom its README

A cache earns its speed by exploiting a program's access history. This chapter builds the mechanisms, measures a host, and asks which conclusions survive when the model changes. Seventeen scenes connect address decoding, replacement, locality, data layout and communication bounds to the continuing Pebble Job. See the series plan and syllabus.

The visual spine moves from a latency scale and address-time scatter to moving cache lines, reuse-distance curves, a pointer-chase staircase, matrix traversal, legal red-blue pebble moves and a conditional cost ledger. English and Chinese narration share bookmark order; a local caption table translates explanatory labels.

Chapter notes
  1. Hook / memory wall. A second-per-cycle illustration uses an explicitly illustrative 2.8 GHz clock. Host footprint samples remain footprint samples, rather than guaranteed L1/L2/L3/DRAM identifications. Historical growth rates illustrate a dated trend; they are not a present-day forecast.
  2. Locality / direct mapping. Watch the Job's table prefixes and letter addresses, then split an address into offset, set and tag. A reuse-distance miss curve assumes fully associative LRU and a specified line size.
  3. Associativity / the three Cs. Compare LRU, tree PLRU, FIFO, random and offline MIN under matching cache rules. A signed set-associative-minus-fully-associative difference can be negative; it is not literally a negative number of physical conflict events. Writes require a separate allocation and propagation policy.
  4. AMAT. Nest conditional miss rates with incremental service costs. Cumulative pointer-chase delays must first be differenced, with a nondecreasing envelope, before they can populate this serialized model.
  5. Measured host. Random dependent loads measure latency-like costs; independent streams measure logical GB/s. Allocation advice does not prove that huge pages were used. A bend alone does not establish a cache boundary, TLB cause, physical miss count or number of outstanding hardware requests.
  6. Programming. Compare row and column traversal, loop order, tiling and structs of arrays. C timings and a NumPy/BLAS result belong to their stated implementations/settings; the chart does not isolate vector width or thread count as a cause. Axes adapt to the cached measurements.
  7. Cache-oblivious algorithms. Recursive transpose illustrates an ideal-cache argument under its cache and tall-cache assumptions. The plotted unit is allocation fills per data reference: 0.125 fills/reference equals 0.25 fills/output element because each output entails two references. Dirty writebacks are excluded from this particular plot. Balanced static van Emde Boas layout has an O(1 + log_B N) search bound in its model.
  8. Pebbles and matrix movement. Every demonstrated compute move has red predecessors and enough red slots. With the stated place-new rule the tiny graph needs at least three red slots: M=2 is impossible, M=3 needs six transfers, and M=4 permits the displayed four-transfer schedule. Independent shortest paths verify this. The classical matrix bound requires its stated computation/output assumptions. Its comparison chart counts line fills, dirty evictions and the final output drain, reserving eight of 1,024 fast data words for scalars.
  9. External memory. Scanning, comparison sorting and B-trees use item/block units. The sorting expression includes the small-input regime. A merge must reserve output space; fan-in is at most floor(M/B)-1 in the simple buffered implementation. Tree height also depends on occupancy and root conventions.
  10. Prefetch / DRAM. The teaching hierarchy has immediate, uncharged prefetch, no queues or bandwidth limit, no coherence/translation, no inclusive back-invalidations and no propagated dirty-write timing. Its dramatic speedups are conditional. The DRAM diagram assigns eight banks and 8 KiB rows; it does not measure host banks. Activation restores charge, precharge prepares bitlines, and refresh/scheduling/interface details matter.
  11. Job / frontier / recap. Exact table-prefix LRU counts coexist with a separate sampled cost projection. Learned replacement uses offline labels and online predictors with explicit state and generalization limits. Hawkeye, Glider, Mockingjay and Streamline illustrate different mechanisms; they are not interchangeable models.
NotesWhat the Job figures mean

The corpus has 4,609,954 words and 57,895 distinct entries in this cached run. A new word reads only existing entries, then appends its own slot. The abstract trace includes the length field at byte offset four of each 12-byte entry. It contains one empty scan and 2,818,246,721 table-line visits, not all loads/stores in the program. A constant-space cached-prefix state computes exact fully associative LRU counts for this stream. Literal cache simulations check small cases; an independent corpus calculation checks all nine capacity rows.

The green feasible comparator pins C-1 initial lines and discards a transient line after use. It obeys forced insertion and upper-bounds MIN's misses; it does not compute exact MIN. For a loop over C+1 lines, MIN's steady miss fraction is 1/C, not one miss per C+1-reference pass.

A different model samples four corpus windows, coalescing table events and first-letter pool events. The abstract grown table and letter pool are relocated into disjoint regions. Later matching letters, target reads and stores are omitted. Synthetic benchmarks on the functional core supply cost increments, and a fit weights those increments by sampled fractions. It is not a full execution of the unchanged Pebble memory image.

The resulting row-3 projection is about 57.36 s at the assumed clock, an approximately 0.0645% increase; turning off immediate free prefetch gives about 2.67%. These values have no claimed physical runtime error bound. They omit bandwidth, queues, prefetch lead time and complete writes. A serialized all-large-set waiting budget is an illustration, not a measured no-cache run or a universal runtime bound.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. The memory wall (Wulf & McKee 1995): the CPU–DRAM gap over decades (cited).
  2. Locality, temporal and spatial; reuse distance; the Job's memory trace as an address-against-time scatter.
  3. Direct-mapped caches: tag, index and offset bits; hits and misses animated.
  4. Associativity; replacement (LRU, pseudo-LRU, random); write-back against write-through; write-allocate.
  5. The 3C model (compulsory, capacity, conflict) measured on traces; miss-rate curves.
  6. AMAT = hit time + miss rate × miss penalty, applied recursively across levels.
  7. Measured on this machine: the pointer-chasing latency staircase (L1, L2, L3, DRAM, TLB) and a bandwidth test. The scale, if one cycle were a second: L1 ≈ 4 s, DRAM minutes, an SSD days, a disk months.
  8. Programming for caches: loop interchange; tiled matrix multiply (callback to AI, Built 17); arrays of structs against structs of arrays. Speedups measured.
  9. The ideal-cache model (Frigo et al. 1999): cache-oblivious transpose and multiply; the van Emde Boas tree layout.
  10. The red–blue pebble game (Hong & Kung 1981): any schedule for n × n matrix multiply with M words of fast memory moves Ω(n³/√M) words (proof idea). Our tiled multiply against the bound.
  11. External memory (Aggarwal & Vitter 1988): the sorting bound (N/B) log_{M/B}(N/B); B-trees (Parts 17, 35).
  12. Prefetching: stride prefetchers and software prefetch.
  13. DRAM in depth: banks, rows, CAS and RAS, row-buffer hits; HBM (callback to AI, Built 17). The TLB previewed (Part 32).
  14. The Job with a cache model. Ledger row 3.
  15. Frontier: learning to replace. Insertion policies on the Job's scans (LRU 63%, bimodal insertion 47%, Belady 33%, computed); Hawkeye and Glider; online policies against Belady, pebble bounds beyond matrix multiply, disaggregated memory.
  16. Outro.

Computed: a cache simulator on the Job and other traces; 3C breakdowns; this machine's latency staircase and bandwidth; tiled matmul speedups; the pebble-game bound against simulated misses. Visuals: address bits splitting; cache sets as shelves with tags; the staircase; the camera zooming down the hierarchy on the "cycle = second" scale. In practice: cache-friendly data layout in game engines, databases and HPC; NUMA tuning; the latency numbers behind every system design. Reading: Hennessy & Patterson ch. 2, App. B; Bryant & O'Hallaron, Computer Systems: A Programmer's Perspective ch. 6; Jacob, Ng & Wang; Drepper, "What Every Programmer Should Know About Memory" (2007); Frigo, Leiserson, Prokop & Ramachandran 1999; Hong & Kung 1981; Aggarwal & Vitter 1988; Wulf & McKee 1995.

Build the film

python -m videos.cs.cs9.compute        # the part's numbers, into .cache/cs9
python tools/build.py cs9                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs9 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs9. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build itReproduce the data and renders

Run from the repository root, using the project environment:

python -m videos.cs.cs9.compute                  # reuse current items; compute missing or legacy items
python -m videos.cs.cs9.compute scans pebbles job_memory job --force
python -m unittest tests.test_cs9_cache
python tools/build.py cs9 -q l                  # low-resolution build
python tools/build.py cs9                       # native production build

Explicit compute commands refresh legacy schemas. Ordinary scene loads reject a legacy scan, movement or projection payload with a refresh command; reading does not silently rewrite evidence. Computations use explainer.paths and .cache/cs9/. Host benchmarks and simulated microbenchmarks can take several minutes. Changing a producer requires reviewing its downstream items as well as its own JSON. --force deliberately replaces cached measurements, so do not use it during a frozen QA run.

This checkpoint's host reports AMD EPYC 9V74 80-Core Processor with no usable measured GHz field. The 2.8 GHz comparison clock is illustrative; Pebble's approximately 885 MHz clock is a teaching assumption inherited from its timing model. Host timings vary with scheduling, virtualization, allocation and workload. Cache inventory reported by the OS does not prove how much capacity this process effectively receives.