CComputer Science, Built

Act II · Making It Fast

Part 7 of 61

Pipelines

Degreestarts at this level34 min of film17 chaptersprerequisites: Part 5, Part 6

How can a processor work on five instructions at once, and what does it do when it must guess?

Part 6's single-cycle Pebble makes every instruction wait for the slowest one: 2.63 ns a cycle on the part's assumed timing budget. The iron law, time = instructions x CPI x cycle time, says where to look, and the laundry picture says how: overlap the work in five stages with registers between them, so that throughput rises while each instruction's latency does not fall. A cycle-by-cycle model of the five-stage pipeline is built and compared with the emulator, and its hazards are counted: structural ones, data ones that forwarding removes except for the bubble after a load, and control ones, where fetch must guess. The part turns on the guess. Smith's 1-bit and 2-bit counters, gshare, a tournament, a small TAGE and Jimenez and Lin's perceptron are run on the same branch traces, with a target buffer and a return stack to say where a branch goes. The Job's first chapter then runs at a CPI of about 1.2 on a 1.13 ns clock, almost twice as fast as Part 6. The part ends with what stopped deeper pipelines (power), with Amdahl's law, with the sorted-array puzzle timed on this machine, and with how far prediction can go on one trace.

What you need. Programming, and school algebra with one derivative for the best depth. No electronics beyond Parts 3 to 6.

Mathematics, ideas and history
the iron law, hazards, forwarding, branch prediction (2-bit, gshare, TAGE, perceptron), Amdahl
What we build or compute
a cycle-accurate pipeline; predictors on real traces

What you will be able to do

Degree

  • Compute a program's run time from the iron law, and explain why MIPS alone can rank two programs the wrong way round.
  • Draw the pipeline chart of a short instruction sequence with forwarding, placing the load-use bubble and the two-cycle flush after a mispredicted branch.
  • Trace a 1-bit and a 2-bit counter over a loop branch and count their misses.

Graduate

  • Derive the pipelined speedup (t + o)/(t/k + o), its limit 1 + t/o, and the depth that minimizes time per instruction when a fraction b of instructions loses k - 1 cycles.
  • Explain what gshare, a tournament, TAGE and a perceptron each add to a table of counters, and what a target buffer and a return stack predict.
  • State what a precise exception guarantees and how the pipeline delivers it.

Research

  • Explain why hindsight majority, an unlimited PPM predictor and a perceptron's failure on XOR are not prediction limits, and say what each does establish.
  • Design a held-out evaluation of a predictor: separate training, tuning and test traces, and a storage budget that counts every bit of state.

Industry

  • Measure before tuning: read cycles, instructions and branch misses from hardware counters and turn them into a CPI breakdown.
  • Decide when replacing a data-dependent branch by arithmetic or a conditional move pays, and measure the extra work it does.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 18 min · Graduate 30 min · Research 34 min · Industry 20 min.

  1. 0Twelve times slowerDegree1 min
  2. 1The iron lawDegree3 min
  3. 2Pipelining, like laundryDegree2 min
  4. 3Pebble's five stagesDegree1 min
  5. 4Structural hazardsDegree1 min
  6. 5Data hazards and forwardingDegree1 min
  7. 6Control hazardsDegree2 min
  8. 7Predicting branchesDegree2 min
  9. 8Correlation, and a perceptronGraduate4 min
  10. 9Where the branch goesGraduate2 min
  11. 10Precise exceptionsGraduate2 min
  12. 11The Job on the pipelineGraduate2 min
  13. 12Deeper, and the end of the raceIndustry1 min
  14. 13Amdahl's lawDegree2 min
  15. 14The puzzle, solvedIndustry1 min
  16. 15Frontier: the limits of predictionResearch4 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 dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.

Twelve times slowerDegree1 min

Here are three lines of C. Walk an array, and add up every value of at least a hundred and twenty-eight. Give it two copies of the same numbers. Leave one shuffled. Sort the other. Same values, same sum, the same additions, in a different order.

That's times slower, for exactly the same additions. Nothing in the C code explains that. The answer is inside the processor. It doesn't wait to learn which way the if will go. It guesses, and races ahead. Guess right, and the work it did early is kept. Guess wrong, and that work is thrown away. Run the same loop on Pebble, the computer we built from gates, and count the wrong guesses. Shuffled: . Sorted: .

By the end of this film you'll know what a wrong guess costs, to the cycle, on a machine we built. To get there, we turn Part 6's computer into an assembly line.

Part 6's Pebble works on one instruction at a time. Today it works on five at once. We'll define speed, build the assembly line, break it with hazards, repair it with guesses, and run the Job on it.

1The iron lawDegree3 min

What does "faster" mean?

To make a computer faster we first need to say what faster means: less time to run a program. That time can be split into three ratios. The number of instructions the program executes. The average number of clock cycles each instruction takes. And the length of a cycle in seconds. Multiply them, and the instructions and the cycles cancel, leaving seconds per program. Architects write it as T equals N times CPI times the cycle time. The textbooks call it the processor performance equation; engineers call it the iron law. Its power is that the three factors belong to different people. N belongs to the algorithm, the compiler and the instruction set. CPI belongs to the organization of the processor. The cycle time belongs to the circuits, and to how the work of an instruction is divided up. Making one factor smaller often makes another larger, and the law keeps the accounts honest.

Here is the law applied to the machine of Part 6 and the one this part builds, both running the first chapter of Pride and Prejudice through the Job. The program is the same, so N is the same: eight hundred and twenty-seven thousand instructions. The single-cycle machine has a CPI of exactly one, and a cycle of two point six three nanoseconds. The pipeline's CPI rises to about one point two, because of the hazards this part is about, but its cycle shrinks to one point one three. Multiply out, and the pipeline is almost twice as fast. That is the whole bargain of pipelining: give up a little CPI to win a lot of clock.

For decades processors were sold by MIPS, millions of instructions per second, a number that leaves out the first factor of the law. Two programs print the numbers from one to two thousand. One finds each digit by subtracting powers of ten, as the Job does. The other uses the divide instruction this part adds to Pebble. The subtracting program runs many simple instructions and scores MIPS. Each divide holds the divider for sixteen cycles, so the dividing program scores only .

2Pipelining, like laundryDegree2 min

How do you finish more without finishing anything sooner?

Patterson and Hennessy picture this as laundry. Each load needs four steps of an hour: wash, dry, fold, put away. One load at a time, four loads take sixteen hours.

Notice what didn't change. Each load still takes four hours from dirty to put away: the latency is the same. What changed is throughput. Once the line is full, a load comes out every hour. A processor works the same way. No instruction finishes sooner; more of them finish per second.

Now the arithmetic. Say an instruction is t of logic, cut into k equal stages, and every pipeline register adds a little overhead, o. The cycle is t over k, plus o. One instruction now takes k cycles, so its latency grows: t plus k times o. But one finishes every cycle, so the speedup is t plus o over t over k plus o. Make k huge and it stops at one plus t over o. The registers, not the logic, set the limit.

Real stages aren't equal. Here is Part 6's single cycle, divided by what each piece does. Cut it at the stage boundaries and stand the pieces up. The two memories dominate; decode and write back are slivers.

So the clock gets times faster, not five. The memories set the pace, which is why Part 9 is all about them.

3Pebble's five stagesDegree1 min

Where do you cut a single-cycle machine?

