Lecture 24 · Programming paradigms: MapReduce, MPI and GraphLab

Distributed Systems · Lecture 24。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: CMU 15-440/640 Spring 2026, the learning outcome on common programming paradigms such as MapReduce, MPI and GraphLab. Problem set: PS4 asks questions about MapReduce jobs and about choosing a framework. This lecture gives the concepts and answers nothing there. Its examples avoid PS4’s computations, and its exercises have different shapes. Sources:

  • J. Dean and S. Ghemawat, MapReduce: Simplified Data Processing on Large Clusters (OSDI 2004);
  • the MPI Forum, MPI: A Message-Passing Interface Standard (version 1.0 1994, 4.0 2021);
  • R. Thakur, R. Rabenseifner and W. Gropp, Optimization of Collective Communication Operations in MPICH (IJHPCA 2005);
  • L. Valiant, A Bridging Model for Parallel Computation (CACM 1990);
  • J. Young, A First Order Approximation to the Optimum Checkpoint Interval (CACM 1974);
  • J. Daly, A Higher Order Estimate of the Optimum Checkpoint Interval for Restart Dumps (FGCS 2006);
  • G. Malewicz et al., Pregel: A System for Large-Scale Graph Processing (SIGMOD 2010);
  • Y. Low et al., GraphLab: A New Framework for Parallel Machine Learning (UAI 2010) and Distributed GraphLab (VLDB 2012);
  • J. Gonzalez et al., PowerGraph: Distributed Graph-Parallel Computation on Natural Graphs (OSDI 2012);
  • M. Zaharia et al., Resilient Distributed Datasets (NSDI 2012);
  • F. McSherry, M. Isard and D. Murray, Scalability! But at what COST? (HotOS 2015).

The slides are not public; this is not a transcript. Every number not attributed to a source comes from code/lecture24/, run on the author’s machine (Apple M4 Pro, macOS, Python 3.13 and 3.9). Cluster time is simulated, the MPI ranks are real threads, and everything is seeded. Code: code/lecture24/. Reading time: ~100 minutes, plus a few seconds to run the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Explain what a programming paradigm for distributed computation buys: by restricting what the programmer writes, the system can take over distribution, failures and stragglers.
  2. Write computations as map and reduce functions, say when a combiner is legal, and recognize key skew.
  3. Describe how MapReduce executes on a cluster and survives failures by re-execution, and why that requires deterministic tasks and atomic commits.
  4. Explain stragglers, backup tasks, and why jobs have many more tasks than machines.
  5. Write MPI-style programs with point-to-point messages and collectives, avoid send–send deadlocks, and compare allreduce algorithms with the α–β model.
  6. Explain bulk-synchronous computation, coordinated checkpointing, and why global rollback stops scaling as machines multiply.
  7. Describe graph-parallel computation: Pregel’s vertex programs, GraphLab’s dynamic scheduling and consistency models, and PowerGraph’s gather-apply-scatter and vertex cuts.
  8. Compare the three paradigms on one computation: what each makes you write, what each moves between machines, and how each handles failures.

0.2 Prerequisites and scope

  • Prerequisites:
    • Lecture 4: at-least-once execution and idempotence;
    • Lecture 11: scaling out, tail latency;
    • Lecture 13: system MTBF is the node MTBF divided by the number of nodes;
    • Lecture 15: coordinated checkpoints, consistent cuts, Young’s and Daly’s intervals;
    • Lecture 16: atomic rename and shadowing;
    • threads and deadlock from 15-213 (helpful).
  • Scope:
    • Covered: the three programming models, their execution and their fault tolerance.
    • Mentioned briefly: Spark, Dryad and streaming systems.
    • Not covered: SQL-on-MapReduce systems, the MPI-IO and one-sided communication parts of MPI, graph databases, and GPU programming.
    • The file systems these systems run on (GFS, HDFS) are Lecture 25.

0.3 Section → code map

SectionIdeaDemo in code/lecture24/
§2.1–2.4the MapReduce model, combiners, skew01_mapreduce_model.py, mapreduce.py
§2.5–2.7execution, failures, determinism, commits02_mapreduce_faults.py
§2.8–2.9stragglers, backup tasks, task granularity03_stragglers.py
§3.1–3.4MPI messages, deadlock, collectives, floating point04_collectives.py, mpi.py
§3.5–3.6bulk-synchronous steps, checkpoints at scale05_bsp_checkpoint.py
§4Pregel, GraphLab, PowerGraph06_graph_parallel.py, graphlab.py
§5one computation, three paradigms07_three_paradigms.py
§6choosing a paradigm(notes)

0.4 Notation

  • P machines, workers or ranks. M map tasks and R reduce tasks in a MapReduce job.
  • n values in a vector (8 bytes each). α is the latency of one message, β the time to transfer one value. The model’s values are α = 5 µs and β = 0.0008 µs (10 GB/s).
  • A graph has V vertices and E edges. D(v) is the degree of v. PageRank’s damping factor is d = 0.85.
  • MTBF: mean time between failures. C is the checkpoint cost, τ the checkpoint interval.

1. Why a programming paradigm?

1.1 The problem

Suppose you must count the words in a few hundred terabytes of web pages, or run 500 time steps of a climate model, or rank a few billion web pages by their links. One machine would take months. A thousand machines could do it in hours, but only if someone solves a long list of problems:

  • Partitioning: split the data and the work.
  • Communication: move intermediate results between machines without drowning the network.
  • Synchronization: know when a stage is finished.
  • Failures: at a thousand machines, some fail during any long job (Lecture 13).
  • Stragglers: one slow machine can hold up everyone (Lecture 11).
  • Load balance: keep machines busy when some pieces of work are much bigger than others.

Writing all that by hand for every program is slow and error-prone. A programming paradigm (编程范式) is a bargain:

  • the programmer accepts a restricted way of writing the computation;
  • in return, the system handles some of the list above.

The more restrictive the model, the more the system can do. The less restrictive, the more the programmer must do.

1.2 Three bargains

MapReduceMPIGraph-parallel (Pregel, GraphLab, PowerGraph)
You writetwo functions: map and reducea whole program per process, with explicit sends, receives and collectivesa vertex program: what a vertex does with its neighbours’ values
The system handlespartitioning, scheduling, the shuffle, failures, stragglersmessage delivery and collective algorithms; nothing elsepartitioning the graph, scheduling vertices, messaging, (some) consistency and checkpoints
Data livesin a distributed file system between stagesin the processes’ memoryin memory, partitioned across machines
Fault tolerancere-execute the lost taskscheckpoint everything, roll everyone backcheckpoint supersteps or snapshots
Sweet spotone pass over huge data with a group-bytightly coupled numerical codesiterative computations on sparse graphs

The rest of the lecture takes each in turn and asks the same questions:

  • What can it express?
  • Does it give the same answer as one machine?
  • What does it move between machines?
  • How does it survive failures and slow machines?

Each demo checks its paradigm against a sequential answer.


2. MapReduce

2.1 The model

MapReduce (Dean and Ghemawat, 2004) came out of Google’s experience: hundreds of special-purpose programs that each read huge inputs, computed something per record, grouped the results by a key and aggregated each group. The distribution logic was the same every time; only the per-record and per-group logic differed. So the programmer writes just two functions:

map(k1, v1)            -> list of (k2, v2)       called once per input record
reduce(k2, [v2, ...])  -> list of output values   called once per distinct intermediate key

Between them the system performs the shuffle (洗牌/混洗): it collects every (k2, v2) pair emitted by any map call, groups the values by k2, and hands each group to one reduce call. In database terms, MapReduce is a per-record transformation, a group-by, and a per-group aggregation.

Word count, the “hello world” of MapReduce (mapreduce.wc_map, wc_reduce):

def wc_map(doc, text):
    for word in text.split():
        yield word, 1

def wc_reduce(word, counts):
    yield sum(counts)

Many computations fit this shape (demo 01 Part A runs the first and last):

  • Inverted index: map emits (word, document) for each word; reduce sorts and deduplicates the documents.
  • Top documents per word: map emits (word, (count in this document, document)); reduce keeps the three largest.
  • Distributed grep: map emits matching lines; there is no reduce at all.
  • Reverse web-link graph: map emits (target, source) for each link; reduce lists a page’s sources.
  • Distributed sort: map emits (key, record); a range partitioner sends each key range to one reduce task, and the reduce outputs its sorted range.

2.2 Why the answer does not depend on the split (demo 01 Part A)

