Parallel Machines
When the clock stopped getting faster, what did more cores buy, and what did they cost?
Fifty years of microprocessors on one chart: around 2005 the clock and power curves bend and a new curve, the number of cores, appears. Dynamic power is activity times capacitance times voltage squared times frequency, Dennard's scaling kept power density constant only while the voltage fell, and when it stopped falling two slower cores became a better buy than one fast one. The condition is that the work divides. The Job is cut into four shards with private tables and a partitioned merge, and the trouble of shared memory is met in order: private caches that disagree and the MESI protocol that reconciles them, false sharing measured on this machine, store buffers that let both threads of a litmus test read zero, and the atomic instructions locks are built from. SIMD and the GPU are the other answers. The part then turns to theory that fixes no machine: work and span, Brent's theorem with its proof, parallel prefix (Part 4's carry tree again), sorting networks and the 0-1 principle, Amdahl against Gustafson, PRAM, BSP and network shapes. The Job's four-core projection is about 12 seconds against 57, more than four times faster, because shorter tables mean less work. The frontier is values out of thin air, work-stealing constants and energy.
What you need. Programming with loops and arrays, logarithms, and proof by counting.
- Mathematics, ideas and history
- the power wall, MESI, memory consistency, SIMD, work–span and Brent, parallel scan, sorting networks and the 0–1 principle
- What we build or compute
- multicore Pebble; false sharing measured
What you will be able to do
Degree
- Explain with the dynamic power formula why two cores at 80% of the clock can replace one at full speed, and what that assumes.
- Trace a cache line through MESI states for a short sequence of reads and writes by several cores, counting invalidations.
- Compute a computation's work, span and parallelism, and its speedup limits under Amdahl and Gustafson.
Graduate
- Prove Brent's theorem by counting complete and incomplete steps, and prove the 0-1 principle.
- Enumerate the outcomes of the store-buffering test under sequential consistency and under total store order, and place fences that forbid the relaxed outcome.
- Run Blelloch's scan by hand, count its additions, and use a scan to compact an array.
Research
- Explain why out-of-thin-air values are hard to forbid in a language memory model without forbidding compiler reorderings.
- State what the work-stealing bound leaves out (the constant, locality, space), and design a simulation that measures one of them.
Industry
- Find and remove false sharing: pad or separate per-thread data, and confirm with a cache-to-cache profile.
- Choose between threads, SIMD and a GPU for a loop from its dependencies, branches and memory pattern, and report strong and weak scaling separately.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 23 min · Graduate 50 min · Research 52 min · Industry 30 min.
- 0The clock stopsDegree2 min
- 1The power wallDegree4 min
- 2Four cores, one JobDegree3 min
- 3Cache coherenceDegree3 min
- 4False sharingIndustry2 min
- 5Memory consistencyGraduate3 min
- 6Atomic instructionsGraduate3 min
- 7SIMD and vectorsIndustry2 min
- 8GPUs in one chapterIndustry3 min
- 9Work, span and Brent's theoremDegree5 min
- 10Parallel prefixGraduate4 min
- 11Sorting networksGraduate4 min
- 12Amdahl and GustafsonDegree3 min
- 13Models and networksGraduate3 min
- 14The Job on four coresGraduate3 min
- 15Frontier: thin air, stealing, dark siliconResearch2 min
- 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.
The clock stopsDegree2 min
Here are fifty years of microprocessors, each dot one chip, on a logarithmic scale. Across this historical sample, transistor counts rise roughly exponentially. Moore described a manufacturing trend, not a physical law or a promise for every chip. The speed of a single thread followed it for thirty years. So did the clock: from under a megahertz to over three gigahertz, roughly a third faster per year in the fitted 1985 to 2004 sample. And power rose with them, to about a hundred watts. Then, around 2005, three of the curves bent. Clock growth slowed sharply in the later sample. Power budgets constrained further scaling, while single-thread performance continued improving more slowly. And a new curve appeared: the number of cores. The transistors kept coming, and designers increasingly spent them on more cores, larger caches and specialized units.
And the Job. On one of Part 8's out-of-order cores, the fitted corpus model projects about fifty-seven seconds to count thirty novels. With four cores, the plan is simple: give each core a word-aligned quarter of the text, let each count its own, and combine the four sets of counts. The obvious way of combining them throws away much of what the cores gained. With partitioned merging, the cost model projects nearly five times the one-core speed. More than four times faster, on four cores. By the end of this part you will know how changing the total work produces that apparent superlinear gain, and which costs the projection leaves out.
Here is the route from hardware limits to correct parallel programs. First, the power wall and why rapid clock scaling slowed. Then shared memory: a coherence protocol simulated step by step, followed by host measurements of false sharing and store buffering. Next, SIMD inside a core and the throughput-oriented GPU. Then the theory: work and span, a scheduling bound, scans and sorting networks. Finally, the Job on four cores: a conditional model and a separate compiled host experiment, with their costs kept explicit.
1The power wallDegree4 min
Where does a chip's power go? Mostly into one formula. Each time a transistor switches, it charges or discharges a tiny capacitance C through the supply voltage V, and that costs energy C V squared. Alpha represents switching activity, with C interpreted as the corresponding effective capacitance, and there are f cycles a second. So the dynamic power is alpha C V squared f. On top of that is leakage: transistors are not perfect switches, and some current flows through them even when they are off. The strong voltage dependence and leakage explain why simple frequency scaling became much harder.
In 1974 Robert Dennard and his colleagues at IBM worked out what happens when you shrink a transistor. Scale every dimension down by a factor kappa. Scale the voltage down by the same factor, so the electric fields inside stay the same. Then the capacitance falls by kappa too, and the transistor switches kappa times faster, so the clock can rise by kappa. Put those into the formula: the power of one transistor falls by kappa squared. But kappa squared as many fit in the same area. So the power per square millimetre stays the same in this ideal constant-field model, holding switching activity fixed. With kappa about one point four each generation, the model suggests twice the transistors and forty percent more frequency at constant power density. Real improvements also depended on circuits, architecture and software; the scaling rule explains one major source of that progress.
Why did it end? Because the voltage stopped falling. A transistor switches fast only if the supply voltage is well above its threshold voltage, the point where it turns on. So to lower V, you must lower the threshold too. But below its threshold a transistor is not quite off: the current through it falls only tenfold for every sixty to a hundred millivolts, the familiar thermal subthreshold slope for conventional field-effect transistors at room temperature. Lower the threshold, and leakage grows exponentially. By about 2005 supply voltages had settled near one volt, and further reductions became much harder; operating voltages still vary by process and operating point. With the voltage fixed, the formula turns against you: each generation packs twice the transistors into the same area, and if the clock still rose, the power per area would grow. A hundred watts is a useful historical desktop scale, not a universal limit: modern servers and accelerators can consume much more. Cooling and energy budgets helped end rapid clock scaling.
So the industry turned the formula around. For a simple illustration, suppose frequency is proportional to voltage and ignore leakage and other fixed costs. This is an approximation, especially poor near threshold. So lowering both together cuts power with the cube of the clock. Take one core at full speed: one unit of power, one unit of work a second. Now two cores, each at eighty percent of the clock and voltage: each draws point eight cubed, about half the power, so the pair draws about the same as the one. But together they do one point six units of work. Sixty percent more, for approximately the same dynamic power in this toy model, with one condition that changes everything: the work has to be divided between them. In 2005 both Intel and AMD shipped their first dual-core processors, and the rest of this part is about that condition.
2Four cores, one JobDegree3 min
A multicore chip is several complete processors on one piece of silicon. In our example, each core has its own pipeline, registers and private caches; actual sharing hierarchies vary. They share a larger cache, and behind it one memory: the threads share an address space, subject to protection and the machine memory model. That sharing is the convenience and the danger. It is convenient because threads of one program can pass data by simply writing it to memory. It is dangerous because each core keeps copies of memory in its private caches, and two cores can disagree about what an address holds. Chapters three to six are about that danger. First, the Job.
Here is the plan. Cut the text into four pieces of equal size, at word boundaries. Each core counts the words of its piece, using Part 6's linear-scan counting algorithm in an abstract feature model, in a table of its own. While they count, no core ever writes anything another core reads, which removes conflicting table updates. Shared input, allocation, boundaries and the final synchronization still need care. Then the four tables must be combined into one, before selecting the top twenty. The estimate prices counting and selected merge insertions on four of Part 8's cores at Pebble's clock, with the same model of the core that gave the ledger its fifty-seven seconds. It omits routing and hashing scans, communication, coherence, bandwidth contention, barriers and final output; it is a conditional compute-cost projection, not a full multicore execution.
Now the four tables have to become one. The obvious way: when all four are done, core zero takes each entry of the other three tables and looks it up in its own, adding the count or appending the word. But every lookup is a scan of a table that grows to fifty-eight thousand entries, and there are ninety thousand lookups: 8 seconds of one core working while three wait. A tree is no better: two merges at once, then a final one, and the final merge of two big tables costs nearly as much as before. The way that works is to split the combining by word instead of by table. Give every word a number from zero to three by a simple rule, here the sum of its letters, and let core k merge, from all four tables, only the words whose number is k. Each core builds a quarter of the final table, so its scans are a quarter as long, and four run at once. The merge shrinks to about 0.6 seconds.
3Cache coherenceDegree3 min
First imagine private caches without a working coherence protocol. Two cores, each with a private cache, and one variable x in memory, holding zero. Both cores read x. Each cache now keeps its own copy. Core zero writes one to x. With a write-back cache, the new value goes into core zero's cache, and memory still says zero. Now core one reads x again. It finds x in its own cache, a hit, and gets zero: a value that was overwritten some time ago. If x were a flag saying the data is ready, a cached stale copy could prevent progress. This deliberately broken example does not describe correctly synchronized code on a coherent machine. Caches made private copies of a shared memory, and the copies have come apart.
A coherence protocol makes the copies behave as if there were only one. It keeps two promises. The first: at any moment, for each cache line, either a single cache is allowed to write it, or any number of caches may read it, but never both. The second: writes to one address have a coherent order, and reads respect that order and the required synchronization. Our sequential simulator returns the last completed write. This does not impose a single order across different addresses. To keep them, every cache must learn what the others are doing to the lines it holds. On a small chip every cache can watch, or snoop on, a shared bus that carries every miss. On a big one, a directory keeps track of who holds what.
The protocol inside most multicore chips descends from MESI, published by Mark Papamarcos and Janak Patel in 1984. Each line in each cache is in one of four states. Modified: this cache has the only copy, and it is newer than memory. Exclusive: the only copy, but clean. Shared: clean, and other caches may have it too. Invalid: not here at all. Now the transitions for this core's own accesses. A read miss asks the bus: if no one else has the line, it arrives Exclusive; if others do, Shared. A write needs the only copy: from Invalid, a read for ownership; from Shared, an invalidation of every other copy; and from Exclusive, nothing at all. That silent upgrade is why E exists: most data is private, and a private line can be written without asking anyone. And the transitions forced by other cores. When another core reads a line this cache holds Modified, this cache supplies the data and both end Shared. When another core writes, every other copy becomes Invalid.
4False sharingIndustry2 min
Here is a trap that catches experienced programmers. Four threads each count something, in an array of four counters, one per thread. No two threads ever touch the same counter, so there is no real sharing at all. But coherence does not work in variables. It works in cache lines, and all four counters fit in one sixty-four-byte line. To increment its counter, a core needs that line in the Modified state, which means taking it away from whichever core had it last. Each thread performs fifty million atomic increments. Ownership transfers when another core needs the line; several local increments may occur before it moves again, so transfers need not equal increments. This is false sharing: the hardware sees sharing where the program has none.
Here it is, measured on this computer. Each thread increments its own counter fifty million times, and we divide elapsed wall time by the fifty million increments per thread. This is a per-thread completion interval, not aggregate time per increment across all threads. One thread alone: 2.3 nanoseconds in this run, the cost of an atomic add on a line the core already owns. Give each counter a line of its own, by padding it to sixty-four bytes, and the chart shows how much this run improves. Padding removes false sharing between counters, but scheduling, frequency and shared resources still affect time. Put the four counters in one line, and contending cores repeatedly transfer ownership. With four threads, each increment takes 22 nanoseconds, 9 times the padded four-thread interval, though no thread ever reads another's counter.
5Memory consistencyGraduate3 min
Coherence is about one address at a time. But programs communicate through several: write the data, then set a flag. In what order do other cores see those writes? In 1979 Leslie Lamport gave the answer programmers assume without thinking. A multiprocessor is sequentially consistent if every execution gives the same result as some single interleaving of all the threads' operations, with each thread's operations in its program order. Here is the test that probes it, called store buffering. Thread zero sets x to one, then reads y. Thread one sets y to one, then reads x. Both start at zero. Can both threads read zero?
Under sequential consistency we can simply list the possibilities. Each thread's two operations stay in order, and the four can be interleaved in six ways. Here they are, with what each thread reads. In every one of them, one of the two stores comes first, and the other thread's load comes after it, so at least one thread reads one. Both reading zero is impossible. Our simulator, running two hundred thousand random interleavings, agrees: it never happens.
Real processors do not wait for stores. When a core executes a store, it puts the address and value in a small queue, the store buffer, and carries on; the store reaches the cache when its line arrives, perhaps a hundred cycles later. Part 8's teaching core also used buffered stores, without implementing a complete multicore TSO model. So thread zero's store of x sits in core zero's buffer, and thread one's store of y in core one's. Now each core loads the other variable. Neither store has reached memory, so both loads read zero. Then the buffers drain, and memory ends with both ones, too late. Each core still sees its own store, because its loads check its own buffer first. But other cores see it late. This is the memory model of x86, called total store order: stores become visible in program order, but a load can overtake an earlier store to a different address.
We ran this test a million times with two worker threads. They are released each trial by an acquire-release handshake, without pinning them to particular cores. The shared x and y use separate relaxed atomic loads and stores: these are defined C operations, not volatile data races. Both reads were zero in 864,425 trials. The observed frequency depends on timing and scheduling; an allowed outcome need not appear in every run. The second run inserts x86 mfence after each worker's store. Under the stated ordinary-memory assumptions, that blocks this store-buffering outcome. The chart reports what was observed. A fence here orders these accesses; arbitrary fences do not automatically make a whole C or C++ program sequentially consistent.
6Atomic instructionsGraduate3 min
Coherence keeps the caches in agreement about each line. It does not make a sequence of operations indivisible. In our defined C demonstration, a relaxed atomic load, local addition and separate relaxed atomic store form three steps. Each access is atomic; their combination is not an atomic increment. Thread zero loads five. Before it stores, thread one also loads five. Both add one; both store six. Two increments, and the counter went up by one. On this computer, four threads each adding one to a shared counter ten million times end with a count of between 12 and 18 million, out of forty. The counts shown are measured outcomes, not a guaranteed lost fraction. Using an ordinary non-atomic C variable for this race would instead make the program undefined.
The fix needs the hardware's help: instructions that read, modify and write a location as a single step no other core can interrupt. The oldest is test-and-set, on IBM's System/360 in 1964: atomically test and set the high bit of a byte, reporting its previous condition. Our pseudocode shows an abstract lock flag. A lock is a word that test-and-set turns from zero to one; whoever got zero back holds the lock. Fetch-and-add adds to a word and returns the old value: exactly the counter, in one instruction. Compare-and-swap stores a new value only if the word still holds the value you expect, and reports whether it did. And load-linked and store-conditional split it in two: a store-conditional can succeed only while its reservation remains valid. It may fail for other reasons too, so code must retry. Implementations differ. A cache-coherent read-modify-write can obtain exclusive ownership while updating the line; LL/SC uses reservations, and some operations use other mechanisms. Coherence alone does not make a multi-instruction sequence atomic.
Here are four correct counters, timed on this host with their final counts checked. The vertical unit is elapsed nanoseconds per aggregate increment, unlike the previous chapter's per-thread interval. With one thread, the split relaxed load-store counter takes 1 nanoseconds per increment. Fetch-and-add, a compare-and-swap retry loop, a mutex and a simple test-and-set spinlock have the costs in the chart. These timings include the surrounding loop and implementation overhead, not just instruction latency. Four threads contend for one counter. Ownership transfers, retries, scheduling and lock behavior all matter. Fetch-and-add performs one atomic update per call; CAS may retry, and a test-and-set spinlock may generate heavy traffic while waiting. The ranking belongs to this benchmark and this run. Reducing shared updates is often a larger improvement than choosing a cheaper primitive.
7SIMD and vectorsIndustry2 min
In 1966 Michael Flynn classified computers by instruction streams and data streams. One instruction stream and one data stream is the simple SISD abstraction. A modern CPU can combine this execution model with vector instructions and other forms of parallelism. Multiple independent instruction streams working on different data give MIMD: multiple cores or machines. SIMD applies one instruction to a vector of logical data lanes. It amortizes instruction control across those elements. The implementation chooses how wide instructions map onto its execution hardware.
Here is SIMD applied to the Job. Most of its time goes into scanning the table, and most entries are rejected on their length alone. So keep the lengths in an array of their own, one byte each: Part 9's structure of arrays. Copy the length of the word being looked up into all thirty-two lanes of a 256-bit register. One AVX2 instruction compares all thirty-two pairs at once, and another squeezes the results into a thirty-two-bit mask. Only the entries whose bit is set, here 7, are compared letter by letter. One iteration of the loop now does the work of thirty-two.
We wrote the Job in C with the same linear-scan dictionary strategy but a different data layout and implementation, ran it on all thirty novels on this computer, and checked its top twenty against the reference. The scalar version, one entry per iteration, takes seconds. The AVX2 version takes . times faster, not thirty-two, and the reasons are instructive. Entries with the same length as the word still need a letter-by-letter comparison. And the rest of the program is not vectorized at all. Early exits and candidate comparisons make automatic vectorization harder. Here we explicitly use AVX2 intrinsics.
8GPUs in one chapterIndustry3 min
A graphics processor makes the opposite bargain from a CPU. A CPU spends its transistors on making a few threads as fast as possible: out-of-order execution, branch prediction, deep caches, everything in Parts 7, 8 and 9. A GPU spends them on arithmetic. It has thousands of simple lanes, grouped into streaming multiprocessors, using throughput-oriented warp scheduling rather than the large speculative out-of-order machinery of a CPU. Modern GPUs still have substantial caches and sophisticated scheduling. But there are tens of thousands of threads, and when one waits for memory, the hardware simply runs another, the multithreading of Part 8 taken to the extreme. As a dated hardware example, the 2022 Nvidia H100 SXM has a hundred and thirty-two multiprocessors and nearly seventeen thousand lanes, fed by stacked memory at over three terabytes a second.
The programming model is called single instruction, multiple threads. You write the code for one thread, as if it ran alone, and launch thousands of copies, each with its own index. In this Nvidia-style example, the hardware groups them in warps of thirty-two, which share one instruction stream: at each step, the same instruction for all thirty-two lanes. So what happens at an if? Some lanes want one branch and some the other. The warp runs the first branch with the other lanes switched off, then the second branch with the first lanes switched off. This is the masked-execution picture of divergence. Actual scheduling, predication and reconvergence depend on the GPU; other vendors can use different subgroup widths.
So GPUs shine on a particular kind of work. The same arithmetic on millions of independent items: pixels, particles, the entries of a matrix. Memory read in wide, regular blocks, so that the thirty-two loads of a warp merge into a few cache lines. And matrix multiplication above all: modern GPUs have tensor cores that multiply small matrices in a single instruction, which is why they run the neural networks of AI, Built. The Job, as written, is the opposite: one long chain of lookups, each a scan whose length depends on the data. One GPU-friendly alternative is sorting words and counting the runs; hashing is another option, and Part 16 develops the sorting approach.
9Work, span and Brent's theoremDegree5 min
To reason about parallel programs without fixing a machine, draw the computation as a graph. Each node is a unit of work. Each arrow says one node must finish before another starts. On the left, four numbers summed as a tree; on the right, a chain of steps, each needing the one before. Two numbers describe it. The work, T one, is the total number of nodes: the time on one processor, here fourteen. The span, T infinity, is the longest path: the time on infinitely many processors, here seven, along the chain. Their ratio, the parallelism, is average available parallelism along an ideal span-length execution, here two. Some steps can have more ready work; the ratio is not a maximum instantaneous width. And they give two lower bounds for any machine with p processors. It can do at most p nodes a step, so it needs at least T one over p steps. And the nodes of a path must run one after another, so it needs at least T infinity.
A schedule decides which nodes run at each step. The simplest good rule is greedy: at every step, if any node is ready, because everything it depends on has finished, never leave a processor idle. Here is a greedy schedule on two processors. Step by step, up to two ready nodes run. Notice the steps where only one node was ready, and a processor had to wait: they all come from the chain. The schedule takes 10 steps, against lower bounds of seven from the work and seven from the span. The best possible schedule, which starts the chain at once, needs eight: the bounds are not always reachable, but as the next theorem shows, greedy is never far from them.
How much worse than the lower bounds can a greedy schedule be? Not much, and the proof fits on a slide. The theorem, from Richard Brent in 1974 and in scheduling form from Ronald Graham in 1966: any greedy schedule on p processors finishes within T one over p, plus T infinity. Call a step complete if all p processors are busy, and incomplete otherwise. Each complete step does p units of the total work, so there are at most T one over p of them. In an incomplete step, fewer than p nodes were ready, so greedy ran every one of them. Now look at the longest path through the work that remains. Its first node is ready, because everything before it is done, so it runs in that step, and the longest remaining path gets one shorter. That can happen at most T infinity times. Add the two kinds of step, and the theorem is proved. Since the larger of T one over p and T infinity is a lower bound for every schedule, greedy is always within a factor of two of the best possible.
Greedy assumes someone hands out the ready nodes. Real runtimes cannot afford a central list that every core fights over, so they use work stealing. Each core keeps its own double-ended queue of tasks and works on the newest. When a task spawns another, the new one goes on the same core's queue. A core with nothing to do picks another core at random and steals the oldest task from its queue, which tends to be a big one. In 1999 Robert Blumofe and Charles Leiserson proved, for fully strict computations under their scheduler and cost assumptions, an expected bound of T one over p plus a constant times T infinity, in expectation, with expected steal attempts bounded by order p times the span. This is an upper bound under a specific model, not a universal claim about communication. Our simplified deque simulation illustrates the scaling on one fork-join tree; it is not the full theorem model: the extra time stays under spans, and steals are rare. Work stealing appears in Cilk, oneTBB, Java fork-join, Rayon and Go, with different task, queue and scheduling policies.
10Parallel prefixGraduate4 min
Here is the problem at the heart of parallel algorithms. Given a list, compute every running total: three, then three plus one, then plus four, and so on. This is called a prefix sum, or a scan. Done the obvious way it takes n minus one additions, which is fine, but each one needs the one before, so the span is also n minus one: no parallelism at all. And the operator need not be addition. Anything associative will do: maximum, matrix products, or a rule you met in Part 4.
In Part 4 we built adders. Take two eight-bit numbers. Each bit position either generates a carry, if both bits are one; propagates one, if exactly one is; or kills it. Two adjacent stretches of bits combine by this rule: the pair generates if the upper part generates, or propagates a carry the lower part generates. The rule is associative. So the carries into every position are a scan of the generate-propagate pairs under this operator. The carry-lookahead adders of Part 4, Kogge-Stone, Sklansky, Brent-Kung, were parallel prefix circuits all along, and Brent of Brent-Kung is the Brent of the last chapter's theorem.
The first parallel answer doubles its reach at every step. In step one, every element adds the one just to its left. In step two, the one two places to the left. Then four. After log n steps, each element has added in everything before it. Three steps for eight elements, twenty for a million. Daniel Hillis and Guy Steele used it on the Connection Machine. But count the work: nearly n additions at every step, n log n in all. For a million elements, twenty million additions where one million would do. With few processors that wasted work is real time.
In 1990 Guy Blelloch showed how to scan with linear work, using a tree in two passes. The up-sweep adds neighbours in pairs, then pairs of pairs, building the partial sums of larger and larger blocks, exactly as you would add up the whole list in parallel. Then clear the last element, and sweep back down. At each level, every node passes its value to its left child and gives its right child the sum of that value and the left child's old block sum. At the bottom, each position holds the sum of everything before it. For a power-of-two n, the two sweeps use exactly n minus one additions in each sweep, two n minus two altogether, and two log-base-two n levels. That is linear work, about twice the serial addition count; exclusive scan also needs an identity element. Blelloch's point was larger than the algorithm: with a fast scan as a primitive, many problems that look sequential become parallel.
Here is the most common use. Keep only the words of seven letters or more, in parallel. Mark each word with a one if it stays, a zero if not. An exclusive scan of the marks gives each kept word its position in the output: the number of kept words before it. Now every word can be written to its place at once, without write conflicts, after the scan and required synchronization complete. The same trick drives radix sort, which splits keys by each bit in turn, quicksort's partition step, and tokenizing text in parallel. On a GPU, scan is a building block of many library primitives, alongside reduction, sorting and other techniques.
11Sorting networksGraduate4 min
Sorting is the next test of parallel thinking, and its parallel form is beautiful. The building block is a comparator: two wires in, and out come the same two values, the smaller on top and the larger below. A sorting network is a fixed list of comparators, chosen before seeing any data, that sorts every input. Comparators on different wires can work at the same moment, so a network's depth, its number of layers, is its parallel time. And because it does the same operations whatever the data, a network suits hardware, SIMD registers and GPUs, where branches are expensive, and some constant-time cryptographic code. A fixed comparison pattern helps, but comparators, memory accesses and the surrounding implementation must also avoid secret-dependent timing.
Here is one of the classic designs, Kenneth Batcher's bitonic sorter from 1968, on eight wires. Watch eight numbers pass through it, one layer at a time. The first layer sorts pairs. The next two merge pairs into sorted fours: the first of them compares mirror images, the second neighbours. The last three merge the fours into a sorted eight. Twenty-four comparators in six layers. In general, the depth grows as the square of log n: for a thousand and twenty-four wires, fifty-five layers.
How do you know a network sorts every input? There are n factorial orders to try. The shortcut, proved in Knuth's Art of Computer Programming, is the zero-one principle. If a network sorts every input made of zeros and ones, it sorts every input at all. The proof is four lines. Take any rising function f. Applying f and then taking the smaller of two values is the same as taking the smaller and then applying f. So f passes through each comparator, and through the whole network. Now suppose the network fails on some input: somewhere in the output, a larger value y i sits above a smaller one. Let f send everything at least y i to one and everything smaller to zero. The network's output on f of x is f of its output on x, which has a one above a zero. So the network also fails on an input of zeros and ones. To check a network on n wires, two to the n inputs suffice, instead of n factorial.
With the principle, we checked networks exhaustively. For ten wires, one thousand and twenty-four inputs instead of three point six million orders. For each n up to ten we built two networks: the insertion network, which mimics insertion sort, and Batcher's odd-even merge network. Both sort all zero-one inputs, and the Batcher networks through eight wires were separately checked on every permutation. Beside them, the smallest sizes and depths known. That column is a research story of its own: the remaining nine- and ten-wire minimum-size cases were proved optimal in the 2014 work, by a computer search that relied on this same principle. And the principle catches mistakes. Remove a single comparator from Batcher's network for eight wires, and the check immediately produces a zero-one input it fails to sort.
12Amdahl and GustafsonDegree3 min
In 1967 Gene Amdahl, the architect of IBM's System/360, argued that parallel machines would always disappoint. Suppose a fraction s of the fixed program's one-processor running time is serial, and the rest divides perfectly among p identical processors, with no extra overhead. On one processor the time is one. On p it is s, plus one minus s over p. The speedup is one over that, and as p grows it approaches one over s, and no further. One percent serial, and a thousand processors give barely ninety-one times. Ten percent serial, and you never pass ten. Twenty-five percent, never four.
Twenty years later John Gustafson, at Sandia National Laboratories, pointed out what Amdahl had assumed: that the problem stays the same size. People who buy a thousand processors do not run yesterday's problem faster. They run a bigger problem in the same time: a finer weather grid, a larger simulation. The idealized assumption is that serial time stays roughly fixed while useful parallel work grows; real input and communication costs may also grow. Measured that way, s is now the serial fraction of the measured parallel runtime, not the same numerical fraction as in the fixed one-core problem. The scaled speedup is s plus p times one minus s under those assumptions. Both are right; they answer different questions. Amdahl's is called strong scaling: the same problem, solved faster. Gustafson motivates scaled-size reasoning. Weak scaling conventionally holds work per processor fixed and measures how runtime changes; constant runtime is its ideal outcome, not its definition. Supercomputers live by weak scaling.
Here is the Job, scaled from one Pebble core to thirty-two, the same thirty novels each time: strong scaling. With the merge on one core, the speedup climbs to about three and then falls. That is worse than Amdahl's law, because the serial part is not fixed: more cores mean more tables to merge. A tree of merges does a little better at the largest sizes, but not much. And with the merge partitioned by word, the conditional compute-cost speedup can exceed p, 34 times on thirty-two cores, because the scan-based algorithm changes its total work as tables shrink. Routing, communication and shared-resource costs are still excluded. Remember where that comes from: an algorithm whose worst case is quadratic, rather than an immutable amount of work. Amdahl's law assumes the total work is fixed; here, splitting the data reduced it.
13Models and networksGraduate3 min
Parallel-algorithm models make their assumptions explicit. A classical PRAM has p synchronous processors and ideal unit-time access to shared cells, without charging for caches or a network. Fortune and Wyllie's 1978 work is one early reference. EREW forbids concurrent reads and writes to one cell; CREW permits shared reads; CRCW also permits shared writes under a specified conflict rule. With n processors and common-value concurrent writes, initialize an answer to zero and let every one-bit write one: OR takes constant time. In the standard bounded-fan-in exclusive-write setting it requires logarithmic time. Processor count, word operations and write-conflict rules matter. PRAM is a useful abstraction, while real communication still has a cost.
In 1990 Leslie Valiant proposed a model that charges for communication, bulk-synchronous parallelism. A computation is a series of supersteps. In each, every processor computes on its own data, then sends messages, and then all wait at a barrier until every message has arrived. A superstep costs the largest local work, plus g times the largest number of words any processor sends or receives, plus the cost of the barrier. Two numbers, g and l, summarize the whole network. LogP, from David Culler and colleagues in 1993, prices each message individually: its latency, the processor's overhead to send it, and the gap between messages. Many clusters use MPI. Broadcast, reduce and all-reduce can implement bulk-synchronous phases, but MPI also supports point-to-point and asynchronous communication; it is not identical to BSP. The all-reduce is how AI, Built's Part 18 trains one model on many GPUs.
Real machines connect their processors with a network, and its shape matters. A ring is cheap but slow to cross. A two-dimensional mesh, the shape of many on-chip networks, connects each node to its neighbours. A torus wraps the mesh's edges around. A hypercube connects each of two to the d nodes to the d nodes that differ from it in one bit. A tree is cheap, but everything between its halves passes through the root. Charles Leiserson's fat tree fixes that by making the links thicker toward the root, and today's data-centre networks are built that way.
14The Job on four coresGraduate3 min
Now the conditional compute-cost projection on four of Part 8's cores. Each core counts its word-aligned quarter of the text. They do not finish together: the last quarter holds books with the largest vocabularies, so its table grows longest. Then the partitioned merge, a fraction of a second. In all, about twelve seconds, against fifty-seven on one core: four point eight times faster. The total work is less than one core's, because the four tables are shorter. And some of the time is wasted: three cores sit idle while the slowest finishes. Cutting the text into many smaller pieces and letting idle cores steal them, the scheduler of chapter nine, can reduce this imbalance, but smaller private tables and extra merges also change the work. The notes compute the 64-piece case separately; this is not a pure scheduling-only comparison.
Now measured host runs of the C implementation, with the same counting strategy but a different layout and instruction stream. Threads are not pinned; host or container CPU limits can constrain the result. One thread, scalar: 24 seconds. With AVX2, 8. Two threads, then four: the four-thread scalar version takes 6.2 seconds, a measured speedup of 3.81. Frequency, scheduling, memory behavior and reduced dictionary work all affect this result. And four threads with vectors: 1.9 seconds, 12 times faster than where we started. Combining thread and vector parallelism helps here; their gains need not multiply independently on every workload. The timer covers counting and merging, excludes corpus loading and final top-twenty printing, and reports the faster of two runs.
So the ledger gets its fifth row. Thirty novels: four and a half minutes on Part 6's single-cycle Pebble, two and a half with a pipeline, under a minute out of order, a conditional memory-cost estimate in Part 9, and now twelve seconds on four cores. But be honest about where this one came from. It remains a feature-model projection with routing, communication and shared-resource costs omitted. Part of the modeled gain is parallelism. Part is that splitting the text shortened the tables, which means the Job's real problem is still its algorithm: every word pays for a scan of the vocabulary. That ends this act. Act Three teaches the machine to understand a language, and in Act Four, Parts 16 and 17 replace the scan itself.
15Frontier: thin air, stealing, dark siliconResearch2 min
A subtle research problem concerns causal cycles in language memory models. Here x and y are initially zero, and all shared accesses mean relaxed atomic accesses. One thread loads x and stores that value to y; the other loads y and copies it to x. Every ordinary program-order interleaving keeps both values zero. Now consider a deliberately permissive toy model that exposes a guessed store before confirming its source load. This is stronger than ordinary internal value prediction. A guess of forty-two can circulate through both threads and confirm itself. Our enumerator checks the candidate values zero, one and forty-two; it illustrates the circular justification, not a complete language semantics. Such out-of-thin-air cycles are discouraged by the C++ standard. Conventional processors do not publish unconfirmed speculative store values this way. The difficult question is how to specify causality precisely while preserving valid compiler transformations.
Energy is another frontier with several different scales. Near-threshold operation can reduce energy per operation for some circuits and workloads, trading away speed and noise margin; the saving is not a universal factor of ten. Specialization can avoid the overhead of a general-purpose processor, as Part 60 explores. Three-dimensional integration can shorten connections, especially between memory and logic, while raising thermal and manufacturing challenges. At the thermodynamic scale, resetting one unknown unbiased bit in a reservoir at temperature T has a minimum average heat cost of k T times natural log two in the ideal erasure setting, about three times ten to the minus twenty-one joules at room temperature. That is not a lower bound on every transistor transition. Reversible and adiabatic designs aim to reduce information loss and dissipation. They do not violate Landauer's erasure bound; initialization, error correction and eventual reset still require accounting. Practical energy efficiency remains a system problem.
Recap, problems, and where this comes backAll tracks3 min
We connected three levels of parallel-machine reasoning. At the physical level, voltage and power budgets constrain frequency scaling. At the shared-memory level, MESI tracks permissions, false-sharing measurements show the cost of poor placement, and defined atomic litmus tests separate coherence from ordering. At the algorithm level, work and span give bounds, scans turn dependencies into parallel structure, and the zero-one principle verifies our small sorting networks. The four-core Job estimate improves partly through parallel execution and partly through less dictionary work, with several machine costs still omitted. Host C timings are separate measurements. Knowing which kind of evidence supports each number is part of understanding the machine.
Where this comes back. Locks, lock-free data structures and the memory model in depth are Part 33. The Job's real fix, a better algorithm, is Parts 16 and 17, and a vectorized tokenizer gives ledger row ten in Part 24. Threads and their scheduling inside an operating system are Part 31. Consensus between machines that can crash, Herlihy's question at the scale of a data centre, is Parts 38 and 59. The partitioned merge grows into MapReduce and the shuffle in Parts 39 and 45. And specialized hardware, the answer to dark silicon, is Part 60.
In practice. Servers give each core its own thread pool and its own counters, and keep hot data out of shared lines. Parallel libraries offer several scheduling policies. oneTBB, Rayon and Java fork-join use forms of work stealing; OpenMP scheduling depends on the runtime and chosen construct. SIMD code is written with intrinsics or portable vector types, and compilers report which loops they vectorized. GPU kernels are written to keep loads coalesced and warps undivided. Supercomputer codes live by MPI collectives and weak scaling. And the tools of the trade are ThreadSanitizer, which can detect many data races, and perf c2c, which helps investigate cache-line contention when the host and permissions support its counters. Neither is a complete proof of correctness or performance.
The notes give six exercises and worked guidance. The fifth changes the Job from four large shards to sixty-four smaller pieces; compare both scheduling balance and the changed amount of dictionary work. The last is a research exercise on scheduler constants and locality.
That ends Act Two. Next comes Act Three, Speaking to the Machine, and Part 11 follows one program from source code to a running process: how its data becomes bytes, its calls a stack, and its names addresses; how the linker and loader bring it to life; and how one unchecked copy can make it do something its author never wrote.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Locks, lock-free structures and the memory model in depth are Part 33; the Job's better algorithm is Parts 16 and 17, and a vectorized tokenizer is ledger row ten in Part 24; threads inside an operating system are Part 31; consensus between machines is Parts 38 and 59; the partitioned merge grows into MapReduce in Parts 39 and 45; specialized hardware, the answer to dark silicon, is Part 60.
Key results
The part's results in one place, for revision.
Try it
Lab 10 · Brent's theorem, two scans and a sorting network
Build a computation of 2,000 unit nodes, schedule it greedily on p processors, and check max(T1/p, Tinf) <= Tp <= T1/p + Tinf for every p. Then count the additions of the Hillis-Steele and Blelloch scans, and test Batcher's 8-wire bitonic network with the 0-1 principle, whole and with one comparator removed.
python -m videos.cs.labs 10
needs numpy, scipy, matplotlib · download lab10.py ·
source on GitHubwork T1, span Tinf, parallelism 2000, 132, 15.2
p = 2: greedy steps 1000 (at least 1000, at most 1132; 1000 complete + 0 incomplete)
p = 8: greedy steps 251 (at least 250, at most 382; 249 complete + 2 incomplete)
p = 64: greedy steps 132 (at least 132, at most 163; 13 complete + 119 incomplete)
scan of 1,024 numbers: additions Hillis-Steele 9,217 = n log2 n - n + 1 Blelloch 2,046 = 2(n - 1)
bitonic network on 8 wires 24 comparators in 6 layers; sorts all 256 0-1 inputs: True
the same without comparator 20 fails on 11111110
A greedy schedule is never more than T1/p + Tinf, so it is within a factor of two of the best; Blelloch's scan does linear work where Hillis-Steele does n log n; 256 inputs of zeros and ones certify a network that 40,320 orderings would.
The code (80 lines; it asserts its own result)
"""Lab 10: schedule a random computation greedily on 1 to 64 processors and hold it against Brent's bound."""
from videos.coursekit import labs
import math
import numpy as np
from explainer.cs.pebble import parallel as par
TITLE = "Brent's theorem, two scans and a sorting network"
GOAL = ("Build a computation of 2,000 unit nodes, schedule it greedily on p processors, and check "
"max(T1/p, Tinf) <= Tp <= T1/p + Tinf for every p. Then count the additions of the Hillis-Steele and "
"Blelloch scans, and test Batcher's 8-wire bitonic network with the 0-1 principle, whole and with one "
"comparator removed.")
TASKS = [
"Schedule with priority=lambda v: -v (newest ready node first). Does the makespan stay inside the two bounds? Must it?",
"Replace the random computation by par.fork_join_tree(10) and compare par.steal(d, p)['makespan'] with greedy's.",
"Find the 0-1 input that each single removed comparator of par.bitonic(8) fails on. Is any comparator redundant?",
]
def run(seed=0):
rng = np.random.default_rng(seed)
d = par.Dag.random(2000, width=int(rng.integers(24, 48)), fan=3, seed=seed + 1)
t1, tinf = d.work(), d.span()
ps = [1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64]
spans = []
lab = labs.Lab()
lab.row("work T1, span Tinf, parallelism", f"{t1}, {tinf}, {t1 / tinf:.1f}")
for p in ps:
g = par.greedy(d, p)
spans.append(g["makespan"])
lower, upper = max(math.ceil(t1 / p), tinf), t1 / p + tinf
assert lower <= g["makespan"] <= upper, "Brent: a greedy schedule lies between the bounds"
assert g["complete"] <= t1 / p and g["incomplete"] <= tinf, "the proof's two kinds of step"
if p in (2, 8, 64):
lab.row(f"p = {p}: greedy steps", f"{g['makespan']} (at least {lower}, at most {upper:.0f}; "
f"{g['complete']} complete + {g['incomplete']} incomplete)")
assert spans[0] == t1 and spans[-1] < 1.2 * tinf, "one processor does the work; many approach the span"
ns = [2 ** k for k in range(1, 11)]
hs, bl = [], []
for n in ns:
xs = [int(v) for v in rng.integers(0, 100, n)]
h, b = par.hillis_steele(xs), par.blelloch(xs)
prefix = np.cumsum(xs)
assert h["result"] == list(prefix) and b["result"] == [0] + list(prefix[:-1]), "both compute the running totals"
assert h["ops"] == n * int(math.log2(n)) - n + 1 and b["ops"] == 2 * (n - 1)
hs.append(h["ops"])
bl.append(b["ops"])
lab.row("scan of 1,024 numbers: additions", f"Hillis-Steele {hs[-1]:,} = n log2 n - n + 1 Blelloch {bl[-1]:,} = 2(n - 1)")
net = par.bitonic(8)
ok, _ = par.sorts_all_01(net, 8)
k = int(rng.integers(len(net)))
broken, witness = par.sorts_all_01(net[:k] + net[k + 1:], 8)
lab.row("bitonic network on 8 wires", f"{len(net)} comparators in {len(par.layers(net))} layers; sorts all 256 0-1 inputs: {ok}")
lab.row(f"the same without comparator {k}", f"fails on {''.join(map(str, witness))}" if not broken else "still sorts")
assert ok and par.sorts_all_perms(net, 8) and (len(net), len(par.layers(net))) == (24, 6)
assert not broken and par.apply(net[:k] + net[k + 1:], witness) != sorted(witness), "every comparator is needed"
lab.note = ("A greedy schedule is never more than T1/p + Tinf, so it is within a factor of two of the best; "
"Blelloch's scan does linear work where Hillis-Steele does n log n; 256 inputs of zeros and ones "
"certify a network that 40,320 orderings would.")
fig, ax = labs.figure(2, size=(11, 4.2))
grid = np.arange(1, 65)
ax[0].plot(grid, t1 / grid + tinf, color=labs.ORANGE, label="Brent: T1/p + Tinf")
ax[0].plot(grid, np.maximum(t1 / grid, tinf), color=labs.GREY, label="lower bound max(T1/p, Tinf)")
ax[0].plot(ps, spans, "o", color=labs.GREEN, label="greedy schedule")
ax[0].set(xscale="log", yscale="log", title=f"{t1} nodes, span {tinf}: steps on p processors", xlabel="processors p",
ylabel="steps")
ax[0].legend()
ax[1].plot(ns, hs, "o-", color=labs.RED, label="Hillis-Steele: n log2 n - n + 1")
ax[1].plot(ns, bl, "o-", color=labs.BLUE, label="Blelloch: 2(n - 1)")
ax[1].plot(ns, [n - 1 for n in ns], ls=":", color=labs.MUTED, label="serial: n - 1")
ax[1].set(xscale="log", yscale="log", title="Additions to scan n numbers", xlabel="n", ylabel="additions")
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Schedule with priority=lambda v: -v (newest ready node first). Does the makespan stay inside the two bounds? Must it?
- Replace the random computation by par.fork_join_tree(10) and compare par.steal(d, p)['makespan'] with greedy's.
- Find the 0-1 input that each single removed comparator of par.bitonic(8) fails on. Is any comparator redundant?
Problems, with solutions
Try each problem before opening its solution.
-
Power density. Under Dennard scaling by κ, how does power per area change if the voltage stays fixed while the clock still rises by κ? And if the clock stays fixed too?
Solution
Per transistor, P = αCV²f. With C → C/κ, V fixed and f → κf, a transistor's power is unchanged: (C/κ)·V²·(κf) = CV²f. But κ² times as many transistors fit in the area, so power per area rises by κ², about twice per generation. With the clock fixed too, a transistor's power falls only to CV²f/κ, so power per area still rises by κ: about 40% a generation. That is why, after 2005, even constant clocks did not make chips cool, and why dark silicon followed.
-
MESI by hand. Four caches, all Invalid. Core 0 reads, core 1 writes, core 0 reads, core 1 writes. Give every state after each step and count the invalidations.
Solution
(states of cores 0–3)
- core 0 reads: no other copy, E I I I;
- core 1 writes: a read for ownership invalidates core 0, I M I I (1 invalidation);
- core 0 reads: core 1 supplies its Modified line, both Shared, S S I I;
- core 1 writes: an invalidation to core 0, I M I I (2 in all).
Each write by core 1 costs a bus transaction because core 0 keeps reading: this is the ping-pong of true sharing.
-
One fence. Under TSO, put a fence in thread 0 of the store-buffering test only. Can both threads still read 0?
Solution
Yes. Thread 0's fence drains x = 1 to memory before it reads y, but thread 1's store y = 1 can still sit in thread 1's store buffer. Run thread 1 first: y = 1 enters its buffer and its load reads x = 0 from memory. Then thread 0 stores x = 1, fences, and reads y = 0, because y = 1 is still buffered. Both read 0. In this fence construction, ordering both workers' store–load pairs is sufficient: one fence each. This is a hardware-model argument; language synchronization must also be defined.
-
Counting scan work. For a nonempty power-of-two input, show that the Hillis–Steele scan does n log₂ n − n + 1 additions, and Blelloch's 2(n − 1).
Solution
At step k (k = 0 … log₂ n − 1) every element at index i ≥ 2ᵏ adds the one 2ᵏ to its left: n − 2ᵏ additions. Summing, n log₂ n − (1 + 2 + … + n/2) = n log₂ n − (n − 1). For n = 8: 24 − 7 = 17, as computed. Blelloch's up-sweep at level d does n/2^(d+1) additions, n/2 + n/4 + … + 1 = n − 1 in all; the down-sweep does one per node again, another n − 1: 2(n − 1). For n = 2²⁰: 19.9 million against 2.1 million.
-
Build: smaller pieces. Cut the Job's text into 64 pieces, each counted in its own table, and let 4 cores take them as they come free. How close to perfect balance, and what does the merge cost now?
Solution
python -m videos.cs.cs10.compute pieces. Counting: 4.82 s on the busiest core against 4.67 s for a perfect quarter of the work: 64 pieces taken as cores come free leave almost no imbalance (four big shards left 8%). The merge now combines 64 tables, so it grows from 0.63 s to 1.34 s, but the total falls to 6.15 s, against 11.85 s with four shards. The balance is only part of the gain: the 64 small tables are much shorter than four big ones, so the counting itself does less work, the reduced scan work discussed in chapter 2. Routing, communication, bandwidth and synchronization are still excluded. A table per token moves the burden into merging; it does not automatically become sorting. Sorting and hashing are separate algorithmic redesigns developed in Parts 16 and 17. -
★ Research: the work-stealing constant. Our runs stay within T₁/p + 1.6 T∞. What is the tight constant for randomized stealing on balanced fork-join trees, and what does choosing victims by locality change?
Where to start. Blumofe and Leiserson (1999) prove E[T_p] ≤ T₁/p + O(T∞) with a potential-function argument; Arora, Blumofe and Plaxton (1998) handle a non-dedicated machine. Tchiboukdjian, Gast, Trystram, Roch and Bernard ("A tighter analysis of work stealing", ISAAC 2010) give explicit small constants for independent unit tasks, and later papers extend the analysis to trees. (a) Reproduce our simulation (
parallel.steal) for depths 8 to 14 and p up to 256, and fit the constant against T∞ and log p. (b) Our simulator charges one step per failed steal; vary that cost (the latency of an inter-core miss) and see how the constant moves. (c) Hierarchical or locality-aware victim selection (steal from a neighbour first) is used in practice (for example in TBB and in NUMA- aware runtimes): prove a bound for it, or find a family of trees where it is worse than uniform stealing.
Notes and sources
Glossary
功率墙 power wall · 登纳德缩放 Dennard scaling · 阈值电压 threshold voltage · 漏电 leakage · 暗硅 dark silicon · 多核 multicore · 共享内存 shared memory · 缓存一致性 cache coherence · 单写多读 single writer, multiple readers · 监听 snooping · 目录 directory · MESI(已修改、独占、共享、无效) MESI (Modified, Exclusive, Shared, Invalid) · 作废 invalidation · 一致性缺失 coherence miss · 伪共享 false sharing · 存储一致性模型 memory consistency model · 顺序一致性 sequential consistency · 存储缓冲 store buffer · 全存储定序 total store order (TSO) · 弱内存模型 weak memory model · 栅栏 fence · 获取 / 释放 acquire / release · 数据竞争 data race · 原子指令 atomic instruction · 测试并置位 test-and-set · 取并加 fetch-and-add · 比较并交换 compare-and-swap · 链接取数 / 条件存数 load-linked / store-conditional · 共识数 consensus number · 无等待 wait-free · 单指令多数据 SIMD · 向量寄存器 vector register · 单指令多线程 SIMT · 线程束 warp · 分歧 divergence · 工作量 work · 跨度 span · 并行度 parallelism · 贪心调度 greedy schedule · 布伦特定理 Brent's theorem · 工作窃取 work stealing · 双端队列 deque · 前缀和 / 扫描 prefix sum / scan · 流压缩 stream compaction · 排序网络 sorting network · 比较器 comparator · 双调排序 bitonic sort · 0–1 原理 0–1 principle · 阿姆达尔定律 Amdahl's law · 古斯塔夫森定律 Gustafson's law · 强扩展 / 弱扩展 strong / weak scaling · 并行随机存取机 PRAM · 整体同步并行 BSP · 超步 superstep · 归约 / 全归约 reduce / all-reduce · 直径 diameter · 对分宽度 bisection width · 胖树 fat tree · 超立方体 hypercube · 环面 torus · 凭空出现的值 out-of-thin-air value · 近阈值计算 near-threshold computing · 兰道尔极限 Landauer's limit
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. 4 and 5; Sorin, Hill & Wood, A Primer on Memory Consistency and Cache Coherence, 2nd ed. (2020); Herlihy, Shavit, Luchangco & Spear, The Art of Multiprocessor Programming, 2nd ed. (2020); Leighton, Introduction to Parallel Algorithms and Architectures (1992); Knuth, The Art of Computer Programming, vol. 3, §5.3.4 (networks for sorting; the 0–1 principle).
Papers: Flynn, "Very high-speed computing systems" (1966); Graham, "Bounds for certain multiprocessing anomalies" (1966); Amdahl, "Validity of the single processor approach to achieving large scale computing capabilities" (1967); Batcher, "Sorting networks and their applications" (1968); Dennard, Gaensslen, Yu, Rideout, Bassous & LeBlanc, "Design of ion-implanted MOSFETs with very small physical dimensions" (1974); Brent, "The parallel evaluation of general arithmetic expressions" (1974); Fortune & Wyllie, "Parallelism in random access machines" (1978); Lamport, "How to make a multiprocessor computer that correctly executes multiprocess programs" (1979); Ladner & Fischer, "Parallel prefix computation" (1980); Ajtai, Komlós & Szemerédi, "An O(n log n) sorting network" (1983); Papamarcos & Patel, "A low-overhead coherence solution for multiprocessors with private cache memories" (1984); Leiserson, "Fat-trees" (1985); Hillis & Steele, "Data parallel algorithms" (1986); Gustafson, "Reevaluating Amdahl's law" (1988); Blelloch, "Prefix sums and their applications" (1990); Valiant, "A bridging model for parallel computation" (1990); Herlihy, "Wait-free synchronization" (1991); Culler et al., "LogP: towards a realistic model of parallel computation" (1993); Blumofe & Leiserson, "Scheduling multithreaded computations by work stealing" (1999); Acar, Blelloch & Blumofe, "The data locality of work stealing" (2000); Heaps, Information Retrieval: Computational and Theoretical Aspects (1978).
Research and later work. Esmaeilzadeh, Blem, St. Amant, Sankaralingam & Burger, "Dark silicon and the end of multicore scaling", ISCA (2011); Batty, Owens, Sarkar, Sewell & Weber, "Mathematizing C++ concurrency", POPL (2011); Boehm & Demsky, "Outlawing ghosts: avoiding out-of-thin-air results" (2014); Codish, Cruz-Filipe, Frank & Schneider-Kamp, "Twenty-five comparators is optimal when sorting nine inputs (and twenty-nine for ten)" (2014); Bundala & Závodný, "Optimal sorting networks" (2014); Kang, Hur, Lahav, Vafeiadis & Dreyer, "A promising semantics for relaxed-memory concurrency", POPL (2017). Data: Karl Rupp, Microprocessor Trend Data (CC BY 4.0), github.com/karlrupp/microprocessor-trend-data.
Additional primary references used for this revision:
- Ehlers and Müller, New Bounds on Optimal Sorting Networks (2015): seventeen-input depth optimality.
- Stern et al., WG21 P3692R3 (2025): a proposal with an implementation-based OOTA argument under stated assumptions; its existence does not establish standard adoption.
- NVIDIA, Hopper architecture and H100 specifications: dated H100 SXM illustration.
About this partfrom its README
The final part of Act II connects physical power limits, shared-memory protocols and parallel algorithms. See the series plan and syllabus. The running example counts the same thirty-novel corpus, first with private shard dictionaries and then with a partitioned merge. A fitted cost projection and a compiled host benchmark are separate experiments.
What is computed and built
| Chapter | Worked visualization and interpretation |
|---|---|
| Opening | Historical chip scatterplots; text shards feed four cores and private tables. Growth fits describe the dataset, not a law of nature. |
| 1. Power | Dynamic power, ideal constant-field scaling, a leakage sketch and a toy dark-silicon grid. The cubic frequency example ignores leakage; the 2011 dark-silicon result is a forecast under assumptions. |
| 2. Multicore | Private tables, shard-count bars and serial/tree/partitioned merge timelines. Smaller vocabularies reduce scan work, so total work changes with processor count. |
| 3. Coherence | Broken stale copies, MESI state graph and eight individually cued accesses with values and permissions. A serialized simulator tests per-address coherence; this does not impose global SC. |
| 4. False sharing | Four counters in one line versus separate 64-byte lines; measured curves fit the current data. Ownership transfers need not equal increments. |
| 5. Consistency | All six SC interleavings, store-buffer paths and a defined C11 relaxed-atomic litmus test with an x86 mfence variant. Relaxed atomics can have no non-atomic data race and still be non-SC. |
| 6. Atomics | Lost-update timelines built from separate relaxed accesses, correct compiled counters and the ideal wait-free consensus hierarchy. LL/SC reservations and coherent RMW ownership are different mechanisms. |
| 7. SIMD | Instruction/data streams, historical vector widths, 32-byte length comparison and candidate mask. The C implementation uses a different layout from Pebble. |
| 8. GPUs | Throughput-oriented hardware, masked lanes and a scan-length utilization proxy. Oracle grouping excludes the cost of obtaining lengths and grouping; no GPU execution is claimed. |
| 9. Work/span | A 14-node DAG, greedy and optimal schedules, the unit-cost list-scheduling proof and random checks. Average parallelism is not instantaneous width; the work-stealing theorem has computation and scheduler assumptions. |
| 10. Prefix | Carry generate/propagate pairs, Hillis–Steele, Blelloch and compaction. Associativity permits regrouping, not swapping operands. The generic down-sweep now preserves noncommutative order. |
| 11. Sorting | An 8-wire network, zero-one proof and exhaustive small tests. At 1,024 wires, bitonic uses 28,160 comparators and odd-even merge 24,063; both have depth 55. Seventeen-wire depth 10 is proved optimal in the cited 2015 work. |
| 12. Scaling | Amdahl uses the serial fraction of one-processor runtime; Gustafson uses the serial fraction of parallel runtime. Weak scaling fixes work per processor, with flat runtime an ideal outcome. |
| 13. Models | PRAM access rules, BSP phases, network graphs/cuts and selected milestones through 2024. Hop count is not latency; early peak and later HPL numbers are not one application's speedup. |
| 14. Job | Conditional projected phases and a separate host C table. Timers and omitted costs are stated explicitly. |
| 15. Frontier | A deliberately permissive causal cycle, formal-model research, work-stealing locality/space questions and energy trade-offs. Landauer concerns ideal irreversible erasure, not every transistor transition. |
The instruments are coherence.py and parallel.py; checks live in test_cs10_parallel.py. Narration and captions are bilingual.
What is computed and builtComputations and measurement scope
compute.py produces all numeric inputs. The four-core feature model gives about 11.85 s, versus 57.32 s
for its Part 8 one-core reference, a 4.84× conditional compute-cost ratio. It includes fitted shard counting
and selected merge insertions. It excludes routing/hash/filter scans, communication, coherence, finite bandwidth,
barriers, scheduling overhead, final selection/output and Part 9's separate memory estimate. Smaller private
tables do not prove those costs negligible. This is not an executed multicore Pebble or a runtime error bound.
The ledger retains Part 9's 57.36 s memory projection as its preceding row; the speedup reference above is Part 8.
workspan.job[].projected_makespan is a phase-model duration, not the unlimited-processor span of a fixed DAG:
changing the shard count changes the computation. The independent 14-node example has work 14, span 7, a greedy
two-processor schedule of 10 steps and an optimal schedule of 8.
Host measurements belong to the environment that generated their cache. Threads are unpinned; frequency, scheduling, container limits and other activity affect results. The current run's C counting/merging times are 23.70 s scalar on one thread, 8.23 s with one-thread AVX2, 6.22 s scalar on four threads and 1.93 s with four-thread AVX2. These are the faster of two runs, exclude file loading and final printing, and check the top twenty against the reference; they do not constitute a full per-word output comparison. Future runs can differ, and narration uses the measured ratios rather than assuming superlinear host speedup.
The C11 counter and litmus examples use defined shared accesses. A relaxed load followed by a relaxed store can
lose updates even though each access is atomic; an ordinary non-atomic racing C variable would be undefined.
The other four counter variants check exact totals. The litmus mfence experiment is explicitly x86-specific;
an allowed outcome's absence in a finite run is not a proof that the architecture forbids it.
The false-sharing timer reports elapsed ns / increments per thread. The shared-counter timer instead reports elapsed ns / all increments across all threads. These are different denominators and should not be compared as if both were single-instruction latency. Per-thread completion intervals and aggregate throughput can both be useful.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- The power wall: P = αCV²f; Dennard scaling (1974) and its end; fifty years of microprocessor trends (cited); dark silicon.
- Multicore and shared memory; the Job split across four Pebble cores.
- Cache coherence: the problem; snooping MSI and MESI as state machines, animated; directories; coherence misses; false sharing measured on this machine.
- Memory consistency: sequential consistency (Lamport 1979); store buffers break it, as the store-buffering litmus test shows (both threads read 0); TSO, weak models, fences. The deep dive is Part 33.
- Atomic instructions: test-and-set, CAS, LL/SC, fetch-and-add (Part 33 uses them).
- SIMD and vectors: Cray-1 (1976), SSE and AVX, NEON, SVE; vectorizing the Job's character scan.
- GPUs in one chapter: SIMT, warps, divergence (callback to AI, Built 17).
- The work–span model: T₁, T∞, parallelism T₁/T∞; Brent's theorem T_p ≤ T₁/p + T∞ (proved); greedy scheduling; work stealing (Blumofe & Leiserson) and its bounds.
- Parallel prefix (scan): Part 4's carry tree reappears. Blelloch's work-efficient scan and its uses (radix sort, stream compaction, lexing).
- Sorting networks: the 0–1 principle (proved); Batcher's bitonic sort, depth O(log² n); AKS; optimal small networks found by computer search (cited).
- Amdahl against Gustafson (both derived); strong and weak scaling.
- Models: PRAM (EREW, CREW, CRCW), BSP (Valiant 1990), LogP; message passing and MPI collectives (callback to AI, Built 18's all-reduce).
- Interconnects: bus, crossbar, mesh, torus, hypercube, fat tree; bisection bandwidth.
- Supercomputers from the Cray-1 to exascale (Top500, cited). Ledger row 4.
- Frontier: thin air, stealing, dark silicon. The load-buffering test enumerated (only (0, 0) in order; any self-confirming guess under value speculation); out-of-thin-air values and the unsolved C/C++ memory model (Batty et al. 2011, promising semantics 2017); what work-stealing bounds leave out (the constant, about 1.6 spans simulated; locality, space, heterogeneous cores); near-threshold computing, 3-D stacking, Landauer's limit.
- Outro.
Computed: the MESI simulation; a false-sharing benchmark on this machine; the work and span of the parallel Job; Brent's bound against simulated greedy schedules; the 0–1 principle checked exhaustively for n ≤ 10; bitonic networks; scan. Visuals: cache lines changing color through MESI; the litmus test as two timelines; a work–span DAG with its critical path glowing; a bitonic network's wires; the scan tree's up-sweep and down-sweep. In practice: multithreaded servers, OpenMP, TBB and Rayon, SIMD intrinsics, GPU kernels, HPC and MPI. Reading: Hennessy & Patterson ch. 5; Sorin, Hill & Wood, A Primer on Memory Consistency and Cache Coherence; Herlihy & Shavit ch. 1; Blelloch 1990; Blumofe & Leiserson 1999; Knuth, TAOCP 3 §5.3.4; Leighton, Introduction to Parallel Algorithms and Architectures; Valiant 1990; Dennard et al. 1974; Esmaeilzadeh et al. 2011.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
功率密度。 按 κ 做登纳德缩放时,如果电压不变而时钟仍提高 κ 倍,单位面积功率怎样变化?如果时钟也不变呢?
解答
每个晶体管 P = αCV²f。C → C/κ、V 不变、f → κf 时,单个晶体管功率不变:(C/κ)·V²·(κf) = CV²f。但同样面积里能放下 κ² 倍的晶体管,所以单位面积功率升高 κ² 倍,每代约两倍。时钟也不变时,单个晶体管功率只降到 CV²f/κ,单位面积功率仍升高 κ 倍:每代约 40%。这就是 2005 年以后连时钟不变芯片也凉不下来、暗硅随之而来的原因。
-
手算 MESI。 四个缓存,全为 Invalid。核 0 读,核 1 写,核 0 读,核 1 写。给出每一步后的所有状态,并数出作废的次数。
解答
(核 0–3 的状态)
- 核 0 读:没有别的副本,E I I I;
- 核 1 写:为获得所有权而读,作废核 0,I M I I(1 次作废);
- 核 0 读:核 1 提供它的 Modified 行,两者都 Shared,S S I I;
- 核 1 写:作废核 0,I M I I(共 2 次)。
因为核 0 一直在读,核 1 的每次写都要一次总线事务:这就是真共享的乒乓。
-
一道栅栏。 在 TSO 下,只在存储缓冲测试的线程 0 里放一道栅栏。两个线程还能都读到 0 吗?
解答
能。 线程 0 的栅栏让 x = 1 在它读 y 之前写进存储器,但线程 1 的存数 y = 1 仍可能待在线程 1 的存储缓冲里。让线程 1 先走:y = 1 进入它的缓冲,它的取数从存储器读到 x = 0。然后线程 0 存 x = 1、过栅栏、读 y = 0,因为 y = 1 还在缓冲里。两个都读 到 0。要禁止这个结果,两个线程的存数—取数对都必须有序:每个线程一道栅栏。
-
数扫描的工作量。 对非空、长度为二的幂的输入,证明 Hillis–Steele 扫描做 n log₂ n − n + 1 次加法,Blelloch 的做 2(n − 1) 次。
解答
第 k 步(k = 0 … log₂ n − 1)每个下标 i ≥ 2ᵏ 的元素加上它左边 2ᵏ 处的那个:n − 2ᵏ 次加法。求和得 n log₂ n − (1 + 2 + … + n/2) = n log₂ n − (n − 1)。n = 8 时:24 − 7 = 17,与计算一致。Blelloch 的上扫在第 d 层做 n/2^(d+1) 次加法,n/2 + n/4 + … + 1 = n − 1 次;下扫每个结点再做一次,又是 n − 1:2(n − 1)。n = 2²⁰ 时:1990 万对 210 万。
-
动手:更小的块。 把任务的文本切成 64 块,每块各用一张表计数,让 4 个核空了就去取下一块。离完美均衡有多近?合并现在花多少?
解答
python -m videos.cs.cs10.compute pieces。计数:最忙的核 4.82 秒,完美四等分是 4.67 秒:64 块按核空闲的先后 取走,几乎没有不均衡(四大块时是 8%)。合并现在要合 64 张表,从 0.63 秒增加到 1.34 秒,但总时间降到 6.15 秒,四大块时 是 11.85 秒。均衡只是收益的一部分:64 张小表比四张大表短得多,所以计数本身做的功更少,这就是第 2 章讨论的扫描工作量减少。路由、通信、带宽和同步仍未计入。每个词元一张表会把负担转移到合并, 并不会自动变成排序;排序与哈希是第16、17部分另行发展的算法重设计。 -
★ 研究:工作窃取的常数。 我们的模拟都落在 T₁/p + 1.6 T∞ 以内。在平衡的分叉—汇合树上,随机窃取的紧常数是多少?按局部性 选择受害者会改变什么?
从哪里开始。 Blumofe 与 Leiserson(1999)用势函数论证证明了 E[T_p] ≤ T₁/p + O(T∞);Arora、Blumofe 与 Plaxton(1998)处理了 非专用的机器。Tchiboukdjian、Gast、Trystram、Roch 与 Bernard(“A tighter analysis of work stealing”,ISAAC 2010)对独立任务 给出了明确的小常数,后来的论文把分析推广到树。(a)对深度 8 到 14、p 到 256 重做我们的模拟 (
parallel.steal),把常数对 T∞ 和 log p 拟合。(b)我们的模拟器每次失败的窃取算一步;改变这个代价(一次核间缺失的延迟),看 常数怎样移动。(c)分层或照顾局部性的受害者选择(先偷邻居的)在实践中被使用(例如 TBB 和照顾 NUMA 的运行时):为它证明一个 界,或者找到一族树,使它比均匀窃取更差。
Build the film
python -m videos.cs.cs10.compute # the part's numbers, into .cache/cs10
python tools/build.py cs10 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs10 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs10. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs10.compute # missing or legacy items; run host timings on an idle machine
python -m videos.cs.cs10.compute --force litmus atomics
python -m unittest tests.test_cs10_parallel
python tools/build.py cs10 -q l # 480p preview
python tools/build.py cs10 # native production render
The C/AVX2 and mfence demonstrations require a suitable x86 host. Numerical files are local generated inputs
under .cache/cs10/. Old racy measurements and mislabeled projection records are rejected by read-only loads;
explicit computation refreshes their schema. A render or sampled QA pass is separate from complete narrated
listening and production review.