Cut Pebble's datapath where the work naturally changes hands. Fetch the instruction. Decode it and read its registers. Execute it in the ALU. Touch data memory. Write the result back. Between the stages go pipeline registers. At every clock edge each one captures what its instruction still needs: operands, the destination register, even the control signals, decoded once and carried along. That's how five instructions, each at a different point in its life, share one datapath.

Watch the clock. The first instruction enters fetch. Every cycle, everything moves one stage right, and a new one enters behind it. By cycle five the pipeline is full: five instructions in flight, and one finishing every cycle.

instructions, cycles: four to fill the pipe, then one per cycle. So cycles equal n plus four, and CPI is one plus four over n, which heads to one for a long program. That's the ideal. The rest of this film is about what stops us reaching it.

4Structural hazardsDegree1 min

What if two instructions need the same part at once?

The ideal pipe breaks whenever an instruction can't move on. These are hazards, and there are three kinds. Structural: two instructions want the same hardware. Data: one needs a value that isn't made yet. Control: the machine has to fetch before it knows where the program goes. The last-resort cure is always the same. Hold the instruction, and let an empty slot, a bubble, travel down the pipe in its place. The art is stalling as rarely as possible.

First, the structural kind. Suppose there's one memory. Fetch reads it every cycle. And whenever a load or store reaches MEM, it wants the same memory, in the same cycle.

Structural hazards also come from slow units. A divide occupies the execute stage for sixteen cycles, two quotient bits at a time, like Part 4's divider. Watch the add behind it. It has nowhere to go, so it waits in decode, and bubbles flow out ahead of it.

Chain eight divides and the program takes cycles, of them stalls. Multiplication, in contrast, settles inside one execute cycle, so it costs nothing extra.

5Data hazards and forwardingDegree1 min

What if an instruction needs a result still on its way?

Here's a chain where every instruction uses the one before it. The add reads a zero, which the instruction just ahead of it is still computing. The subtract needs the add's answer, and so on down.

Watch the subtract. It reaches decode, finds its operand missing, and stays. Bubbles leak out ahead of it.

But the value exists long before it is written back. It's sitting at the end of execute, in the next pipeline register. So send it straight back, to the next instruction's ALU input. That's forwarding, and the yellow arcs are values taking the shortcut.

cycles instead of : every bubble gone. The hardware is a few comparators and multiplexers. Does a source register match the destination of an instruction ahead? Then take the newest match.

So the hardware stalls once, and compilers learn to fill that slot with useful work.

On real programs: without forwarding, CPI runs from to . Switch it on, and every bar shrinks. The drops from to . What's left is load-use stalls, and branches.

6Control hazardsDegree2 min

What do you fetch before you know where the program goes?

Fetch must deliver an instruction every cycle. But after a branch, which one? The branch is only decided in execute, two stages later. The simplest policy is to keep fetching the next instructions in memory, and hope the branch isn't taken. Here's a loop whose branch is taken twice.

Watch the grey ones fall. By the time the ALU decides, two wrong instructions are already inside, one in decode and one in fetch. They're flushed before they change anything, and fetch restarts at the target. Two cycles lost, every taken branch.

How much does that cost? The extra CPI is branches per instruction, times the fraction we get wrong, times the penalty. In the Job, percent of instructions are branches, and percent of those are taken. Two cycles each: about cycles added to every instruction. And a deeper pipeline decides later, so the penalty grows with depth. This one equation made branch prediction one of the most studied problems in architecture.

Three ways out. Decide earlier: compare in decode and lose only one cycle, at the price of a longer stage. Change the rules: in classic MIPS the instruction after a branch always runs, and the compiler tries to put something useful there. That slot became a burden later, and newer designs dropped it. Or guess. Fetch the likely path, check in execute, and pay only when wrong. Every fast processor since the nineties guesses, and guessing well is the next chapter.

7Predicting branchesDegree2 min

Can the past predict a branch?

The cheapest guess is a fixed rule. Early machines used this one. A branch that jumps backwards is probably closing a loop: guess taken. A branch that jumps forwards is probably an if: guess not taken. On the insertion sort, that rule is right percent of the time.

In 1981 James Smith measured the obvious learning rule. Keep a small table of bits, indexed by the low bits of the branch's address. To predict, look the branch up: a one means it was taken last time, so guess taken again. When it resolves, write down what it actually did.

A loop that runs ten times shows the flaw. Its branch is taken nine times, then not. A one-bit table flips on the exit, so it misses the exit, and then misses again when the loop restarts.

Watch the yellow dot. It sits at strongly taken. The exit nudges it to weakly taken, not across, so the restart is still guessed right.

Here are all seven programs, percent predicted correctly. Two bits are a big step up from fixed rules. But look at the threshold loop on random data and the Fibonacci recursion: a counter per branch remembers only which way it usually goes. To do better, it has to know what happened just before.

8Correlation, and a perceptronGraduate4 min

Can other branches predict this one?

A branch's own past is not the only clue. If the first two conditions here are known, the third is determined. A counter watching only the third branch does not directly observe that cross-branch information. Record recent outcomes in order in a global history shift register: one for taken, zero for not taken. Yeh and Patt's 1991 work demonstrated two-level adaptive prediction. Which information helps depends on the program, history representation, table sharing and training.

Global history records recent branch outcomes. McFarling's gshare hashes that history with the branch address using exclusive-or, then selects a two-bit counter. Different contexts can select different counters; collisions can also make unrelated contexts share one. Our tournament chooses between a per-address bimodal counter table and gshare, using another table of counters. This illustrates adaptive choice. It is not a reproduction of Alpha 21264's historical local-history and global-history predictor: a per-address direction counter is simpler than a local-history predictor.

Different branches benefit from different history lengths. Seznec and Michaud's TAGE combines a base predictor with partially tagged components using geometrically spaced histories. Our simplified version uses four through sixty-four outcomes. It selects the longest matching tag and allocates longer-history entries after some misses. Full designs add confidence, alternate-provider and replacement policies. TAGE and its descendants are influential competition and processor designs. We will compare our small implementation, keeping its results distinct from commercial predictors and the full published algorithms.

Jimenez and Lin proposed perceptron branch prediction in 2001. Represent each of the last h outcomes as plus one or minus one. A hash of the branch address selects a weight vector, so different branches can share and interfere with the same weights. Add a bias and the weighted inputs; a nonnegative sum predicts taken. When wrong or insufficiently confident, adjust weights toward the observed outcome. The heatmap next shows the weights this rule learns. Parameter count grows linearly with history length, unlike a fully enumerated context table. That comparison does not cover every table-based scheme.

Because a perceptron's knowledge is a row of weights, we can look at what it learned. Each row here is one branch: the bias weight, then one weight for each of the last sixteen branch outcomes, most recent first. The correlated benchmark was built so that branch B repeats the outcome of branch A, four branches earlier, with three random branches in between. The perceptron found it: one bright weight at position four, almost nothing elsewhere, and B predicted almost perfectly, where a two-bit counter manages a coin toss. The Job's scan branch, the test for a table entry of the wrong length, has a messier pattern: its outcome depends on the lengths of words in the table, and some of that shows up in the recent history. The insertion sort's comparison alternates with its loop branch, and the weights alternate too.

Compare the learning predictors on these traces. Global information helps Fibonacci and the correlated benchmark, but the latter uses fixed-seed pseudorandom data, not genuine independent coin flips. Our TAGE is best on the shown Job trace and reduces misses relative to the two-bit predictor.

9Where the branch goesGraduate2 min

Knowing it is taken is not enough