The input is cut into M splits, each processed by a map task (a run of map over every record of the split). Each map task divides its output into R buckets with a partitioning function, by default hash(k2) mod R; mapreduce.partition uses crc32 so that it is stable across runs. Reduce task j fetches bucket j from every map task, sorts the pairs by key, and calls reduce once per key.

Two facts make the result equal to a single machine’s:

  1. Map calls are independent. Each record is processed by exactly one map call, and no map call sees another’s state. Splitting the input changes only which machine runs which call.
  2. Every occurrence of a key reaches the same reduce call. The partitioning function sends all pairs with key k2, from every map task, to the same reduce task. That task sees the complete group.

Demo 01 Part A splits three jobs into 16 map and 8 reduce tasks (mapreduce.run_local). All five variants, with and without combiners, match mapreduce.sequential exactly. These two facts assume the functions are deterministic and have no side effects. §2.7 shows what happens when they are not.

2.3 Combiners (demo 01 Part B)

In word count, a map task that processes a thousand documents emits (“the”, 1) thousands of times, and every one of those pairs crosses the network. A combiner (合并器) is a reduction run inside the map task, on its own output, before the shuffle. For word count it is the reduce function itself: the map task sends (“the”, 3517) once.

Demo 01 Part A measured it:

  • word count’s shuffle fell from 24,000 pairs to 8,379, about 3×;
  • top-3 documents per word fell from 17,571 to 12,489.

On real text, where the frequent words are much more frequent, the saving is larger.

When is it legal? The reduce function may serve as a combiner only if reducing partial results and then reducing those gives the same answer as reducing everything at once:

reduce(reduce(A) ∪ reduce(B)) = reduce(A ∪ B)      for every way of splitting the values into A and B

That holds if the reduction is associative and commutative: the system may apply it to any subset, in any order, any number of times (zero included). The classification of aggregates from data cubes (Gray et al., 1997) is the useful vocabulary:

KindExamplesCombiner
distributivesum, count, max, minthe reduce itself
algebraic: a fixed-size summary combinesrange (max − min), via the pair (min, max)a different intermediate value. The combiner emits (min, max), and the final reduce subtracts.
holistic: no fixed-size summary sufficesmedian, exact number of distinct values, modenone in general. The combiner can at most remove duplicates or pre-count (value, count) pairs.

Demo 01 Part B tests maximum and median as combiners. Maximum is right on every data set. The median of the map tasks’ medians is wrong: on uneven data the true median is 1,311, while the median of medians is 1,353. A trap: on values spread evenly over the map tasks, the median of medians happened to be right (1,500 both ways). A test on symmetric data would have certified a wrong combiner. Test combiners on skewed and uneven partitions.

Top-k needs care too. In demo 01, “top-3 documents per word” is combinable: each value (one document’s count for one word) is complete inside one map task, so truncating to the top 3 per map task loses nothing. “The 10 most frequent words per author” is not combinable that way. A word ranked 11th in every map task can be first overall, because a word’s count is spread over many map tasks. The combiner may sum counts per (author, word), but it must not truncate. Whether a reduction is combinable depends on what the values mean, not on the name of the operation.

The paper’s combiner is usually the same code as the reduce function. The difference is that its output goes to the intermediate file instead of the final output. A related optimization, in-mapper combining, keeps a dictionary inside the map task and emits once at the end (Lin and Dyer, 2010). It saves the cost of emitting and sorting pairs, at the price of memory.

2.4 Skewed keys (demo 01 Part C)

Real keys are rarely uniform. Word frequencies follow Zipf’s law. Popular URLs, users and products get a large share of the traffic. In demo 01’s Zipf corpus, the three most frequent words are 22.7% of all occurrences. A reduce task receives every value of its keys, so a hot key makes a hot reduce task:

Reduce tasks RCombinerBusiest reduce input / mean
8no1.62
8yes1.03
32no4.54
32yes1.12

More reduce tasks made the imbalance worse: one key cannot be split, so with 32 tasks the hottest word’s task got 4.54× the mean. The job’s reduce phase lasts as long as its busiest task (§2.8). A combiner fixes this for combinable reductions, because it collapses the hot key’s occurrences inside every map task. Otherwise there are two remedies:

  • Key salting: split a hot key into k sub-keys, (key, i). The salt i must be computed deterministically from the record, for example a hash of its id, never a fresh random number (§2.7). A second, small job merges the k partial results.
  • Sampling partitioners: for a sort, sample the keys first and choose range boundaries that equalize the work.

2.5 Execution on a cluster

 input splits      map tasks             local disks            reduce tasks         output files
 (in GFS)          (near their split)    (R buckets each)       (fetch, sort, reduce) (in GFS)

 split 0  ──►  [map] ──► bucket 0 | bucket 1 | ... | bucket R-1 ─┐
 split 1  ──►  [map] ──► bucket 0 | bucket 1 | ... | bucket R-1 ─┼──► [reduce 0] ──► part-0
   ...                                                           ├──► [reduce 1] ──► part-1
 split M-1 ──► [map] ──► bucket 0 | bucket 1 | ... | bucket R-1 ─┘       ...
                     ▲                                                   ▲
                     └──────────────── master: assigns tasks, pings workers, tracks outputs

The steps, as Dean and Ghemawat describe them (mapreduce.cluster implements them on dsim):

  1. The master (one per job) assigns each idle worker a map task, preferring a worker that holds a replica of the task’s split. In the paper, most input was read from local disk and used no network bandwidth (Lecture 25 explains GFS’s chunk replicas).
  2. A map task reads its split and calls map. It partitions the output into R buckets and writes them to its local disk, not to GFS. Then it reports the buckets’ locations to the master.
  3. When a reduce task starts, it fetches its bucket from every map task’s worker, sorts by key and calls reduce. The output goes to a temporary file in GFS, which is renamed to its final name when the task completes (§2.7).
  4. The job ends when all R reduce tasks have committed. The output is R files.

There is a barrier between the phases: no reduce call can run before the last map task finishes, because any map task might emit a pair for any key. Fetching can overlap the end of the map phase; reducing cannot. A reduce task also sorts its input by key. As a result each output file is sorted, which a user of a sort job relies on.

2.6 Fault tolerance by re-execution (demo 02 Part A)

The master pings every worker periodically. A worker that does not answer is declared dead, and its work is redone elsewhere:

What the dead worker hadRedone?Why
a running map or reduce taskyesit never finished
a completed map taskyesits output was on the dead worker’s local disk
a completed reduce tasknoits output is committed in GFS, which replicates it

A reduce task that fails to fetch a map output reports it. The master then re-executes every map task whose output was on that worker, without waiting for the pings to time out. Re-execution is the whole mechanism: there is no checkpoint and no rollback of other tasks. A map task is a function of its input split, so running it again elsewhere recreates its output.

Demo 02 Part A crashes workers during a word count on 8 workers:

FailureFinishedMap runs (40 tasks)Maps re-executedCorrect
none156 ms400yes
W01 dies in the map phase (30 ms)311 ms432yes
W01 dies in the reduce phase (110 ms)364 ms5111yes
three workers die437 ms5613yes
seven of eight die1,111 ms7831yes

The crash in the reduce phase re-executed 11 map tasks: W01’s completed map tasks, discovered after 2 failed fetches. Each failure cost about the time to detect it plus the redone work. The answer stayed exact even with one worker left. Dean and Ghemawat reported the same at scale. When they killed 200 of their 1,746 worker processes in the middle of a 1 TB sort, the job took 933 s instead of 891 s, about 5% longer.

The master is a single point of failure. The original implementation simply aborted the job if the master died, and the client retried; failures of one machine are rare compared with failures among thousands. The master could checkpoint its state periodically and restart from it. Later systems (Hadoop YARN’s application masters) do that.

2.7 What re-execution demands: determinism and atomic commits (demo 02 Parts B and C)

Re-execution produces at-least-once execution of tasks (Lecture 4). Some tasks run twice: after a crash, after their outputs are lost, or as backup copies (§2.8). The system must make that invisible. Two conditions do it.

1. Deterministic tasks. If map and reduce are deterministic functions of their input, a re-executed task produces the same output, and the whole job equals some failure-free sequential execution. Dean and Ghemawat promise this for deterministic operators. With non-deterministic operators they promise less. Each reduce task’s output equals the output of some sequential execution, but different reduce tasks may correspond to different executions of the same map task.

Demo 02 Part B makes this concrete with mapreduce.sample_map. The map samples a subset of each document’s words with a seed that differs per execution, as a map seeded from the clock or from random without a seed would. It also emits a “#docs” count:

Failure#docsWords counted60 × #docsConsistent
none20112,06012,060yes
W01 dies in the map phase (30 ms)19911,94011,940yes
W01 dies in the reduce phase (100 ms)20112,05812,060NO
W01 dies in the reduce phase (110 ms)20112,06012,060yes

With the crash at 100 ms, some reduce tasks had fetched from the first execution of a lost map task, and others from its re-execution. The output counts 201 documents but only 12,058 words, a combination that no single execution produces. The same crash 10 ms later did no harm: by then every reduce task had fetched from the same execution. The bug depends on timing, so it shows up rarely, in production, and is nearly impossible to reproduce. The remedy is to make the randomness a function of the input, for example seeding from the split’s id, so that a re-execution reproduces it.

Not every source of non-determinism matters. Iterating over a hash set in a different order produces the same multiset of pairs, which is harmless. Summing floating-point values in a different arrival order changes the last bits but commits once, which is a reproducibility problem rather than a consistency problem (§3.4). The dangerous kind changes which pairs different reduce tasks receive.

2. Atomic commits. A task that runs twice must not produce its output twice.

  • Map tasks: the master accepts the first completion message and ignores later ones. Their output files are private until then.
  • Reduce tasks: each copy writes a private temporary file, and the master or the file system atomically renames it to the final name. Only the first rename succeeds, so the final file is exactly one copy’s output. This is Lecture 16’s shadowing in one line.

Demo 02 Part C runs a job with backup copies of the last tasks. With temporary files and an atomic rename, the 2 copies that finished second were discarded, and the output was exact. With copies appending directly to the final file (bugs=("nonatomic_commit",)), 465 words appeared twice with two different lines.

Side effects outside the framework get no such protection. A map that also writes to an external service will write twice whenever it runs twice. Such effects must be idempotent, or be moved into the committed output.

2.8 Stragglers and backup tasks (demo 03 Part A)

A straggler (掉队者) is a machine that runs much slower than its peers but has not failed. Causes include a disk with correctable errors, a busy neighbour on the same machine, a misconfigured kernel, or a CPU throttled for heat. A job finishes when its last task finishes, so the slowest machine sets the pace (Lecture 11’s tail at scale).

Demo 03 Part A runs a word count over 2,000 documents with 20 workers, M = 200 and R = 20:

Slow workers (1/10 speed)Backup tasksFinishedTask executions (220 tasks)
0no524 ms220
1no2,436 ms220
1yes699 ms231
2no2,437 ms220
2yes700 ms231

One slow worker made the job 4.7× slower. A second added almost nothing, because the two crawl side by side and the job waits for the slower of them.

The remedy is backup tasks: when only a few tasks remain (here 5%), the master starts second copies of the ones still running on idle workers, and whichever copy finishes first wins. It brought the job back to 699 ms for 11 extra executions out of 220. The master cannot tell a slow task from a long one, so it also started 11 copies when no worker was slow; they cost nothing in time. Dean and Ghemawat reported that their 1 TB sort took 44% longer with backup tasks disabled (1,283 s against 891 s), for a few percent extra resources.

Backup tasks are safe only because of §2.7: copies of deterministic tasks with atomic commits are interchangeable.

2.9 How many tasks? (demo 03 Part B)

MapReduce deliberately makes M and R much larger than the number of machines. In the paper a typical job had M = 200,000 and R = 5,000 on 2,000 machines. Many small tasks help in two ways:

  • Load balance: a fast machine simply takes more tasks; nobody waits for one big one.
  • Recovery: a dead worker’s completed map work is spread over many small tasks, which all the other workers redo in parallel.

Demo 03 Part B uses 20 workers and R = 20, and kills worker W01 at 60 ms:

Map tasks MFinished (no failure)Finished (with crash)Map input processed again
20509 ms759 ms100 documents
40511 ms709 ms100 documents
200524 ms669 ms60 documents
1,000584 ms661 ms36 documents

With one map task per worker (M = 20), the crash cost a whole task of 100 documents, redone by one worker while the others waited. With M = 1,000 it cost 36 documents and was absorbed. The price of small tasks shows without failures: 584 ms against 509, from per-task overheads. At scale the master also pays: O(M + R) scheduling decisions and O(M × R) state, since it tracks every map output bucket. The paper’s sizing rule is to choose M so that each split is 16–64 MB, about one GFS chunk, and R as a small multiple of the number of machines.

2.10 Where MapReduce fits, and where it does not

MapReduce succeeded because of its restrictions. Deterministic functions, a fixed dataflow and outputs in a replicated file system are exactly what made re-execution, backup tasks and locality possible without the programmer’s help. Hadoop, an open-source implementation, became the standard platform for batch processing in the late 2000s.

The same restrictions make some computations awkward:

  • Iterative computations. PageRank, k-means-style clustering and gradient descent run the same step many times. As MapReduce, each iteration is a separate job that reads its whole input from the file system and writes its whole output back. §5 measures the cost.
  • Multi-stage pipelines. A join followed by an aggregation followed by a sort is a chain of jobs, each with its own barrier. Dryad (Isard et al., 2007) generalized the dataflow to arbitrary acyclic graphs of stages.
  • Low latency and streaming. A job is a batch: nothing comes out until the last reduce task commits.

Spark (Zaharia et al., 2012) kept MapReduce’s central idea, fault tolerance by recomputing lost data from a deterministic description of how it was produced. Spark calls that description the lineage (血统/世系) of a resilient distributed dataset. Spark keeps datasets in memory across iterations, which made iterative jobs about an order of magnitude faster than chains of Hadoop jobs. The principle is the same as §2.6: deterministic tasks make lost work recomputable.


3. MPI: message passing

3.1 The model

MPI (the Message Passing Interface, a standard since 1994) comes from high-performance computing. The setting is different from MapReduce’s:

  • a fixed set of P processes, called ranks, numbered 0 … P − 1, usually running the same program (SPMD: single program, multiple data);
  • all state in memory;
  • a fast network;
  • computations such as simulations and linear algebra, where every step needs the neighbours’ results from the previous step.

MPI gives the programmer communication primitives and nothing else. Decomposing the data, balancing load and recovering from failures are left to the programmer.

mpi.py provides the core of the model, on real threads:

def body(comm):                 # runs once per rank, comm.rank in 0..P-1
    if comm.rank == 0:
        comm.send(1, [1.0, 2.0])     # point-to-point: destination, data (, tag)
    elif comm.rank == 1:
        x = comm.recv(0)             # blocks until a matching message arrives
    total = comm.allreduce([float(comm.rank)], "ring")   # collective: every rank calls it
    return total

results = mpi.World(4).run(body)

Messages are matched by (source, destination, tag). MPI guarantees that two messages from the same sender with the same tag arrive in order. mpi.py uses one FIFO queue per (source, destination, tag), which makes every run deterministic regardless of thread scheduling.

3.2 Point-to-point messages and deadlock (demo 04 Part D)

MPI has several send modes:

  • MPI_Send may return as soon as the data is copied into a buffer, or it may wait for the matching receive; the standard allows either.
  • MPI_Ssend (synchronous) returns only when the receiver has started receiving.
  • MPI_Isend and MPI_Irecv are nonblocking and return a request that is completed later with MPI_Wait.

Consider two ranks that exchange data by each sending first and then receiving:

def exchange(c):
    c.ssend(1 - c.rank, data)        # both ranks block here, waiting for the other's recv
    return c.recv(1 - c.rank)

Each rank waits for the other to receive, and neither ever gets to its receive: a deadlock, with the cycle of waiting from 15-213 (mutual exclusion, hold and wait, no preemption, circular wait), now in messages. Demo 04 Part D runs three versions. Both ranks calling ssend first ended in DEADLOCK (detected by a time-out). Ordering the operations so that rank 0 sends first and rank 1 receives first completed, and so did sendrecv, which posts both operations together.

With MPI_Send the same program usually works: small messages fit in the library’s buffers, so the sends return. It then hangs when a message grows past the buffer size, often on a larger problem or a different MPI implementation. The standard calls such programs unsafe: correct only by grace of buffering. The fixes are the ones Part D shows:

  • break the cycle by ordering (even ranks send first, odd ranks receive first);
  • use MPI_Sendrecv;
  • use nonblocking operations and wait for both.

3.3 Collectives and their algorithms (demo 04 Parts B and C)

Collective operations (集合通信) involve every rank:

  • broadcast, scatter and gather;
  • reduce, and allreduce (every rank receives the element-wise sum of every rank’s vector);
  • allgather, all-to-all and barrier.

Allreduce is the workhorse. It sums gradients in data-parallel training, combines partial dot products in iterative solvers and computes global convergence tests. Which algorithm runs it matters a lot.