Direction alone is not enough: fetch also needs a target. A branch target buffer, indexed by the program counter, remembers the kind and target of earlier control transfers. On a hit with a correct taken prediction and correct target, our ideal front end fetches from that target next cycle. On a miss it continues at pc plus four until a redirect. A warm, correct BTB hit can therefore remove the modeled unconditional-jump redirect cost. Cold misses, aliases, wrong indirect targets and real fetch-bandwidth constraints can still cost time. Free here is a condition of this model, not a universal property of jumps.

A return can have many targets. The same instruction returns to different callers, so remembering only its last target often fails in recursion. Recognized calls and returns normally nest: push the return address on a small front-end stack at each call and pop it at a return. A sixteen-entry stack works well on the balanced call patterns shown. Deeper nesting can discard entries; unusual control transfers, context switches and speculative repair also matter in real systems. Its residual misses must be measured rather than attributed to overflow from the count alone.

Run the same recursive Fibonacci program on three modeled front ends. With no target buffer, the table records redirects for jumps and returns. A BTB removes many jump redirects, but a last-target entry still misses many returns. Adding a sixteen-entry return stack cuts return misses to a few hundred and lowers CPI to about one point one two in this run.

10Precise exceptionsGraduate2 min

Where exactly was the machine when it stopped?

An exception needs a precise architectural boundary. In this sketch, Pebble's custom policy treats division by zero as a fault. The divide is in execute, with older and younger instructions around it. RISC-V's M extension instead defines a result for division by zero. At a precise fault, older instructions have committed their architectural effects; the faulting instruction follows its defined side-effect policy, and younger instructions have not committed theirs. Pebble stops and reports the divide's address. An operating system could use such a boundary for recovery, but this simulator implements no operating-system resume mechanism. Cache and predictor effects are a separate question.

Separate detecting a fault from committing it. The model records a detected problem with its instruction. When that instruction reaches write-back, it stops the machine and discards younger work. Older operations have completed. Stores occur in MEM only after older instructions have passed the stages where this model can discover a fault. In this test, the first store commits, the divide faults, and the younger store does not change memory. The final architectural state and fault address agree with the emulator. That is the tested promise; it does not erase all microarchitectural traces of younger activity. Out-of-order execution needs additional machinery to preserve the same boundary.

Self-modifying code exposes another boundary. This loop changes the offset in its own load. The sequential emulator and gate machine give thirty-one, while this predicted pipeline gives twenty-six. Fetch can revisit the load before the older store updates its encoding. Without prediction the redirect happens to refetch the newer word; that is accidental. Instruction-fetch synchronization is ISA-specific. RISC-V fence dot i orders a hart's already-visible prior stores before its later fetches; other harts and operating-system migration need broader protocols. x86 also specifies self- and cross-modification rules. Our Pebble model implements no instruction fence, so this example demonstrates its explicit limitation.

11The Job on the pipelineGraduate2 min

Where do the Job's cycles go now?

Look closely at the Job's search loop. The displayed mismatched-length fast path has six instructions. Loading the entry length immediately before testing it causes one load-use bubble. Equal-length entries can enter the letter-comparison path and do more work. With warm, correct direction and target predictions, the jump back adds no modeled redirect cost. On that fast path, six instructions then take seven steady-state cycles. The larger ninety-nine point seven percent figure covers the whole search in the single-cycle instruction count, not only this path. Scheduling an independent, safe instruction between the load and use can hide the bubble; moving a load past a bounds check first needs an address-safety proof.

The simulator accounts for every cycle, so the Job's CPI on its first chapter can be taken apart. With no forwarding and no prediction, the CPI is one point nine: the base cycle, plus waiting for data, plus a flush on every taken branch and jump. Forwarding removes the data waits except for the load-use bubbles. A target buffer and two-bit counters remove most of the branch losses. A tournament predictor and a return stack shave off a little more: a CPI of one point two, three quarters of whose excess is the load-use bubble in the scan loop, the rest the branches that still go wrong.

The full-corpus pipeline row is a projection. Fit a linear bubble model to twenty-four short passages, using text events such as scanned entries. This is different from Part 6's instruction path-count formula. The displayed sixteen-thousand-character heldout text, encoded as sixteen thousand and nineteen bytes, checks one prediction and reports its error. It does not establish an error bound for the thirty novels. Combining the fitted bubbles with the corpus instruction count and eight-hundred-and-eighty-five-megahertz clock gives the displayed CPI and projected minutes. The ledger's speedup is therefore a model-based estimate for the same program. A full run or broader validation could reveal a different result.

12Deeper, and the end of the raceIndustry1 min

Why did clocks stop getting faster?

Put numbers on it. Time per instruction is the cycle, which shrinks as you add stages, times one plus the miss rate times the cycles each miss throws away, which grows. Here it is with the Job's own miss rate.

That's what happened. Through the nineties, clocks climbed a hundredfold, from sixty-six megahertz to gigahertz. The Pentium 4 pushed depth to twenty stages, then thirty-one, and reached three point eight gigahertz. Then Intel cancelled the next, deeper design, and in 2006 Core 2 arrived with about fourteen stages and a lower clock, and beat it. Clocks have crept up since, but the race was over.

The other wall was power. A chip's switching power is roughly activity, times capacitance, times voltage squared, times the clock. For decades each new process lowered the voltage, which paid for the faster clock. Around 2005 voltage stopped falling, because lower voltages leak. Every extra hertz now cost real watts, and a deep pipeline spends many of them on work it throws away. The transistors kept coming. They went into more cores, which is Part 10.

13Amdahl's lawDegree2 min

How much can speeding up one part help?

Amdahl's 1967 argument is a model for fixed work. Let p be the fraction of baseline execution time improved by a factor n. Assume the remaining work and its cost stay fixed, with no new overhead. The new time, relative to the old, is one minus p plus p over n. Speedup is its reciprocal. For p less than one, the limit is one over one minus p. Make ninety percent of the original time vanish, and the unchanged ten percent limits speedup to ten. Changing problem size or adding costs requires a different accounting.

Plot the speedup against n for a few values of p. Each curve rises, then flattens against its ceiling: two for p of a half, ten for ninety percent, twenty for ninety-five, a hundred for ninety-nine. The corollary is the design rule this series keeps meeting: make the common case fast. And after every improvement, look again, because the part you did not speed up is now most of the time. John Gustafson pointed out in 1988 that people given a bigger machine usually run a bigger problem, whose improvable part grows with it, which is why many processors turned out to be worth building after all.

Apply the accounting carefully. Pipelining improves throughput; it does not make every individual instruction finish sooner. For the same instruction count, total speedup is the clock-rate ratio divided by the CPI ratio. Linear search accounts for ninety-nine point seven percent of this Job's single-cycle instructions. That is also its time share only in the uniform-cost single-cycle model. Eliminating that work with no replacement cost would give an ideal ceiling of about three hundred and fifty. On a pipeline, measure the time share and new costs again. Hardware schedules the work better; algorithms can change how much work remains.

14The puzzle, solvedIndustry1 min

Why does sorting the data make a loop faster?

Back to where we started. The same loop, times slower on shuffled data. You now have everything you need to explain it.

Watch the branch inside the loop, one value at a time. On shuffled data, taken or not is a coin flip. A predictor learns nothing, and misses about half the time. On sorted data it's one long run of not taken, then one long run of taken. The predictor misses once at the switch, and that's it.

Or remove the branch altogether. Compare, and turn the answer into a mask: all ones for a big value, zeros for a small one. AND it with x, and add. Nothing to guess.

15Frontier: the limits of predictionResearch4 min

How good could a branch predictor be?

What do these experiments establish? This is an empirical comparison on one trace, not a prediction limit. The Job chapter supplies about a quarter-million branch outcomes. The two-bit table is our baseline. Our simplified TAGE improves as its arrays grow. The horizontal axis estimates nominal packed table payload, excluding history, validity and implementation overhead; it is not Python memory or a complete hardware budget. The perceptron changes little over the tested sizes. The dashed PPM result uses a different algorithm with unbounded context-table growth but a bounded set of history lengths. Its advantage cannot be assigned entirely to storage, and its remaining errors are not proved impossible. Compare algorithms under a defined training protocol before drawing stronger conclusions.

Try a table for each chosen history length. Predict before updating on each outcome. In this run, online accuracy peaks near twelve outcomes of history, then falls as contexts recur less often. This is an observed learning trade-off, not a universal optimum. The dashed curve instead uses each context's majority label from the entire evaluated trace. That is an offline oracle for this feature class; it uses future labels and is not a deployable online predictor. It is bounded by one hundred percent. Our PPM-style model backs off among its configured lengths, up to sixty-four outcomes, and stores the shown number of contexts. Partial matching links prediction and compression, but entropy and code length concern probabilities and log loss. They do not directly give a branch-accuracy ceiling. TAGE shares some ideas while imposing finite hashed tables.

A small example gives a precise representational result. Let branch B equal the exclusive-or of two earlier bits, A and C. The taken cases lie on opposite corners. No fixed affine line separates all four labels. With only these two features, a perceptron cannot classify XOR perfectly; a best line can still get three of four equally likely cases right. Thus fifty percent is not the mathematical ceiling. Our online parity run happens to give this perceptron about forty-nine percent. Other histories, initialization and learning rules can change that empirical result; it does not explain the entire Job plateau. Research expands features and combines predictors: piecewise-linear methods select functions by path; multiperspective predictors hash several history features.

Research starts by defining the information and evaluation protocol. Profile which static branches cause errors on the chosen workload. Independent unseen random data would defeat a history-only guess, but our fixed traces do not prove such independence. BranchNet, published in 2020, trains convolutional models offline and combines predictions for selected hard branches with a runtime predictor. Its paper evaluates unseen inputs; that is research evidence for specified workloads, not a claim that arbitrary branches become predictable. Large code footprints also pressure instruction fetch and prediction capacity. Accuracy and capacity both matter, depending on the application. A fair next experiment fixes allowed features, all state bits, training data and heldout chapters. Keep test labels out of design and initial state. That makes improved accuracy evidence of generalization, rather than memorization of a known trace.

Recap, problems, and where this comes backAll tracks3 min

We visualized hazards, forwarding, load-use stalls, and precise architectural exceptions, with finite emulator comparisons. We measured counter, TAGE and perceptron implementations on specified traces, without claiming an absolute prediction limit. Short Job passages were simulated cycle by cycle; the full-corpus ledger row is a fitted projection, nearly twice as fast under its assumptions. Multiple instructions overlap, while this one-wide pipeline retires them in order.

Where this comes back. Our pipeline overlaps instructions but retires at most one per cycle in order; Part 8 lets independent instructions execute out of order. The assumed memory delays lead to Part 9's caches. Power constraints motivate multicore and SIMD. Instruction scheduling can hide some load-use bubbles when movement is safe. Speculation's microarchitectural traces connect to Spectre, and Amdahl's fixed-work accounting returns in parallel and distributed systems.

In practice, measure first. Linux perf stat can report supported cycle, instruction and branch events when permissions allow; results depend on the processor and operating system. Profilers help find baseline time shares, and wall time differs from processor time. Conditional moves, safe if-conversion and data reordering can help hot loops, but measure their extra work too. Vendor manuals and Agner Fog's tables provide useful measured and documented costs, not every core's complete internal pipeline. Open-source Rocket and BOOM offer concrete predictor implementations to inspect.

Six problems are in the notes. The fifth schedules the Job's loop, with a required proof that a hoisted load is safe under this memory layout. The starred exercise designs a predictor within sixty-four kibibytes of fully accounted state. Choose training and tuning chapters first, then evaluate untouched chapters with no encoded future outcomes. A known trace can be memorized, so replay accuracy alone is not the research question. Report the protocol, remaining misses and what generalizes.

Next time: our pipeline overlaps instructions, but executes and retires in order. When an older operation blocks progress, independent younger work may still be ready. Part 8 studies scheduling that work with register renaming and a reorder buffer to preserve precise architectural state. Modern cores can keep many instructions in flight. The 2018 Spectre disclosures also showed how some speculative activity can leak information through microarchitectural effects, under specific attack conditions.

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

Where it goes next. The in-order pipeline becomes the out-of-order core of Part 8, where speculation past a predicted branch returns as Spectre; the assumed one-nanosecond memories become the caches of Part 9; the power wall and Amdahl against Gustafson return in Part 10; hiding a load-use bubble by moving an instruction returns as instruction scheduling in Part 13's compiler.

Key results

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

The iron law\(\displaystyle T = N\times\text{CPI}\times t_{\text{clk}}\)
Pipelined speedup\(\displaystyle \frac{t+o}{t/k+o}\ \longrightarrow\ 1+\frac{t}{o}\quad\allowbreak (k\to\infty)\)
Every cycle accounted for\(\displaystyle \text{cycles}=n+4+\text{bubbles},\qquad\allowbreak \text{CPI}\to 1+\frac{\text{bubbles}}{n}\)
The cost of branches\(\displaystyle \text{CPI}=1+f_{\text{branch}}\times m_{\text{miss}}\times\text{penalty}\)
The best depth\(\displaystyle T(k)=\Bigl(\frac{t}{k}+o\Bigr)\bigl(1+b(k-1)\bigr),\qquad\allowbreak k^*=\sqrt{\frac{t(1-b)}{b\,o}}\)
Amdahl's law\(\displaystyle S(n)=\frac{1}{(1-p)+p/n}\ \le\ \frac{1}{1-p}\)

Try it

Lab 7 · Every bubble counted: a sort on the five-stage pipeline

Assemble an insertion sort of sixty random words, run it on the instruction emulator and on three pipelines (no forwarding, forwarding, forwarding with a target buffer and 2-bit counters), and check that each pipeline's cycles are instructions + 4 + the bubbles it reports. Then count a loop branch's misses under 1-bit and 2-bit counters.

Figure produced by Lab 7: Every bubble counted: a sort on the five-stage pipeline
Produced by the lab below, seed 0, in 0.2 s.
python -m videos.cs.labs 7 needs numpy, scipy, matplotlib · download lab07.py · source on GitHub
instructions executed (emulator)       5,733
no forwarding, predict not taken       8,928 cycles = 5,733 + 4 + 2,164 data + 1,027 control   CPI 1.557
forwarding, predict not taken          7,665 cycles = 5,733 + 4 + 901 data + 1,027 control   CPI 1.337
forwarding, BTB and 2-bit counters     6,766 cycles = 5,733 + 4 + 901 data + 128 control   CPI 1.180
loop of 10, run 4 times: 1-bit misses  8 of 40   (the film: 8)
loop of 10, run 4 times: 2-bit misses  5 of 40   (the film: 5)