mpi.py implements four:

AlgorithmHowRoundsValues sent per rank
naiveeveryone sends to rank 0, which adds and sends the sum back2(P − 1) (the root works sequentially)root: 2(P − 1)·n
treebinomial-tree reduce to rank 0, then binomial-tree broadcast2 log₂ P≤ 2 log₂ P · n
recursive doublinglog₂ P rounds; in round i, rank r exchanges its whole vector with rank r XOR 2^ilog₂ Plog₂ P · n
ringreduce-scatter around a ring (P − 1 rounds of n/P values), then allgather (P − 1 rounds)2(P − 1)2(P − 1)/P · n

The counts measured in demo 04 Part B (P = 8, 1,024 values per rank) confirm the table:

  • recursive doubling needed 3 rounds but sent 3,072 values per rank;
  • the ring sent 1,792 values per rank, 2(P − 1)/P of the vector, but in 14 rounds;
  • the naive root sent 7 messages of the full vector.

The ring’s volume is optimal: every rank must receive the contributions of P − 1 others, and an allreduce cannot move less than about 2(P − 1)/P · n values per rank (Patarasuk and Yuan, 2009).

The α–β model turns these counts into time: T = rounds · α + (values on the critical path) · β. With α = 5 µs and β = 0.0008 µs per value (mpi.cost_model, demo 04 Part C):

Pnnaivetreerecursive doublingring
8870 µs30 µs15 µs70 µs
810⁷112 ms48 ms24 ms14 ms
1,024810.2 ms100 µs50 µs10.2 ms
1,02410⁷16.4 s160 ms80 ms26 ms

Short messages are latency-bound, and the fewest rounds win: recursive doubling. Long messages are bandwidth-bound, and the least volume wins: the ring. MPI libraries therefore switch algorithms by message size and P, using thresholds tuned per machine (Thakur, Rabenseifner and Gropp, 2005). Rabenseifner’s algorithm combines a recursive-halving reduce-scatter with a recursive-doubling allgather, getting log-many rounds and ring-like volume. The ring’s popularity in deep learning (NCCL, Baidu’s 2017 work, Horovod) comes from the long-message row: gradients are tens to hundreds of megabytes.

3.4 Floating point and reproducibility (demo 04 Part A)

Floating-point addition is commutative but not associative: (a + b) + c can differ from a + (b + c) in the last bits. Each allreduce algorithm adds the P contributions in a different order. Demo 04 Part A summed 8 ranks’ vectors of 1,000 values, spread over 16 orders of magnitude:

  • on integers, all four algorithms gave the exact sum;
  • on floats, every rank agreed within one algorithm (each rank ended with an identical vector);
  • the tree, recursive-doubling and ring results differed from the rank-by-rank sum in 451, 451 and 376 of the 1,000 elements, by relative errors up to 5 × 10⁻¹⁴.

These are not bugs. But the same program on a different P, or with a library that switched algorithms, gives slightly different answers. In a chaotic simulation, or a long training run, such differences grow until two runs visibly disagree. Reproducibility needs a fixed reduction order, such as a fixed tree, or exact accumulators.

Python itself shows the effect. Since Python 3.12 the built-in sum() of floats uses compensated summation, while 3.9 adds left to right. In demo 07, a MapReduce reduce that summed contributions in shuffle order first differed from one machine by 3.5 × 10⁻¹⁸ on Python 3.9 and by zero on 3.13. Fixing the order of additions (§5) made both exact.

3.5 Bulk-synchronous programs (demo 05 Part A)

Many MPI programs follow a rhythm that Valiant (1990) named bulk-synchronous parallel (BSP, 整体同步并行). The computation proceeds in supersteps:

  1. each process computes on its own data;
  2. processes exchange messages;
  3. a barrier, or the arrival of the needed messages, ends the superstep.

BSP’s cost model charges each superstep w + g·h + l: the largest local work w, the largest number of values h any process sends or receives at g per value, and the synchronization cost l. It is the α–β model per step.

Demo 05 runs the classic example: heat diffusion on a 1-D rod of 400 cells for 200 steps (mpi.heat_rank). Each step updates every cell from itself and its two neighbours. Rank r owns a contiguous slice and keeps one ghost cell (or halo, 光环/幽灵单元) on each side, a copy of the neighbour rank’s edge cell. Each step it exchanges edge cells with its neighbours (sendrecv, deadlock-free) and updates its slice.

Ranks PBit-identical to one processMessages per stepCells per rank
1yes0400
4yes6100
16yes3025

Splitting changed nothing in the result: each cell is computed from the same values in the same order, whoever owns them. The cost is 2(P − 1) messages per step, and the synchronous rhythm: no rank can start step t + 1 before its neighbours’ step-t edges arrive, so the slowest rank sets the pace of every step.

In two and three dimensions the halo is the surface of each block and the work its volume. Bigger blocks per rank mean relatively less communication, the surface-to-volume argument for how finely to split.

3.6 Failures: coordinated checkpoints and global rollback (demo 05 Parts B and C)

By default an MPI job aborts when any rank fails: the error handler MPI_ERRORS_ARE_FATAL. The ranks’ memory is the only copy of the state, and the program’s communication pattern assumes all P ranks exist. The standard recovery is coordinated checkpoint/restart (Lecture 15):

  • every so many steps, all ranks save their state at the same superstep boundary;
  • after a failure, the job is restarted, possibly on a spare node, and every rank resumes from the last checkpoint.

A checkpoint taken at a superstep boundary is automatically a consistent cut, since no messages are in flight between supersteps. No Chandy–Lamport markers are needed.

Demo 05 Part B checkpoints every 25 steps and fails one rank at step 137. All 4 ranks rolled back to step 125 and redid 12 steps, and the result was still bit-identical. One failure costs every rank the work since the last checkpoint. Compare MapReduce, where a failure costs only the dead worker’s tasks.

At scale this stops working. Failures of independent nodes add up: the system MTBF is the node MTBF divided by P (Lecture 13). Checkpoints must come more often as P grows, and each failure throws away the work of all P nodes. Demo 05 Part C uses Lecture 15’s exact model (rollback.expected_time, after Daly 2006) for a 24-hour job, with a checkpoint cost of 5 min, a restart cost of 10 min and a node MTBF of 5 years:

Nodes PSystem MTBFBest intervalYoung’s √(2CM)Expected run timeUseful fraction
100438 h509 min513 min24.5 h98%
1,00043.8 h159 min162 min25.6 h94%
10,0004.4 h48 min51 min30.5 h79%
100,0000.4 h13 min16 min69.8 h34%

At 100,000 nodes, two thirds of the machine’s time goes to writing checkpoints, restarting and redoing lost work. The HPC community’s responses:

  • cheaper checkpoints: to a partner node’s memory, to node-local flash or to burst buffers, with multilevel schemes such as SCR that also write to the parallel file system less often (exercise 5);
  • survive failures without global restart: ULFM (User-Level Failure Mitigation), proposed for MPI, lets the surviving ranks learn of a failure, shrink or repair the communicator, and continue;
  • algorithm-based fault tolerance: checksums carried through matrix computations that let the algorithm reconstruct lost data.

3.7 Where MPI fits

MPI gives control: data stays in memory, communication patterns are explicit and optimized, collectives are tuned to the network. For tightly coupled numerical codes, such as simulations, dense and sparse linear algebra and large-model training, nothing else comes close to its performance.

Everything else is the programmer’s job:

  • decomposition and load balance (a rank with more work slows every superstep);
  • deadlock-free communication (§3.2);
  • reproducibility (§3.4);
  • failures (§3.6).

MPI suits stable machines, expert programmers and computations whose structure is regular enough to decompose by hand.


4. Graph-parallel computation: Pregel, GraphLab, PowerGraph

4.1 Why graphs need their own paradigm

Many important computations are iterative and graph-structured: each vertex’s value is updated from its neighbours’ values, over and over, until nothing changes much. Examples:

  • PageRank;
  • shortest paths and connected components;
  • belief propagation in graphical models;
  • collaborative filtering (alternating least squares on the user–item graph);
  • label propagation in social networks.

Neither earlier paradigm fits well:

  • MapReduce runs each iteration as a job that must ship the whole graph through the shuffle, along with the values (§5).
  • MPI keeps the graph in memory, but the programmer must partition an irregular graph by hand, write the message exchange, and handle failures.

The graph-parallel systems let the programmer write a vertex program, what one vertex does with its neighbours’ values, and handle the rest. This is often summarized as “thinking like a vertex”.

4.2 Pregel: BSP for graphs