Cycles are instructions + 4 + bubbles exactly: forwarding removes the data waits except after a load, a target buffer with 2-bit counters removes most redirects, and a 2-bit counter misses a loop once per run where a 1-bit one misses twice.
The code (101 lines; it asserts its own result)
"""Lab 7: run a sort on Pebble's five-stage pipeline and account for every cycle above one per instruction."""

from videos.coursekit import labs

import numpy as np

from explainer.cs.pebble import assemble
from explainer.cs.pebble import predict as PR
from explainer.cs.pebble import programs as P
from explainer.cs.pebble.emu import run as emulate
from explainer.cs.pebble.pipe import Pipeline

TITLE = "Every bubble counted: a sort on the five-stage pipeline"
GOAL = ("Assemble an insertion sort of sixty random words, run it on the instruction emulator and on three pipelines "
        "(no forwarding, forwarding, forwarding with a target buffer and 2-bit counters), and check that each "
        "pipeline's cycles are instructions + 4 + the bubbles it reports. Then count a loop branch's misses under "
        "1-bit and 2-bit counters.")
TASKS = [
    "Sort an array that is already in order (values = sorted(values)). Which bubbles disappear, and which stay?",
    "Replace PR.TwoBit() by PR.GShare() and by PR.Perceptron(). Does either beat the counters on this sort?",
    "Change the loop trace to trips of 3 instead of 10. How do the 1-bit and 2-bit miss counts compare now?",
]

CONFIGS = [
    ("no forwarding, predict not taken", dict(forwarding=False, btb_entries=0, ras_depth=0)),
    ("forwarding, predict not taken", dict(btb_entries=0, ras_depth=0)),
    ("forwarding, BTB and 2-bit counters", dict()),
]


def misses(predictor, trace):
    """Where an online predictor is wrong on a branch trace [(pc, taken), ...]: predict, then update."""
    out = []
    for pc, t in trace:
        out.append(bool(predictor.predict(pc)) != t)
        predictor.update(pc, t)
    return np.array(out)


def pipelines(seed):
    rng = np.random.default_rng(seed)
    values = [int(v) for v in rng.integers(0, 1000, 60)]
    image = assemble(P.insertion_sort(values)).image
    ref = emulate(image, mem_size=8192)  # the emulator: the meaning of the program
    rows = []
    for name, kw in CONFIGS:
        if name.endswith("counters"):
            kw = dict(kw, predictor=PR.TwoBit())
        q = Pipeline(image, mem_size=8192, **kw).run()
        s = q.stats
        data = s["load_use"] + s["raw"]
        control = s["branch_flush"] + s["jump_redirect"] + s["jalr_flush"]
        assert q.regs == ref.regs and bytes(q.mem) == bytes(ref.mem), "the pipeline computes what the emulator does"
        assert q.retired == ref.steps
        assert q.cycles == q.retired + 4 + q.bubbles and q.bubbles == data + control, "every lost cycle is a counted bubble"
        rows.append((name, q, data, control))
    return values, ref, rows


def run(seed=0):
    values, ref, rows = pipelines(seed)
    lab = labs.Lab()
    n = ref.steps
    lab.row("instructions executed (emulator)", f"{n:,}")
    for name, q, data, control in rows:
        lab.row(name, f"{q.cycles:,} cycles = {n:,} + 4 + {data:,} data + {control:,} control   CPI {q.cpi:.3f}")
    cpis = [q.cpi for _, q, _, _ in rows]
    assert cpis[0] > cpis[1] > cpis[2] > 1, "forwarding, then prediction, each lower the CPI; none reaches 1"
    assert rows[1][1].stats["raw"] == 0 and rows[1][1].stats["load_use"] > 0, "forwarding leaves only load-use bubbles"

    # Chapter 7's loop: a branch taken nine times and then not, four times over
    trace = [(0x40, k % 10 != 9) for k in range(40)]
    m1, m2 = misses(PR.OneBit(), trace), misses(PR.TwoBit(), trace)
    lab.row("loop of 10, run 4 times: 1-bit misses", f"{m1.sum()} of 40   (the film: 8)")
    lab.row("loop of 10, run 4 times: 2-bit misses", f"{m2.sum()} of 40   (the film: 5)")
    assert m1.sum() == 8 and m2.sum() == 5
    lab.note = ("Cycles are instructions + 4 + bubbles exactly: forwarding removes the data waits except after a "
                "load, a target buffer with 2-bit counters removes most redirects, and a 2-bit counter misses a "
                "loop once per run where a 1-bit one misses twice.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    names = ["no forwarding", "forwarding", "forwarding,\nBTB + 2-bit"]
    base = np.ones(3)
    data = np.array([d / n for _, _, d, _ in rows])
    control = np.array([c / n for _, _, _, c in rows])
    ax[0].bar(names, base, color=labs.GREY, label="one cycle per instruction")
    ax[0].bar(names, data, bottom=base, color=labs.BLUE, label="data bubbles")
    ax[0].bar(names, control, bottom=base + data, color=labs.RED, label="flushes and redirects")
    for k, c in enumerate(cpis):
        ax[0].text(k, c + 0.03, f"CPI {c:.2f}", ha="center", color=labs.INK)
    ax[0].set(title=f"Insertion sort of {len(values)} words: cycles per instruction", ylabel="cycles per instruction",
              ylim=(0, max(cpis) + 0.45))
    ax[0].legend(loc="upper right")
    ks = np.arange(40)
    ax[1].step(ks, [t for _, t in trace], where="mid", color=labs.GREY, lw=1.2, label="outcome (1 = taken)")
    ax[1].scatter(ks[m1], np.full(m1.sum(), 1.35), color=labs.RED, marker="x", s=40, label=f"1-bit wrong ({m1.sum()})")
    ax[1].scatter(ks[m2], np.full(m2.sum(), 1.2), color=labs.GOLD, marker="o", s=30, label=f"2-bit wrong ({m2.sum()})")
    ax[1].set(title="A ten-trip loop branch, four runs", xlabel="branch execution", yticks=[0, 1], ylim=(-0.15, 2.1))
    ax[1].legend(loc="upper center", ncols=3)
    lab.fig = fig
    return lab

Now change it

  1. Sort an array that is already in order (values = sorted(values)). Which bubbles disappear, and which stay?
  2. Replace PR.TwoBit() by PR.GShare() and by PR.Perceptron(). Does either beat the counters on this sort?
  3. Change the loop trace to trips of 3 instead of 10. How do the 1-bit and 2-bit miss counts compare now?

Problems, with solutions

Try each problem before opening its solution.

  1. A load-use chart. Draw the pipeline chart for lw t0, 0(a0); add t1, t0, t0; sw t1, 4(a0) with forwarding. Where is the bubble, and which paths carry values?

    Solution
                   1    2    3    4    5    6    7    8
    lw  t0, 0(a0)  IF   ID   EX   MEM  WB
    add t1, t0, t0      IF   ID   ID   EX   MEM  WB
    sw  t1, 4(a0)            IF   IF   ID   EX   MEM  WB
    

    The add is held in ID for one cycle (cycle 4), and a bubble enters EX behind the load: its value exists only at the end of MEM. In cycle 5 the MEM/WB → EX path carries t0 into the add, and in cycle 6 the EX/MEM → EX path carries t1 into the store's data operand. Three instructions take 3 + 4 + 1 = 8 cycles.

  2. The cost of branches. 20% of instructions are branches, 60% of them taken. Predict-not-taken costs 2 cycles per taken branch; a predictor that is 95% right costs 2 per mistake. What CPI does each give?

    Solution

    CPI = 1 + branch fraction × miss rate × penalty. Predict-not-taken misses every taken branch: 1 + 0.2 × 0.6 × 2 = 1.24. The predictor: 1 + 0.2 × 0.05 × 2 = 1.02 (assuming the target buffer supplies the target of every correctly predicted taken branch). A 20-stage machine with a 15-cycle penalty would give 1 + 0.2 × 0.6 × 15 = 2.8 against 1 + 0.2 × 0.05 × 15 = 1.15: the deeper the pipeline, the more a predictor is worth.

  3. The best depth. Minimize T(k) = (t/k + o)(1 + b(k − 1)) to show k* = √(t(1 − b)/(b·o)). With t = 2560 ps and o = 70 ps, what is k* for b = 0.01 and for b = 0.1?

    Solution

    Multiply out: T = t/k + o + bt − bt/k + bok − bo = t(1 − b)/k + bok + (o + bt − bo). The constant does not depend on k, so dT/dk = −t(1 − b)/k² + bo, which is zero at k = √(t(1 − b)/(b·o))*; the second derivative 2t(1 − b)/k³ is positive, so it is a minimum. For b = 0.01: √(2560 × 0.99 / 0.7) ≈ 60 stages; for b = 0.1: √(2560 × 0.9 / 7) ≈ 18 stages. For small b the depth scales approximately as 1/√b; the exact expression also contains √(1−b). The Job's measured b = 0.0265 gives 37.

  4. Amdahl and Gustafson. 80% of a program can run in parallel. What speedup do 4, 16 and infinitely many processors give? What if the problem grows so the serial time stays fixed (Gustafson)?

    Solution

    Amdahl: S(n) = 1 / (0.2 + 0.8/n): 2.5 for 4 processors, 4.0 for 16, and 5 at most, however many. Gustafson measures the fractions on the parallel machine: if the serial part stays 20% of the run time there and the parallel work grows with n, the same work would take 0.2 + 0.8n on one processor, so the scaled speedup is 3.4 for 4 and 13.0 for 16, growing without limit. Both are right; they answer different questions (a fixed problem, or a fixed time).

  5. Build: hide the bubble. In the Job's scan loop, move one instruction so the load-use bubble disappears. Run chapter 1 on the pipeline: how many cycles do you save, and what is the new CPI?

    Solution

    The loop reads an entry's length and tests it at once:

    scan:   beq  a2, s1, insert
            lw   t1, 4(t0)       # same length?
            bne  t1, a1, next    # needs t1 now: one bubble per entry
    

    For this byte-array model, first prove that t0+4 is aligned, remains in allocated readable memory even at the insertion slot, and has no MMIO side effects. Then swap the first two instructions so the test fills the slot. Hoisting a potentially faulting or out-of-bounds load is not generally valid:

    scan:   lw   t1, 4(t0)       # read early only after proving address safety
            beq  a2, s1, insert
            bne  t1, a1, next
    

    On chapter 1 with the ledger's pipeline (forwarding, a BTB, a tournament predictor and a return stack) the load-use stalls fall from 124,112 to 28,699, the cycles from 995,654 to 952,210 (43,444 saved, 4.4%), and the CPI from 1.203 to 1.150, at the price of 331 more instructions (one extra load each time a word is added to the table). The output is unchanged. Part 13's compiler finds moves like this one by itself: instruction scheduling.

  6. ★ Research: close the gap. On the Job's chapter-1 branches our TAGE gets 94.3% in 9 KB and the unlimited PPM predictor 97.5%. How much of that gap can a 64 KB predictor close? Which branches stay wrong, and could anything but branch history predict them?

    What is known, and where to start. This is a heldout generalization problem. The known 254,436 outcomes need only 31,805 bytes plus an index to replay perfectly, within 64 KiB; predict-before-update alone does not prevent encoded future labels. Choose separate training, tuning and untouched test chapters, prohibit future-label encoding in code or initial state, and count all tables, histories, tags, validity, weights and metadata in the budget. Start from explainer/cs/pebble/predict.py and the trace from videos/cs/cs7/compute.py (trace_of(*benchmarks()["the Job, chapter 1"])); PR.accuracy scores any object with predict(pc) and update(pc, taken). Count mispredictions per static branch first. On this trace 68% of our TAGE's misses come from one branch, the scan loop's length test bne t1, a1, next (9,846 of 14,412); the letter comparison in cmp gives 15% and the letter-or-separator test 9%. The unlimited PPM predictor cuts the scan branch's misses to 2,120, because between insertions the table's sequence of lengths is fixed, so a long enough history pins down where the scan is.

    Three directions, each from the literature. (1) Better use of history: the full TAGE of Seznec's TAGE-SC-L (more tables, longer tags, alternate-prediction logic, a statistical corrector and a loop predictor) is the standard 64 KB baseline in the Championship Branch Prediction. (2) Path and position: the scan branch's outcome is a function of the loop counter a2 and the current word's length a1, which is not in the branch history at all. A predictor indexed by data values (Heil, Smith and Smith, "Improving branch predictors by correlating on data values", MICRO 1999) could predict it almost perfectly; the question is what such a predictor costs in hardware and whether it generalizes beyond this program. (3) Offline learning: train a small model per hard branch on one chapter and test it on another (Zangeneh et al., BranchNet, MICRO 2020). A careful answer reports accuracy on a different chapter from the one used for design, the storage in bits counted as the championship counts it, and which misses remain.

Notes and sources

Glossary

极限研究 limit study · 部分匹配预测 prediction by partial matching (PPM) · 线性可分 linearly separable · 熵率 entropy rate · 统计校正器 statistical corrector · 难预测的分支 hard-to-predict branch · 前端瓶颈 front-end bottleneck · 流水线 pipeline · 流水级 pipeline stage · 流水线寄存器 pipeline register · 吞吐量 throughput · 延迟 latency · 取指 / 译码 / 执行 / 访存 / 写回 IF / ID / EX / MEM / WB · 流水线图 pipeline chart · 冒险 hazard · 结构冒险 structural hazard · 数据冒险 data hazard · 控制冒险 control hazard · 写后读 RAW · 停顿 stall · 气泡 bubble · 转发 forwarding · 取数—使用冒险 load-use hazard · 冲刷 flush · 延迟槽 delay slot · 分支预测 branch prediction · 静态预测 static prediction · 饱和计数器 saturating counter · 全局历史 global history · 锦标赛预测器 tournament predictor · 感知机预测器 perceptron predictor · 分支目标缓冲器 branch target buffer (BTB) · 返回地址栈 return-address stack · 精确异常 precise exception · 每秒百万条指令 MIPS · 功耗墙 power wall · 登纳德缩放 Dennard scaling · 阿姆达尔定律 Amdahl's law · 古斯塔夫森定律 Gustafson's law · 无分支代码 branch-free code · 条件传送 conditional move

Sources

The reading list is split, as the research tier asks (videos/cs/SYLLABUS.md §1.1), into the qualifying-exam canon and recent work.

Canon. Books: Hennessy & Patterson, Computer Architecture: A Quantitative Approach, 6th ed., ch. 1 and 3 and Appendix C; Patterson & Hennessy, Computer Organization and Design, RISC-V Edition, ch. 1 and 4; Shen & Lipasti, Modern Processor Design, ch. 2 and 9; Harris & Harris, Digital Design and Computer Architecture, ch. 7; Fog, The microarchitecture of Intel, AMD and VIA CPUs (updated yearly).

Papers: Amdahl, "Validity of the single processor approach to achieving large scale computing capabilities", AFIPS (1967); Dennard et al., "Design of ion-implanted MOSFETs with very small physical dimensions", IEEE JSSC (1974); Smith, "A study of branch prediction strategies", ISCA (1981); Gustafson, "Reevaluating Amdahl's law", CACM (1988); Yeh & Patt, "Two-level adaptive training branch prediction", MICRO (1991); McFarling, "Combining branch predictors", DEC WRL TN-36 (1993); Jiménez & Lin, "Dynamic branch prediction with perceptrons", HPCA (2001); Hrishikesh et al., "The optimal logic depth per pipeline stage is 6 to 8 FO4 inverter delays", ISCA (2002); Seznec & Michaud, "A case for (partially) tagged geometric history length branch prediction", JILP (2006); Wall, "Limits of instruction-level parallelism", ASPLOS (1991); Cleary & Witten, "Data compression using adaptive coding and partial string matching", IEEE Trans. Comm. (1984); Chen, Coffey & Mudge, "Analysis of branch prediction via data compression", ASPLOS (1996); Minsky & Papert, Perceptrons (1969).

Recent work. Jiménez, "Piecewise linear branch prediction", ISCA (2005); Heil, Smith & Smith, "Improving branch predictors by correlating on data values", MICRO (1999); Kanev et al., "Profiling a warehouse-scale computer", ISCA (2015); Seznec, "TAGE-SC-L branch predictors again" and Jiménez, "Multiperspective perceptron predictor", 5th Championship Branch Prediction (2016); Zangeneh, Pruett, Lym & Patt, "BranchNet: a convolutional neural network to predict hard-to-predict branches", MICRO (2020).

About this partfrom its README

Part 7 of the sixty-one-part course (plan, syllabus) opens Act II, Making It Fast. It is the pilot of the series' watch standard (syllabus §1.2). The film opens on a loop that runs twelve times slower on shuffled data than on sorted data, measured on the rendering machine, and answers it in chapter 14. Every chapter asks a prediction first. The caveats the film shows only as source tags (assumed, simulated, measured) are stated in full below. A functional cycle-by-cycle Pebble model overlaps instructions through five stages. Finite tests compare selected programs/configurations with the instruction emulator. It is not a physical gate pipeline: memory delays, mux/control estimates and register overhead define an assumed teaching clock budget. The M-extension latencies are modeled, motivated by earlier arithmetic circuits.

  • Performance accounting: time = instructions × CPI × clock period. The same Job chapter uses 827,576 instructions; measured model CPI and assumed periods give its projected speedup. MIPS alone can mislead.
  • Throughput versus latency: equal stages give speedup (t+o)/(t/k+o) with limit 1+t/o. Register overhead increases instruction latency. The assumed five-stage period is 1,130 ps versus 2,630 ps single-cycle. The depth optimum assumes equal splittable work, fixed miss fraction and k−1 penalty; compare feasible integer depths near the continuous optimum. Historical Pentium 4 depths do not validate it.
  • Structural and data hazards: one coherent byte array has two ideal logical access ports. Division occupies EX for 16 modeled cycles. Forwarding prioritizes the newest producer, ignores zero-register writes and cannot forward unavailable load data. A load produces at end-MEM while the next consumer needs start-EX in the same cycle; these are different instants. Write-back-before-decode is a simulator policy.
  • Branches and targets: counter startup, aliasing, gshare, our bimodal/gshare tournament, simplified TAGE, and indexed perceptron weights. A counter's failure does not test all local-history models. Classic MIPS delay slots were removed in Release 6. Warm correct BTB hits and balanced recognized calls explain modeled benefits; neither guarantees free branches or perfect returns.
  • Precise exceptions: committed architectural state has a precise boundary; cache/predictor effects are separate. Pebble stops and reports a fault PC, with no OS resume implementation. Its divide-zero fault differs from RISC-V M's defined result. fence.i orders same-hart instruction fetch; multicore/migration requires the specified wider protocol. The deliberate stale-code example has no instruction-fence implementation.
  • The Job: six instructions/seven cycles describes the mismatched-length fast path with warm correct prediction. Full search includes letter comparisons. The corpus row is a fitted extrapolation from 24 passages, checked on one 16,000-character heldout text (16,019 encoded bytes); that check supplies no full-corpus error bound. Projected runtime also assumes the teaching clock.
  • Power and Amdahl: dynamic αCV²f excludes leakage. Lower VDD slows circuits; lower threshold to retain speed raises leakage. Fixed-work Amdahl fractions are baseline time fractions. Search is 99.7% of single-cycle instructions; deleting it at no replacement cost gives a roughly 350× ceiling only in that uniform-cost model, not a measured pipeline bound. Pipeline speedup is clock ratio divided by CPI ratio.
  • Sorted arrays: fixed-seed irregular and sorted orders preserve the sum. Host bars read current cached five-run medians; no historical Xeon timings are narrated. Sorting/generation are excluded; 300 passes reuse the same array. Compiler options, output observability and machine dependence are recorded. Timing alone does not isolate branch prediction. Branchless masking uses (x<128)-1 in the word model and can do more work.
  • Frontier: report empirical one-trace curves and nominal packed table payload, excluding history, validity and implementation overhead. PPM-style context tables grow over configured lengths up to 64. Its algorithm differs from TAGE, so the gap does not isolate storage or establish an impossibility bound. Hindsight majority is an offline oracle for a chosen feature class. Compression relates probabilities/log loss to code length, not directly to an accuracy ceiling. XOR has no perfect fixed affine separator of its two input bits, but a fixed line can classify 3/4 of uniform cases; this run's 49% is not a theorem. Piecewise-linear and multiperspective predictors use different feature constructions. TAGE-SC-L combines components; BranchNet evaluates offline convolutional training on unseen inputs. Research exercises specify heldout evaluation.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. The iron law, derived as a product of ratios; the MIPS myth.
  2. Pipelining as laundry: throughput against latency; why the ideal speedup k is never reached; the optimal pipeline depth (overhead against hazard penalty, derived).
  3. The 5-stage Pebble pipeline built (IF ID EX MEM WB), with its pipeline registers.
  4. Structural hazards.
  5. Data hazards: RAW; stalls; forwarding paths drawn; the load-use stall.
  6. Control hazards: the branch penalty; MIPS's delayed branch as a historical choice.
  7. Branch prediction: static; 1-bit against 2-bit saturating counters (Part 5's FSMs); accuracy measured on the Job's branch trace.
  8. Correlating predictors:
    • global history and gshare;
    • tournament predictors;
    • TAGE, with geometric history lengths (Seznec);
    • the perceptron predictor (Jiménez & Lin 2001), a neural network inside every CPU (callback to AI, Built).
  9. Branch target buffers and return-address stacks.
  10. Precise exceptions in a pipeline.
  11. The Job's CPI on the cycle-accurate pipeline, with its stall breakdown. Ledger row 1.
  12. The deep-pipeline era and its end: the Pentium 4's 31 stages, the frequency race, and the power wall (Part 10).
  13. Amdahl's law, derived, with its corollaries.
  14. The sorted-array puzzle, measured on this machine: why sorting data makes a branchy loop several times faster; branchless code and conditional moves.
  15. Outro.

Computed: the cycle-accurate pipeline; CPI breakdowns; 1-bit, 2-bit, gshare, TAGE-lite and perceptron accuracy on traces of the Job and other programs; sorted against unsorted branches timed on this machine. Visuals: the pipeline chart with bubbles, forwarding arrows and flushes; predictor state machines flipping; the perceptron's weights as a heatmap over branch history. In practice: performance work with hardware counters (perf stat: IPC, branch misses); branchless code in databases, codecs and trading systems. Reading: Patterson & Hennessy ch. 4; Hennessy & Patterson, Computer Architecture: A Quantitative Approach ch. 3, App. C; Shen & Lipasti, Modern Processor Design; Smith 1981; Yeh & Patt 1991; McFarling 1993; Seznec & Michaud 2006; Jiménez & Lin 2001; Amdahl 1967.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. 取数—使用的流水线图。 在有转发的情况下,画出 lw t0, 0(a0)、add t1, t0, t0、sw t1, 4(a0) 的流水线图。气泡在哪里? 哪些通路传送数值?

    解答

    流水线图见上文英文部分。add 在 ID 级多停一个周期(第 4 周期),一个气泡跟在取数指令后面进入 EX:它的值要到 MEM 结束才有。第 5 周期,MEM/WB → EX 通路把 t0 送进 add;第 6 周期,EX/MEM → EX 通路把 t1 送进存数指令的数据操作数。 三条指令共用 3 + 4 + 1 = 8 个周期。

  2. 分支的代价。 20% 的指令是分支,其中 60% 跳转。"预测不跳转"每遇到一次跳转损失 2 个周期;一个正确率 95% 的预测器每次猜错 损失 2 个周期。两者的 CPI 各是多少?

    解答

    CPI = 1 + 分支比例 × 猜错率 × 代价。"预测不跳转"错在每一条跳转的分支:1 + 0.2 × 0.6 × 2 = 1.24。预测器: 1 + 0.2 × 0.05 × 2 = 1.02(假设分支目标缓冲器为每条预测正确的跳转分支提供目标地址)。一台代价为 15 个周期的 20 级流水线 机器则是 1 + 0.2 × 0.6 × 15 = 2.8 对 1 + 0.2 × 0.05 × 15 = 1.15:流水线越深,预测器越值钱。

  3. 最佳深度。 求 T(k) = (t/k + o)(1 + b(k − 1)) 的最小值,证明 k* = √(t(1 − b)/(b·o))。取 t = 2560 ps,o = 70 ps,b = 0.01 和 b = 0.1 时 k* 各是多少?

    解答

    展开:T = t(1 − b)/k + bok + (o + bt − bo),常数项与 k 无关,所以 dT/dk = −t(1 − b)/k² + bo,在 k = √(t(1 − b)/(b·o))* 处为零;二阶导数 2t(1 − b)/k³ 为正,所以是最小值。b = 0.01 时约 60 级;b = 0.1 时约 18 级。当 b 很小时,深度近似与 √b 成反比;精确式还含 √(1−b)。用任务实测的 b = 0.0265 得到 37。

  4. 阿姆达尔与古斯塔夫森。 一个程序 80% 可以并行。4 个、16 个、无穷多个处理器各带来多少加速?如果问题随之变大、使串行时间保持 不变(古斯塔夫森),又如何?

    解答

    阿姆达尔:S(n) = 1 / (0.2 + 0.8/n):4 个处理器 2.5,16 个 4.0,无论多少个最多 5。古斯塔夫森在并行机器上 度量比例:如果串行部分在那里始终占运行时间的 20%,而并行工作随 n 增长,同样的工作在单处理器上要 0.2 + 0.8n,于是按规模放大的 加速是 4 个 3.4、16 个 13.0,没有上限。两者都对,回答的是不同的问题(问题固定,还是时间固定)。

  5. 动手:藏起气泡。 在任务的扫描循环里移动一条指令,让取数—使用气泡消失。在流水线上运行第 1 章:省下多少周期?新的 CPI 是多少?

    解答

    循环读出条目的长度后立刻检查它(代码见上文英文部分)。先证明 t0+4 对齐、即使到插入位置仍在已分配可读内存中,且没有设备访问副作用。只有在这些条件下才能把前两条指令对调,让取数在"表结束了吗"的检查之前发出,由这个 检查填补空档。在第 1 章上,用账本所用的流水线(转发、分支目标缓冲器、锦标赛预测器和返回地址栈),取数—使用停顿从 124,112 次 降到 28,699 次,周期从 995,654 降到 952,210(省下 43,444,4.4%),CPI 从 1.203 降到 1.150,代价是多执行 331 条指令 (每往表里加一个词就多一次取数)。输出不变。第 13 部分的编译器会自己找到这样的移动:指令调度。

  6. ★ 研究题:缩小差距。 在任务第 1 章的分支上,我们的 TAGE 用 9 KB 达到 94.3%,不限存储的 PPM 预测器达到 97.5%。一个 64 KB 的预测器能把这个差距缩小多少?哪些分支仍然猜错?除了分支历史,还有什么能预测它们?

    已知什么,从哪里入手。 这是留出泛化问题。已知的254,436次结果只需31,805字节加索引,就能在64二进制千字节内完美重放;先预测再更新本身不能阻止编码未来标签。必须分开训练、调参与未使用测试章节,禁止代码或初值编码未来测试结果,并把表、历史、标记、有效位、权重与元数据全计入预算。从 explainer/cs/pebble/predict.py 和 videos/cs/cs7/compute.py 里的轨迹入手(trace_of(*benchmarks()["the Job, chapter 1"]));PR.accuracy 可以给任何带 predict(pc) 和 update(pc, taken) 的对象打分。先按静态分支统计预测错误。在这条轨迹上,我们的 TAGE 有 68% 的错误来自同一条 分支,即扫描循环里的长度检查 bne t1, a1, next(14,412 次中的 9,846 次);cmp 里的字母比较占 15%,字母还是分隔符的检查占 9%。不限存储的 PPM 把扫描分支的错误降到 2,120 次,因为在两次插入之间表里的长度序列是固定的,足够长的历史就能确定扫描进行到了哪里。

    文献中有三个方向。(1)更好地利用历史:塞兹内克 TAGE-SC-L 的完整 TAGE(更多的表、更长的标签、备选预测逻辑、统计校正器和循环 预测器)是分支预测锦标赛 64 KB 赛道的标准基线。(2)路径与位置:扫描分支的结果是循环计数器 a2 和当前单词长度 a1 的函数, 而它们根本不在分支历史里。按数据值索引的预测器(Heil、Smith 和 Smith,《通过与数据值相关来改进分支预测器》,MICRO 1999)可以提供有用特征;问题在于这样的预测器在硬件上要花多少,以及它能否推广到这个程序之外。(3)离线学习:在一章上为每条难预测的分支训练 一个小模型,在另一章上测试(Zangeneh 等,BranchNet,MICRO 2020)。一个认真的回答应当报告在设计时没有用过的另一章上的准确率、按锦标赛 规则以比特计算的存储,以及还剩下哪些错误。

Build the film

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

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

Build it
python -m videos.cs.cs7.compute            # every number in the part (about ten minutes; the Job's fit is the slow step)
python tools/build.py cs7 -q l             # a 480p preview
python tools/build.py cs7                  # 1080p

The sorted-array timings are measured by compiling a small C program with the system compiler (-O1 with if-conversion and vectorization turned off, so the branch survives) and are machine-specific; the scene reads the CPU name from /proc/cpuinfo. Ledger rows 0 and 1 are written to .cache/cs7/ledger.json.