Pregel (Malewicz et al., 2010; named after the river of Euler’s Königsberg bridges) applies BSP (§3.5) to vertices. In each superstep, every active vertex:

  1. receives the messages sent to it in the previous superstep;
  2. updates its value;
  3. sends messages along its out-edges, to be delivered in the next superstep;
  4. may vote to halt: it becomes inactive until a message arrives for it.

The computation ends when every vertex has halted and no messages are in flight. Like MapReduce, Pregel offers combiners, which sum the messages to one vertex before they cross the network, and aggregators, global reductions visible to every vertex in the next superstep. For fault tolerance the workers checkpoint their partitions at the start of some supersteps. When a worker fails, all partitions are reloaded from the last checkpoint and the supersteps since are redone. That is §3.6’s global rollback, but with the system doing it.

4.3 Dynamic computation and asynchronous engines (demo 06 Part A)

A plain power iteration recomputes every vertex in every round. In PageRank most vertices converge quickly, and a few keep changing. Dynamic computation recomputes only the vertices whose inputs changed enough. A vertex that changes signals its out-neighbours, and only signalled vertices are recomputed.

GraphLab (Low et al., 2010, 2012) went further with an asynchronous engine. A scheduler holds the signalled vertices, and an update sees the newest values of its neighbours, not those of the previous superstep. The motivation is Gauss–Seidel iteration, which often converges in fewer updates than the Jacobi-style synchronous version.

graphlab.pagerank_gas implements:

  • the synchronous engine, with or without signalling;
  • the asynchronous engine with a FIFO scheduler;
  • two signalling rules:
    • residual: reschedule w once the change it has received exceeds the tolerance;
    • any: reschedule every out-neighbour of a vertex that changed.

Demo 06 Part A runs them on a 3,000-vertex preferential-attachment graph with 13,510 edges, and measures the error against a reference computed to 10⁻¹⁴. At tolerance 10⁻⁸:

EngineVertex updatesError
power iteration (every vertex, every round)66,0004 × 10⁻⁹
sync supersteps, signalled vertices only44,4243 × 10⁻⁸
async, FIFO scheduler, residual signalling81,8211 × 10⁻⁶
async, signal on any change94,5435 × 10⁻⁷

Dynamic computation paid off: 33% fewer updates than power iteration. Power iteration’s error is smaller because its stopping rule is global and stricter.

Asynchrony did not, at any of the three tolerances tried. It needed more updates and gave errors 30–40× larger. This was not the result I expected; it is reported as measured. Two effects explain it:

  • An asynchronous engine recomputes a vertex each time a change reaches it. A vertex with ten changing in-neighbours may be recomputed ten times, where a superstep would recompute it once with all ten changes.
  • Changes below the tolerance are never pushed, so small errors accumulate along paths.

A priority scheduler (largest residual first), tried while writing the demo, did no better. The lesson is not that asynchronous engines are useless. They pay off for algorithms whose synchronous form converges slowly or not at all, where fresh values matter. Exercise 8 shows one: label propagation along a path. They also pay off for algorithms that need serializable updates (§4.5). The scheduler is part of the algorithm, and must be chosen and measured per computation.

4.4 Natural graphs and vertex cuts: PowerGraph (demo 06 Part B)

Real graphs, such as social networks, the web and citation graphs, have power-law degree distributions: most vertices have few edges, and a few have enormous numbers. That breaks the obvious way to distribute a graph, the edge cut:

  • each vertex is assigned to a machine, by hashing;
  • each edge between machines carries a message per iteration;
  • a vertex with millions of edges puts all of its work, and all of its messages, on one machine.

PowerGraph (Gonzalez et al., 2012) made two changes.

1. Gather-apply-scatter (GAS). A vertex program is split into three phases:

gather(u → v):   a value from each in-edge, combined with a commutative, associative sum
apply(v, sum):   the new value of v
scatter(v → w):  along out-edges: signal w if v changed enough

For PageRank: gather = rank(u)/outdeg(u), the sum is +, and apply = (1 − d)/V + d · sum. Because the gather sum is commutative and associative (the combiner condition of §2.3 again), it can be computed in pieces on different machines and combined.

2. Vertex cuts. Instead of assigning vertices to machines, assign edges. A vertex whose edges are on several machines is replicated there: one copy is the master, the others are mirrors. Each iteration:

  • every mirror gathers over its local edges and sends one partial sum to the master;
  • the master applies and sends the new value back to the mirrors.

That is 2 × (replicas − 1) messages per vertex, however many edges it has.

The quality of a vertex cut is its replication factor. For random placement, a vertex of degree D on P machines has P(1 − (1 − 1/P)^D) replicas on average. PowerGraph’s greedy placement puts each edge on a machine that already holds its endpoints, if one exists, with ties broken toward the least-loaded machine.

Demo 06 Part B splits the same graph three ways (graphlab.edge_cut, vertex_cut):

PPartitioningReplicas per vertexMessages per iterationEdge imbalance (max / mean)
8edge cut (hash vertices)–11,7821.04
8vertex cut, random4.7922,7401.03
8vertex cut, greedy2.227,3001.00
32edge cut (hash vertices)–13,0931.20
32vertex cut, random7.1336,8021.09
32vertex cut, greedy2.7710,6361.00
  • Random vertex cuts are worse than edge cuts: replicating every vertex over most machines costs more than the cut edges.
  • Greedy vertex cuts are better: 38% fewer messages than the edge cut on 8 machines and 19% fewer on 32, with perfect balance, while the edge cut’s busiest machine had 20% more edges than the mean on 32 machines.

This graph is only mildly skewed: largest degree 252, median 6, and the 1% highest-degree vertices touch 10% of all edge endpoints. PowerGraph’s argument is that the more skewed the degrees, the more the vertex cut gains. Exercise 6 computes why: cutting a high-degree vertex saves messages, while cutting a low-degree one costs messages. Later hybrid partitioners (PowerLyra, Chen et al. 2015) cut only the high-degree vertices.

4.5 Consistency models (demo 06 Part C)

When several machines update vertices at the same time, an update may read a neighbour’s value while that neighbour is being updated. For PageRank this is harmless: a stale value only delays convergence. PageRank’s iteration is linear, with a nonnegative matrix of spectral radius d < 1, and such iterations converge even when updates use stale values (Chazan and Miranker, 1969; Bertsekas and Tsitsiklis, 1989). For other algorithms it breaks correctness.

GraphLab defines a vertex’s scope as its own data, its adjacent edges and its adjacent vertices. It offers three consistency models (一致性模型), from weakest to strongest:

  • Vertex consistency: an update has exclusive access to its own vertex only. Neighbours may update at the same moment and read each other’s old values.
  • Edge consistency: exclusive access to the vertex and its adjacent edges, and read access to adjacent vertices. No two adjacent vertices update at the same time.
  • Full consistency: exclusive access to the whole scope. No two vertices within distance 2 update at the same time.

Under edge or full consistency, a parallel execution is equivalent to some sequential order of updates: it is serializable (Lecture 17).

Demo 06 Part C shows the difference with greedy graph colouring: each vertex takes the smallest colour none of its neighbours has. Each step, a batch of 64 conflicting vertices recolours at once from the colours seen at the start of the step:

  • under vertex consistency neighbours could be in the same batch; they kept choosing the same colour as each other, and 5 conflicting edges remained after 2,000 steps;
  • under edge consistency no two neighbours shared a batch, and the colouring was proper after 43 steps with 10 colours.

There are two ways to implement edge consistency:

  • Distributed locking: lock the scope, ordering lock acquisition to avoid deadlock. This is Lecture 17’s two-phase locking with a canonical order.
  • The chromatic engine of Distributed GraphLab: colour the graph first, then run one colour class at a time in parallel. Same-coloured vertices are never adjacent, so each phase is edge-consistent for free. Full consistency needs a colouring of the graph’s square (distance-2 colouring).

4.6 Fault tolerance

All three graph systems keep the graph in memory and recover by checkpoints:

  • Pregel checkpoints at superstep boundaries, so the cuts are consistent automatically (§3.6). The Pregel paper also describes confined recovery: only the failed partitions are recomputed, from messages the healthy workers logged (Lecture 15’s message logging).
  • Distributed GraphLab has no superstep boundaries in its asynchronous engine. It takes asynchronous snapshots based on Chandy–Lamport (Lecture 15), so the computation need not stop to checkpoint.

The scaling argument of §3.6 applies to all of them. Graph jobs are usually much shorter than HPC simulations, which is what keeps checkpointing affordable.


5. One computation, three paradigms (demo 07)

Demo 07 computes 30 iterations of PageRank on demo 06’s graph (3,000 vertices, 13,510 edges) on 8 machines, three ways.

As a chain of MapReduce jobs, one job per iteration:

def pr_map(v, val):                   # val = (rank, out-neighbours)
    rank, out = val
    yield v, ("graph", out)           # the reduce must rebuild the graph...
    for w in out:
        yield w, ("contrib", (v, rank / len(out)))

def pr_reduce(v, vals):               # ...so the adjacency list travels through the shuffle
    out = next(x for t, x in vals if t == "graph")
    contribs = sorted(x for t, x in vals if t == "contrib")
    yield (1 - d) / V + d * sum(c for _, c in contribs), out

The map has to emit each vertex’s adjacency list, because a reduce sees nothing but its key’s values. Between jobs the whole state, ranks and graph, is written to the file system and read back.

As an MPI program, each rank owns 1/8 of the vertices and holds the whole graph in memory. It computes its vertices’ new ranks, and an allreduce gives every rank the full vector.

As a GAS vertex program on a greedy vertex cut, graphlab.pagerank_gas runs 30 synchronous supersteps.

All three were bit-for-bit identical to a single machine. To get that, the edges are sorted so that every vertex adds its contributions in the same order, and the MapReduce reduce sorts its contributions by source (§3.4).

What crossed between machines per iteration:

ParadigmValues movedSynchronizationWhat moves
MapReduce69,040a job (map, shuffle, reduce, write); 2 barriersthe whole graph, every iteration
MPI42,000one allreducethe full rank vector to every rank
GAS (vertex cut)7,300one superstepvalues of replicated vertices only
  • MapReduce moved the most and, in a real system, would pay a job’s start-up cost, often tens of seconds in Hadoop, 30 times.
  • MPI moved a rank vector per rank. An allgather instead of an allreduce would halve that, and a hand-written exchange of only the needed values would approach the vertex cut’s figure, at the price of writing it.
  • The vertex program moved only the values of vertices that span machines.

This is why iterative graph and machine-learning workloads moved from chains of MapReduce jobs to systems that keep state in place between iterations: Pregel, GraphLab and PowerGraph, Spark with in-memory datasets, and MPI-style collectives in training frameworks.


6. Choosing a paradigm

No paradigm wins everywhere. The questions to ask about a computation, independent of any particular scenario:

  1. How much data, and how many passes? One pass over data far bigger than memory, with a group-by, is MapReduce’s home: it streams from disk and survives failures cheaply. Many passes over data that fits in the cluster’s memory favour in-memory systems (Spark, graph systems, MPI).
  2. How regular is the communication? Regular, dense, predictable patterns (stencils, collectives) are MPI’s strength. Sparse, irregular dependencies along a graph are what vertex programs and vertex cuts are for.
  3. How long is the job, and how often do machines fail? Compare the job length with the system MTBF: a job much longer than the system MTBF needs cheap, local recovery (re-execution, lineage). A short job on reliable machines can afford global restart.
  4. Do tasks have to be deterministic? Re-execution and backup tasks rely on it. A computation with inherent randomness must seed it from its input.
  5. What does a straggler cost? Bulk-synchronous designs wait for the slowest participant at every step. Task-based designs can work around it.
  6. Who writes and maintains the code? MapReduce’s two functions can be written by anyone. A correct, efficient MPI program needs an expert.
  7. Is distribution needed at all? McSherry, Isard and Murray (2015) measured several published graph systems against a competent single-threaded implementation on a laptop. Many systems needed tens to hundreds of cores before they beat it, and some never did. They call the number of cores needed to beat one thread a system’s COST: the Configuration that Outperforms a Single Thread. Measure against a good single-machine baseline before scaling out (Lecture 11).

Real systems blend the paradigms:

  • Spark offers MapReduce-like operators with lineage and in-memory iteration, and GraphX puts vertex programs on top.
  • Training frameworks use MPI-style allreduce inside a job scheduler that restarts failed workers from checkpoints.
  • Streaming systems (Flink, Dataflow) extend MapReduce’s dataflow to unbounded inputs, with checkpointing based on Chandy–Lamport.

7. Design rules

  1. Restrict the program so the system can help. Deterministic, side-effect-free tasks with declared inputs and outputs are what make automatic distribution, recovery and speculation possible.
  2. Make re-executed work indistinguishable from the original: deterministic functions, randomness seeded from the input, outputs committed atomically (first rename wins), side effects idempotent.
  3. Push reductions toward the data (combiners, partial gathers), but only for reductions that may be split; test them on uneven partitions.
  4. Plan for skew: one key or one vertex can hold a large share of the work. Salt hot keys deterministically, split high-degree vertices, and measure the busiest task, not the average.
  5. Cut work into many more tasks than machines, for balance and cheap recovery, but not so many that per-task overhead dominates.
  6. Expect stragglers and run backup copies near the end, which is safe only under rule 2.
  7. Choose communication algorithms by message size: few rounds for small messages, little volume for large ones.
  8. Fix the order of floating-point reductions if results must be reproducible.
  9. Keep iterative state where it is computed: don’t write it to stable storage and read it back every iteration unless recovery requires it.
  10. Match the recovery scheme to scale: global rollback becomes unaffordable as P grows. Prefer local recovery (re-execution, lineage, partner checkpoints) for large systems.

Summary

  • A paradigm is a bargain: restrictions on the program in exchange for the system handling distribution, failures and stragglers.
  • MapReduce: map, shuffle (group by key), reduce.
    • Correct because map calls are independent and every occurrence of a key reaches one reduce call: all jobs matched one machine.
    • Combiners cut the shuffle (24,000 → 8,379 pairs), and are legal only for reductions that may be split: maximum yes, median no (1,353 against 1,311). Symmetric test data hid the bug.
    • Skew: one hot key made the busiest of 32 reduce tasks 4.54× the mean; more reduce tasks do not help.
    • Fault tolerance by re-execution: completed map tasks are redone too, since their output is on local disk. The answer stayed exact with 7 of 8 workers dead.
    • Re-execution needs deterministic tasks: a sampling map gave output matching no single run, depending on the timing of a crash. It also needs atomic commits: appending copies left 465 duplicated words.
    • Stragglers: one slow worker made the job 4.7× slower; backup tasks recovered most of it (699 ms against 524) for 5% extra executions.
    • Many small tasks recover cheaply (36 documents redone instead of 100), at some cost in overhead.
  • MPI: explicit messages and collectives among P ranks in memory.
    • Send–send cycles deadlock once messages outgrow buffers; order the operations, use sendrecv, or use nonblocking operations.
    • Allreduce: recursive doubling wins for small messages (latency), the ring for large (bandwidth: 26 ms against 80 ms for 10⁷ values on 1,024 ranks). Libraries switch by size.
    • Different algorithms add floats in different orders: 376–451 of 1,000 elements differed.
    • Bulk-synchronous steps with halo exchange are exact (bit-identical for P = 1..16). A failure rolls everyone back to the last coordinated checkpoint.
    • System MTBF falls as 1/P. For a 24-hour job on 5-year nodes, the useful fraction falls from 98% at 100 nodes to 34% at 100,000.
  • Graph-parallel: vertex programs on an in-memory graph.
    • Recomputing only signalled vertices saved a third of PageRank’s work.
    • Asynchronous scheduling did not pay off for PageRank here (more updates, larger errors). It suits computations where fresh values matter.
    • Vertex cuts with greedy placement beat edge cuts (19–38% fewer messages, perfect balance); random vertex cuts are worse than both.
    • Edge consistency is needed for algorithms like colouring: without it, 5 conflicts remained after 2,000 steps; with it, a proper colouring took 43 steps.
  • One computation three ways: identical PageRank; values moved per iteration 69,040 (MapReduce), 42,000 (MPI), 7,300 (vertex cut). Iterative work belongs in systems that keep state in place.

Common pitfalls

  • Using the reducer as a combiner without checking that the reduction may be split, and testing it only on evenly distributed data.
  • Seeding a map’s randomness from the clock, or giving tasks other non-determinism that changes which pairs they emit, then trusting re-execution.
  • Writing task outputs or side effects non-atomically, which breaks under re-execution and backup tasks.
  • Adding reduce tasks to fix a hot key. A key cannot be split; salt it, or combine.
  • Choosing M equal to the number of machines, so that one failure or one slow machine delays the whole job.
  • MPI programs that work only because sends are buffered, and then hang on larger inputs.
  • Expecting bit-identical floating-point results across allreduce algorithms, process counts or library versions.
  • Assuming asynchronous engines are always faster than synchronous ones; measure per algorithm.
  • Partitioning a power-law graph by hashing vertices, which leaves high-degree vertices on overloaded machines; or by assigning edges at random, which replicates everything.
  • Planning global checkpoint/restart for a machine whose MTBF is shorter than a checkpoint interval.
  • Scaling out before measuring a single-machine baseline.

Exercises

  1. Which reductions may be split? For each reduction, say whether the reducer itself can serve as the combiner, whether a combiner with a different intermediate value works, or whether only a partial pre-aggregation is possible: (a) the largest file size per directory; (b) the range (max − min) of readings per sensor; (c) the exact number of distinct visitors per page; (d) the 10 most frequent words per author, where the map emits (author, word) for each occurrence; (e) the most common value per key.

    Answer(a) Maximum is distributive: the reducer is the combiner. (b) Algebraic. The range of the map tasks' ranges is wrong: values spanning [0, 5] and [3, 9] give ranges 5 and 6, the reducer turns those into 6 − 5 = 1, and the true range is 9. A combiner that emits (min, max) works, with a final reduce that takes the min of the mins and the max of the maxes, then subtracts. (c) Holistic for exact answers: per-map distinct counts cannot be added, because visitors overlap. A combiner may deduplicate (page, visitor) pairs, since set union is associative, commutative and idempotent; the final reduce counts. Approximate answers can merge fixed-size sketches (e.g. HyperLogLog), which are algebraic. (d) Not combinable by truncation: a word ranked 11th in every map task can be first overall, because one word's occurrences are spread over many map tasks. A combiner may sum counts per (author, word), but must not truncate. Contrast demo 01's top-3 documents per word, where each value is complete inside one map task. (e) Holistic: the mode of the modes is wrong. A combiner may pre-count (key, value) pairs, and the final reduce picks the most frequent value from the summed counts.
  2. A hot key. A job counts events per account: 10⁹ events, R = 100 reduce tasks, and one account produces 20% of the events. The reduce must see every event (it also checks each for fraud), so no combiner may be used. (a) Roughly how much more input does the busiest reduce task get than the average task? (b) Design key salting for this job. How must the salt be chosen, and what does the second stage cost? (c) Why does no partitioning function alone fix the problem?

    Answer(a) The average task gets 1% of the events. The hot account's task gets the hot 20% plus about 1% of the rest, about 20.8%, roughly 21× the mean, so the reduce phase lasts about 21 times longer than balance would allow. (b) For the hot account, the map emits key (account, i) with i = hash(event id) mod k, say k = 20. Each salted key then gets 1% of the events, like any other task. The salt must be a deterministic function of the record: a random salt would put the same event in different sub-keys in a re-execution, the non-determinism of §2.7. The second stage combines the k partial results per account, usually 20 small records, and is cheap if the per-event work can be done in stage 1 and only a summary merged in stage 2. (c) The partitioning function only decides which task receives each key. Every value of one key must reach a single reduce call, so a key holding 20% of the values is indivisible whatever the partitioning.
  3. Which non-determinism matters? A map task’s behaviour varies between executions in four ways: (a) it iterates over a hash set of the document’s words, in an order that varies between processes; (b) it keeps a random 10% of each document’s sentences, using an unseeded random generator; (c) the reduce adds floating-point values in the order fetches complete, which varies; (d) the map adds the current time to every pair’s value. For each, can the job’s output be inconsistent with every failure-free execution, and what is the fix?

    Answer(a) Harmless: the multiset of emitted pairs is the same, and the reduce sorts and groups them. (b) Dangerous: if a map task is re-executed after some reduce tasks have fetched its first execution's output, the reduce tasks see different samples. The output then matches no single execution, as in demo 02 Part B. Fix: seed the generator from the split's or document's id. (c) A reproducibility problem, not a consistency problem: each reduce task's output is committed once and is the sum of the right values, only rounded differently between runs. Fix, if reproducibility matters: sort the values before adding, or use an exact accumulator. (d) Dangerous in the same way as (b), whenever the time affects what reaches different reduce tasks. Even when it does not, it makes the output differ between runs. Fix: take times from the input records, or record the job's start time once and pass it to every task.
  4. Allreduce crossover. With α = 5 µs, β = 0.0008 µs per value and P = 64: (a) above what vector length n does the ring beat recursive doubling? (b) How many bytes is that? (c) Rabenseifner’s algorithm costs 2 log₂ P · α + 2 (P − 1)/P · n β. Compare it with the other two at n = 8 and n = 10⁷.

    Answer(a) Recursive doubling costs 6α + 6nβ and the ring 126α + 1.96875 nβ. They are equal when (6 − 1.96875) nβ = 120α, i.e. n = 600 / (4.03125 × 0.0008) ≈ 186,000 values (`mpi.cost_model` agrees: 923.0 µs each at n = 186,047). (b) About 1.5 MB. (c) At n = 8: Rabenseifner about 60 µs, recursive doubling 30 µs, ring 630 µs, so recursive doubling is still best. At n = 10⁷: Rabenseifner 60 µs + 15.75 ms ≈ 15.8 ms, the ring 0.63 ms + 15.75 ms ≈ 16.4 ms, recursive doubling 48 ms. Rabenseifner wins for long messages: it has the ring's volume with logarithmically many rounds.
  5. Checkpointing a large MPI job. A job runs on 50,000 nodes whose MTBF is 10 years each; a checkpoint to the parallel file system takes 2 minutes. (a) What is the system MTBF? (b) Find Young’s interval and the first-order overhead C/τ + τ/(2M). (c) A checkpoint to a partner node’s memory takes 10 seconds. Redo (b). (d) Which failure does the partner checkpoint not survive, and how do multilevel schemes deal with it?

    Answer(a) 87,660 h / 50,000 ≈ 1.75 h ≈ 105 min. (b) τ = √(2 × 2 × 105) ≈ 20.5 min. The overhead is 2/20.5 + 20.5/210 ≈ 0.098 + 0.098 ≈ 0.195 per unit of work, so about 84% of the time is useful. Lecture 15's exact model with a 10-minute restart gives 74%. (c) τ = √(2 × (1/6) × 105) ≈ 5.9 min, with overhead ≈ 0.028 + 0.028 ≈ 0.056, about 95% useful (86% with the exact model and a 10-minute restart). (d) A failure that takes out a node *and* its partner, such as a rack's power supply or switch, loses both copies. Partners must be placed in different failure domains (Lecture 13). Multilevel checkpointing (e.g. SCR) writes frequent cheap checkpoints to partners or local storage, and rare expensive ones to the parallel file system for the failures the cheap level cannot survive.
  6. Vertex-cut arithmetic. On P = 32 machines with random edge placement, a vertex of degree D has on average P (1 − (1 − 1/P)^D) replicas. (a) Compute this for D = 100 and D = 3. (b) Compute the messages per iteration for each under the vertex cut, 2 × (replicas − 1). Compare with a hashed edge cut, where on average D (P − 1)/P of a vertex’s edges cross machines. (c) What does this suggest about which vertices to cut?

    Answer(a) D = 100: 32 × (1 − 0.96875¹⁰⁰) ≈ 32 × (1 − 0.042) ≈ 30.7 replicas. D = 3: 32 × (1 − 0.96875³) ≈ 2.91. (b) Vertex cut: 2 × 29.7 ≈ 59 messages and 2 × 1.91 ≈ 3.8. Edge cut: 100 × 31/32 ≈ 97 and 3 × 31/32 ≈ 2.9. (c) Cutting the high-degree vertex saves about 40% of its messages, and it also spreads its work over many machines. Cutting the low-degree vertex costs more than leaving it whole. Hybrid partitioners (PowerLyra) therefore cut only high-degree vertices and keep low-degree vertices with their edges. Greedy placement reduces replication further: 2.8 replicas on average on 32 machines in demo 06, against 7.1 for random.
  7. Consistency models. Which consistency model does each vertex program need? How would a chromatic engine provide it? (a) PageRank: reads its in-neighbours’ ranks, writes its own. (b) A Gibbs sampler for a Markov random field: draws a vertex’s new value from a distribution that depends on its neighbours’ current values. (c) An update that moves “mass” from a vertex to its neighbours, writing their values.

    Answer(a) Vertex consistency suffices. A stale neighbour value only delays convergence: PageRank's linear iteration has a nonnegative matrix of spectral radius d < 1, and such iterations converge with stale values too (§4.5). (b) Edge consistency. If two neighbours are sampled at once from each other's old values, neither draw comes from the right conditional distribution, and the chain may not converge to the target. Demo 06 Part C's colouring is a deterministic version of the same failure. A chromatic engine colours the graph and samples one colour class at a time (the chromatic Gibbs sampler). (c) Full consistency. Two vertices two hops apart can write the same neighbour, so even non-adjacent updates conflict. The chromatic engine needs a distance-2 colouring: a colouring of the graph's square.
  8. Connected components three ways. Label propagation: every vertex starts with its own id as its label and repeatedly takes the minimum of its label and its neighbours’ labels. (a) How many synchronous supersteps until the labels stop changing on a path of 1,000 vertices, and on a star of 1,000 vertices? (b) The path’s ids increase from one end to the other. An asynchronous engine sweeps the vertices in order along the path, starting at the end with id 0. How many updates does it need? What if the sweep runs the other way, toward id 0? (c) As a chain of MapReduce jobs, what must each job shuffle, and how many jobs does the path need?

    Answer(a) A label moves one hop per superstep. On the path, the smallest id must travel up to 999 hops: 999 supersteps of change, plus one in which nothing changes and the computation detects quiescence. On a star, at most two hops (leaf → centre → leaves): 2 supersteps (plus one). (b) In increasing order, each vertex sees its predecessor's freshly updated label 0, so one sweep of 1,000 updates converges; a second sweep confirms nothing changes. Sweeping toward id 0, each vertex has already been updated before the vertex behind it changes, so the minimum moves only one hop per sweep: about 1,000 sweeps, as bad as synchronous. Asynchrony helps when the schedule follows the direction information flows. That is the situation where GraphLab's engines shine, and it does not arise in PageRank (demo 06). (c) Each job shuffles every vertex's label to each neighbour (2E pairs for an undirected graph) plus every vertex's adjacency list, because the reduce must re-emit the graph for the next job. The path needs about 1,000 jobs. At a Hadoop job's start-up overhead of tens of seconds, that is hours for a graph that one thread processes in microseconds: McSherry's COST argument.
  • Problem Set 4 asks questions about MapReduce jobs and about which framework suits a given application. §2 and §6 give the concepts and the questions to ask. The PS’s computations and scenarios are not discussed, and no answers are given; the exercises above have different shapes.
  • Project 3 (scaling a cloud service) faces the same tension as §2.8–2.9 between task granularity, overhead and tail latency, for requests instead of tasks.

Further reading

  • J. Dean and S. Ghemawat, “MapReduce: Simplified Data Processing on Large Clusters”, OSDI 2004 (and the CACM 2008 version).
  • M. Isard, M. Budiu, Y. Yu, A. Birrell and D. Fetterly, “Dryad: Distributed Data-Parallel Programs from Sequential Building Blocks”, EuroSys 2007.
  • M. Zaharia et al., “Resilient Distributed Datasets: A Fault-Tolerant Abstraction for In-Memory Cluster Computing”, NSDI 2012.
  • J. Lin and C. Dyer, Data-Intensive Text Processing with MapReduce, Morgan & Claypool 2010 (combiners, in-mapper combining, design patterns).
  • J. Gray et al., “Data Cube: A Relational Aggregation Operator Generalizing Group-By, Cross-Tab, and Sub-Totals”, Data Mining and Knowledge Discovery 1997 (distributive, algebraic and holistic aggregates).
  • W. Gropp, E. Lusk and A. Skjellum, Using MPI, 3rd ed., MIT Press 2014.
  • R. Thakur, R. Rabenseifner and W. Gropp, “Optimization of Collective Communication Operations in MPICH”, IJHPCA 2005; P. Patarasuk and X. Yuan, “Bandwidth Optimal All-reduce Algorithms for Clusters of Workstations”, JPDC 2009.
  • L. Valiant, “A Bridging Model for Parallel Computation”, CACM 1990.
  • J. Young, CACM 1974; J. Daly, Future Generation Computer Systems 2006; A. Moody et al., “Design, Modeling, and Evaluation of a Scalable Multi-level Checkpointing System” (SCR), SC 2010.
  • G. Malewicz et al., “Pregel: A System for Large-Scale Graph Processing”, SIGMOD 2010.
  • Y. Low et al., “GraphLab: A New Framework for Parallel Machine Learning”, UAI 2010; “Distributed GraphLab”, PVLDB 2012.
  • J. Gonzalez, Y. Low, H. Gu, D. Bickson and C. Guestrin, “PowerGraph: Distributed Graph-Parallel Computation on Natural Graphs”, OSDI 2012.
  • R. Chen, J. Shi, Y. Chen and H. Chen, “PowerLyra: Differentiated Graph Computation and Partitioning on Skewed Graphs”, EuroSys 2015.
  • D. Chazan and W. Miranker, “Chaotic Relaxation”, Linear Algebra and its Applications 1969; D. Bertsekas and J. Tsitsiklis, Parallel and Distributed Computation: Numerical Methods, Prentice Hall 1989 (convergence of asynchronous iterations).
  • F. McSherry, M. Isard and D. Murray, “Scalability! But at what COST?”, HotOS 2015.

Preview of Lecture 25 — Large-scale storage and peer-to-peer: GFS, Ceph and DHTs

MapReduce read its input from, and committed its output to, a file system that spread huge files over thousands of machines and kept them available through failures. Lecture 25 looks at such storage systems:

  • GFS: a single master, large chunks, three replicas, and a record-append operation designed for many concurrent writers;
  • Ceph: no central lookup for data placement, because clients compute object locations with CRUSH;
  • consistent hashing and Chord: how a peer-to-peer system finds a key among nodes that come and go, in O(log n) hops.

术语表 (Glossary, English → 中文)

English中文
programming paradigm / programming model编程范式 / 编程模型
data parallelism / task parallelism数据并行 / 任务并行
map / reduce / shuffle映射 / 归约 / 洗牌(混洗)
intermediate key-value pair中间键值对
input split / partitioning function输入分片 / 分区函数
map task / reduce task / master / worker映射任务 / 归约任务 / 主节点 / 工作节点
combiner / in-mapper combining合并器 / 映射端内合并
associative / commutative / idempotent结合律的 / 交换律的 / 幂等的
distributive / algebraic / holistic aggregate分布式聚合 / 代数聚合 / 整体聚合
key skew / hot key / key salting键倾斜 / 热点键 / 键加盐
data locality数据本地性
barrier屏障(栅栏)
re-execution / at-least-once execution重新执行 / 至少一次执行
deterministic / non-deterministic operator确定性 / 非确定性算子
atomic commit / atomic rename原子提交 / 原子重命名
straggler / backup task (speculative execution)掉队者(慢节点) / 备份任务(推测执行)
task granularity任务粒度
lineage / resilient distributed dataset (RDD)血统(世系) / 弹性分布式数据集
message passing / rank / communicator消息传递 / 进程号(秩) / 通信子
SPMD (single program, multiple data)单程序多数据
point-to-point communication / tag点对点通信 / 标签
blocking / nonblocking / synchronous send阻塞 / 非阻塞 / 同步发送
unsafe program (relies on buffering)不安全程序(依赖缓冲)
collective operation / broadcast / allreduce / allgather集合通信 / 广播 / 全归约 / 全收集
reduce-scatter / recursive doubling / ring allreduce归约-散播 / 递归倍增 / 环形全归约
α–β (latency–bandwidth) modelα–β(延迟–带宽)模型
floating-point non-associativity / reproducibility浮点加法不满足结合律 / 可复现性
bulk-synchronous parallel (BSP) / superstep整体同步并行 / 超步
stencil / halo (ghost cell) exchange模板计算 / 光环(幽灵单元)交换
surface-to-volume ratio表面积与体积之比
coordinated checkpoint / global rollback协调检查点 / 全局回滚
multilevel checkpointing / partner checkpoint多级检查点 / 伙伴检查点
algorithm-based fault tolerance基于算法的容错
graph-parallel computation / vertex program图并行计算 / 顶点程序
vote to halt / aggregator投票停止 / 聚合器
gather-apply-scatter (GAS)收集-应用-分发
dynamic computation / signal / scheduler动态计算 / 信号(激活) / 调度器
synchronous / asynchronous engine同步 / 异步引擎
power-law degree distribution / natural graph幂律度分布 / 自然图
edge cut / vertex cut / replication factor边切分 / 点切分 / 复制因子
master / mirror replica主副本 / 镜像副本
scope / vertex, edge, full consistency作用域 / 顶点、边、完全一致性
chromatic engine / graph colouring着色引擎 / 图着色
serializability可串行化
asynchronous snapshot异步快照
label propagation / connected components标签传播 / 连通分量
COST (configuration that outperforms a single thread)超越单线程所需配置
← 返回课程目录