University Computer Science — Year 3 · Bachelor Year 3
24Parallel Programming
A laptop has many cores, and a program that uses one of them leaves the others idle. Splitting the work is easy to start and hard to finish: the parts must not interfere, the time spent splitting and joining must stay small, and some steps cannot be split at all. This chapter measures what a split gains on the laptop, proves the two laws that bound it, models a computation as a graph whose total size and longest path decide how fast any number of processors can run it, and builds the parallel prefix sum, a small algorithm that looks sequential and is not. Along the way the Rust compiler refuses a data race, two threads slow each other down without sharing a single variable, and the C compiler turns one loop into instructions that add four numbers at once.
You already know
The threads of a process share its memory and run interleaved, in an order nobody controls; a data race is two unsynchronised accesses to one location by two threads, at least one a write. A cache keeps recently used memory in lines of 64 bytes close to the processor (Year 2 volume). Divide and conquer splits a problem into smaller ones of the same kind, and its cost satisfies a recurrence such as , whose solution is (Year 1 volume). A scoped thread in Rust may borrow from the function that spawned it, because the scope waits for it before returning.
24.1 Speed-up and its limits
Definition 24.1 (Speed-up, efficiency)
Let be the time of a computation on one processor and its time on processors. Its speed-up on processors is , and its efficiency is . A speed-up of , efficiency 1, is linear.
The first program splits two jobs over scoped threads. One adds numbers, a job of one addition per number read from memory; the other runs a loop of shifts and exclusive ors on as many numbers, a job of 120 shift-and-xor steps, 240 operations, per number that touches no memory at all.
fn sum_mem(data: &[u32], p: usize) -> u64 {
let chunk = data.len().div_ceil(p);
thread::scope(|s| {
let parts: Vec<_> = data
.chunks(chunk)
.map(|c| s.spawn(move || c.iter().map(|&v| v as u64).sum::<u64>()))
.collect();
parts.into_iter().map(|h| h.join().unwrap()).sum()
})
}
fn sum_cpu(n: u64, p: u64) -> u64 {
thread::scope(|s| {
let parts: Vec<_> = (0..p)
.map(|t| {
s.spawn(move || {
(t * n / p..(t + 1) * n / p)
.map(mix)
.fold(0, u64::wrapping_add)
})
})
.collect();
parts
.into_iter()
.map(|h| h.join().unwrap())
.fold(0, u64::wrapping_add)
})
}
$ rustc --edition 2021 -O -o sum_threads sum_threads.rs && ./sum_threads
p memory-bound ms speed-up compute-bound ms speed-up
1 10.4 1.00 454.4 1.00
2 5.9 1.77 230.6 1.97
3 4.3 2.42 156.3 2.91
4 3.7 2.82 119.6 3.80
5 3.4 3.06 100.7 4.51
6 3.4 3.06 92.4 4.92
7 3.1 3.33 87.3 5.21
8 2.9 3.57 80.3 5.66
Neither job reaches 8. The compute-bound loop shares nothing, so its losses do not come from communication. Creating and joining eight threads costs microseconds, nothing against a run of 80 ms. The likelier causes are in the machine: the program gives every thread an equal chunk, but the laptop’s processor mixes fast and slower cores, so the slowest thread decides when the job ends; cores also run at lower clock speeds when more of them are busy, and other programs share them. The curve bends after , as these causes predict. The memory-bound sum stops earlier for a different reason, which no number of cores fixes: the cores share the path to memory, and a few of them already read as fast as it delivers.
Every program also has parts that do not split. If a fraction of its time on one processor is sequential, the rest gains at most .
Theorem 24.2 (Amdahl’s law)
If a fraction of a computation’s time on one processor must run sequentially and the rest divides perfectly among processors, its speed-up is , which increases with towards and never reaches it.
Proof. With , the sequential part takes on any number of processors, and the rest takes , so and . As grows the denominator decreases strictly towards , so increases strictly towards without reaching it. ∎
The law was presented by Gene Amdahl at a conference of 1967. Its lesson is severe: with 5 % of sequential work, a million processors give less than 20.
Amdahl’s law keeps the problem fixed. In practice a larger machine is used for a larger problem, whose parallel part grows while its sequential part stays the same, and the question becomes how much more work fits in the same time.
Theorem 24.3 (Gustafson’s law)
If a run on processors spends a fraction of its time in sequential work and the rest with all processors busy, the same computation takes times longer on one processor: its scaled speed-up is .
Proof. Take the parallel run’s time as 1. Its sequential part takes on one processor as well. Its parallel part keeps processors busy for , which is processor-time units, and one processor needs that long to do it. So and . ∎
The law is named after John Gustafson and his colleague Edwin Barsis; Gustafson presented it in 1988 in an article titled Reevaluating Amdahl’s law. The two laws do not contradict each other: they answer different questions. With measured on 8 processors, Gustafson’s scaled speed-up is 7.3, while Amdahl’s law with measured on one processor gives 4.7.
A speed-up can even exceed . When a job’s data do not fit in one core’s cache but its parts fit in caches, each part runs from its cache and the whole runs faster than times the original: the superlinear speed-up comes from more cache, not from more processors.
24.2 Task and data parallelism
Definition 24.4 (Task parallelism, data parallelism, fork–join)
Data parallelism applies the same operation to different parts of the data at once, as the chunks of Listing 24.1. Task parallelism runs different computations at once, such as the two recursive calls of a sort. In the fork–join pattern, a computation forks into parts that run in parallel and continues only when all of them have finished, at the join.
A recursive merge sort is fork–join: the two halves are sorted in parallel, then merged. The C program below forks a thread at each of the top levels of the recursion with POSIX threads, and joins it before the merge.
static void *sort(void *arg)
{
job *w = arg;
if (w->n < 2) return NULL;
size_t h = w->n / 2;
job left = {w->a, w->tmp, h, w->threads / 2};
job right = {w->a + h, w->tmp + h, w->n - h, w->threads - w->threads / 2};
if (w->threads > 1) { /* fork: the left half on a new thread, the right here */
pthread_t t;
pthread_create(&t, NULL, sort, &left);
sort(&right);
pthread_join(t, NULL); /* join */
} else {
sort(&left);
sort(&right);
}
merge(w->a, w->tmp, w->n);
return NULL;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o psort psort.c -lm && ./psort
p time ms speed-up
1 1354.2 1.00
2 716.2 1.89
4 418.5 3.24
8 303.1 4.47
Each thread sorts its own range of the array, so no two threads write the same element. In C, nothing checks it. In Rust, the borrow checker does: a scoped thread may hold a mutable reference only if no other thread holds a reference to the same data, which is exactly the absence of data races.
fn main() {
let mut count = 0u64;
thread::scope(|s| {
s.spawn(|| {
for _ in 0..1000 {
count += 1;
}
});
s.spawn(|| {
for _ in 0..1000 {
count += 1;
}
});
});
println!("{count}");
}
$ rustc --edition 2021 -O -o race_reject race_reject.rs && ./race_reject
error[E0499]: cannot borrow `count` as mutable more than once at a time
--> race_reject.rs:14:17
|
8 | thread::scope(|s| {
| - has type `&'1 Scope<'1, '_>`
9 | s.spawn(|| {
| - -- first mutable borrow occurs here
| _________|
| |
10 | | for _ in 0..1000 {
11 | | count += 1;
| | ----- first borrow occurs due to use of `count` in closure
12 | | }
13 | | });
| |__________- argument requires that `count` is borrowed for `'1`
14 | s.spawn(|| {
| ^^ second mutable borrow occurs here
15 | for _ in 0..1000 {
16 | count += 1;
| ----- second borrow occurs due to use of `count` in closure
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0499`.
[exit status 1]
The program is fixed by giving each thread its own counter and adding them after the join, as sum_threads.rs does, or by an atomic counter or a mutex; all three compile.
24.3 Work and span
A parallel program’s running time depends on how many processors run it and how they are scheduled. Two numbers of the computation itself bound it whatever the machine.
Definition 24.5 (Work, span, parallelism)
A computation is modelled as a directed acyclic graph, its DAG: one node per operation, taking unit time, and an edge from each operation to every operation that uses its result. The work of the computation, also written , is its number of nodes; its span , also written , is the number of nodes on a longest path, its critical path. Its parallelism is the ratio .
One processor runs one node per step, so it needs steps; infinitely many still need , since the nodes of a path run one after the other. On processors, therefore, (the work law) and (the span law). The parallelism is the largest speed-up the computation allows: .
The program below builds the DAGs of the chapter’s algorithms node by node and measures them.
def work_span(preds):
"""preds: node -> the nodes it depends on (a DAG)."""
@cache
def depth(v):
return 1 + max((depth(u) for u in preds[v]), default=0)
return len(preds), max(depth(v) for v in preds)
$ python workspan.py
algorithm n work span parallelism
sum (reduction) 8 7 3 2.3
sum (reduction) 1024 1023 10 102.3
Hillis-Steele scan 8 17 3 5.7
Hillis-Steele scan 1024 9217 10 921.7
Blelloch scan 8 14 5 2.8
Blelloch scan 1024 2046 19 107.7
merge sort, serial merge 8 24 14 1.7
merge sort, serial merge 1024 10240 2046 5.0
A schedule decides which ready nodes run at each step; a node is ready when all its inputs have run.
Definition 24.6 (Greedy scheduler, work stealing)
A greedy scheduler on processors never leaves a processor idle while a node is ready: at each step it runs of the ready nodes. Under work stealing, each processor keeps a queue of the tasks it has forked and works from it; a processor whose queue is empty takes a task from the queue of another, chosen at random.
Theorem 24.7 (Brent’s theorem)
A greedy scheduler runs a computation of work and span on processors in steps. Since every schedule needs at least steps, a greedy schedule takes at most twice as long as the best one.
Proof. Call a step complete if it runs nodes, incomplete otherwise. Each complete step runs of the nodes, so there are at most complete steps. In an incomplete step, the greedy scheduler runs every ready node. Let be the DAG of the nodes not yet run; its sources are exactly the ready nodes, and every longest path of starts at a source, since a longest path that started below a node would extend to it. Running all the sources shortens every longest path of by its first node, so each incomplete step decreases the span of by one, and there are at most of them. Hence . Every schedule takes at least steps and at least steps, so the best one takes , and . ∎
The theorem goes back to Richard Brent’s paper of 1974 on evaluating arithmetic expressions in parallel. The program below schedules two DAGs greedily and compares the result with both bounds.
def greedy(preds, p):
"""Steps taken by a greedy schedule, ready nodes taken oldest first."""
waiting = {v: len(us) for v, us in preds.items()}
users = {v: [] for v in preds}
for v, us in preds.items():
for u in us:
users[u].append(v)
ready = [v for v, k in waiting.items() if k == 0]
steps = 0
while ready:
run, ready = ready[:p], ready[p:]
for u in run:
for v in users[u]:
waiting[v] -= 1
if waiting[v] == 0:
ready.append(v)
steps += 1
return steps
$ python brent.py
random DAG: work W = 2000, span S = 214
p T_p max(W/p, S) W/p + S T_p / lower bound
1 2000 2000 2214 1.00
2 1000 1000 1214 1.00
3 667 667 881 1.00
4 501 500 714 1.00
5 402 400 614 1.00
6 338 334 547 1.01
7 296 286 500 1.03
8 266 250 464 1.06
merge sort of 256: work W = 2048, span S = 510
p T_p max(W/p, S) W/p + S T_p / lower bound
1 2048 2048 2558 1.00
2 1152 1024 1534 1.12
3 896 683 1193 1.31
4 768 512 1022 1.50
5 704 510 920 1.38
6 662 510 851 1.30
7 631 510 803 1.24
8 608 510 766 1.19
On the random DAG, whose parallelism is above 9, the greedy schedule is almost perfect for up to 8 processors. On the merge sort, parallelism 4, the final merges leave processors idle, and adding them beyond 4 helps little. A real runtime does not see the DAG in advance: tasks appear as the program forks them. Work stealing balances them as they appear; Blumofe and Leiserson proved in 1999 that it runs a well-structured fork–join computation in expected time , close to Brent’s bound.
24.4 Parallel algorithms
Definition 24.8 (Parallel reduction, prefix sum)
A parallel reduction combines values with an associative operation, such as or , by a tree of combinations: work , span . The prefix sum, or scan, of is the sequence of running totals: inclusive, at position , or exclusive, , which starts with 0.
Associativity is what allows the tree: equals , so the pairs can be added at the same time. Floating-point addition is not exactly associative, and a parallel sum of floats may differ in its last digits from the sequential one; the programs of this chapter add integers.
A scan looks sequential: each total needs the one before it. Hillis and Steele gave in 1986 a scan of span , in which every element adds the one places to its left in round ; it does additions instead of . Blelloch’s scan does , in a tree.
/// Exclusive scan in place (n a power of two): an up-sweep builds a tree of partial
/// sums, a down-sweep pushes the sums of the left subtrees down to the right.
pub fn blelloch(x: &mut [i64], trace: bool) -> (u64, u32) {
let (n, mut work, mut span) = (x.len(), 0, 0);
let mut d = 1;
while d < n {
for i in (2 * d - 1..n).step_by(2 * d) {
x[i] += x[i - d];
work += 1;
}
span += 1;
if trace {
println!("up {d}: {x:?}");
}
d *= 2;
}
x[n - 1] = 0;
while d > 1 {
d /= 2;
for i in (2 * d - 1..n).step_by(2 * d) {
let left = x[i - d];
x[i - d] = x[i];
x[i] += left;
work += 1;
}
span += 1;
if trace {
println!("down {d}: {x:?}");
}
}
(work, span)
}
$ rustc --edition 2021 -O -o scan scan.rs && ./scan
rain: [0, 62, 0, 29, 8, 34, 0, 0]
up 1: [0, 62, 0, 29, 8, 42, 0, 0]
up 2: [0, 62, 0, 91, 8, 42, 0, 42]
up 4: [0, 62, 0, 91, 8, 42, 0, 133]
down 4: [0, 62, 0, 0, 8, 42, 0, 91]
down 2: [0, 0, 0, 62, 8, 91, 0, 133]
down 1: [0, 0, 62, 62, 91, 99, 133, 133]
n Hillis-Steele work span Blelloch work span
16 49 4 30 8
256 1793 8 510 16
4096 45057 12 8190 24
65536 983041 16 131070 32
1048576 19922945 20 2097150 40
scan.rs prints it; shaded cells written in that round, even when the value stays the same. After the up-sweep the last cell holds the total, 133; it is replaced by 0 and the down-sweep ends with the exclusive running totals.Theorem 24.9 (Blelloch’s scan)
For , Blelloch’s scan computes the exclusive prefix sums with additions in rounds, the additions of each round being independent.
Proof. View positions as the leaves of a complete binary tree; a node of height covers consecutive positions and is stored at the last of them. Up-sweep. In round , position adds position : it then holds the sum of its node’s left child (stored at ) and right child (stored at ), by induction on . The positions written in one round are distinct and none is read by another addition of the round, so the additions are independent. Round does additions, in all, in rounds. Down-sweep. Claim: when the down-sweep reaches height , the position of each node of height holds the sum of all positions before the node. It holds at the root, set to 0. At a node with that value stored at , whose left child is stored at and still holds the left sum from the up-sweep, the round writes at and at : exactly the sums before the left and the right child. At height 0 every position holds the sum before it. The down-sweep, too, does independent additions in rounds. ∎
The DAG of workspan.py finds a span of , one less than the rounds: the root’s sum, computed by the last addition of the up-sweep, is replaced by 0, so no path runs through it into the down-sweep.
A scan on processors does not need a tree of leaves. The blocked scan of the weekend problem cuts the array into blocks: each processor sums its block, the sums are scanned, and each processor scans its block again from the total before it; exercise 24.11 analyses it.
Parallel threads can also slow each other down without sharing data. A cache works in lines of 64 bytes, and a core must hold a line on its own to write it; two cores writing two different variables of one line pass the line back and forth.
Definition 24.10 (False sharing)
False sharing occurs when threads on different cores repeatedly write different variables that lie in the same cache line: the line moves between the cores’ caches at every write, though no variable is shared.
#define MAXP 8
struct padded { _Alignas(64) atomic_long v; };
static _Alignas(64) atomic_long packed[MAXP]; /* eight counters in one 64-byte line */
static struct padded spread[MAXP]; /* one counter per line */
static void *bump(void *arg)
{
atomic_long *c = arg;
for (long i = 0; i < STEPS; i++)
atomic_fetch_add_explicit(c, 1, memory_order_relaxed);
return NULL;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o false_sharing false_sharing.c -lm && ./false_sharing
p adjacent ms padded ms ratio
1 191.3 194.5 1.0
2 762.5 195.8 3.9
4 2507.4 208.1 12.0
8 5832.6 351.5 16.6
all counts correct: yes
With one thread the two layouts take the same time. With 8, each thread does the same work as alone, yet the adjacent counters take more than 30 times longer than with one thread, while the padded ones take less than twice as long. The fix is the padding of struct padded: one counter per line.
24.5 Vector instructions and accelerators
Parallelism also lives inside one core.
Definition 24.11 (SIMD, vectorisation)
A SIMD instruction (single instruction, multiple data) applies one operation to several values held side by side in a wide register, its lanes: a 16-byte register holds four 32-bit floats. Vectorisation is the compiler’s rewriting of a loop so that each instruction processes several iterations, one per lane.
A loop can be vectorised only if running several iterations at once gives the same result as running them in order. GCC reports what it did when asked.
/* saxpy.c -- y = a x + y over n floats, and a running sum over n floats. */
void saxpy(int n, float a, const float *restrict x, float *restrict y)
{
for (int i = 0; i < n; i++)
y[i] = a * x[i] + y[i];
}
void running_sum(int n, float *y)
{
for (int i = 1; i < n; i++)
y[i] = y[i] + y[i - 1];
}
$ gcc -O3 -fopt-info-vec-optimized -c saxpy.c
saxpy.c:4:23: optimized: loop vectorized using 16 byte vectors
saxpy.c:4:23: optimized: loop vectorized using 8 byte vectors
$ gcc -O3 -fopt-info-vec-missed -c saxpy.c 2>&1 | grep -E '^saxpy.c:1[01]'
saxpy.c:10:23: missed: couldn't vectorize loop
saxpy.c:11:24: missed: not vectorized, possible dependence between data-refs *_6 and *_3
$ gcc -O3 -S -o - saxpy.c | grep -E 'mulps|addps|mulss|addss'
mulps %xmm2, %xmm1
addps %xmm3, %xmm1
mulps %xmm2, %xmm1
addps %xmm2, %xmm1
mulss (%rcx,%rax,4), %xmm0
addss (%rdx), %xmm0
addss (%rax), %xmm0
ps, four floats each) and scalar ones (ss, one float).The restrict qualifiers promise that x and y do not overlap; without them the compiler would have to check at run time that a write to y cannot change a later x[i]. The running sum is a scan, and its dependency of distance one keeps every lane waiting for the one before.
A graphics processor, or GPU, takes the same idea much further: thousands of lanes grouped into many cores, each group running one instruction on many data, with its own memory hierarchy between the lanes and the main memory. It suits data parallelism on large arrays, the matrix products of neural networks above all; the One Artificial Intelligence Book and One Quant Book series return to it at length.
24.6 Exercises
Exercise 24.1 ★
A program spends 10 % of its single-processor time in sequential work. What speed-up does Amdahl’s law give on 8 processors, and what is its limit? What sequential fraction would allow a speed-up of 6 on 8 processors?
Solution
Solution of Exercise 24.1.
, and the limit is . A speed-up of 6 on 8 processors needs , so and .
Exercise 24.2 ★
Draw the DAG of the evaluation of , one node per operation. Give its work, span and parallelism. Do the same for .
Solution
Solution of Exercise 24.2.
The four additions , , , have no inputs computed by other nodes; the two products each use two of them, and the final addition uses both products. Work 7, span 3 (an addition, a product, the final addition), parallelism . The second expression is a chain of four additions, each using the one before: work 4, span 4, parallelism 1. Since addition is associative, gives the same value with span 3.
Exercise 24.3 ★
A computation has work and span . Bound the time of a greedy schedule on 8 processors, and on 10,000, from above and below. Beyond how many processors can the speed-up no longer grow much?
Solution
Solution of Exercise 24.3.
On 8 processors, . On 10,000 processors, . The parallelism is : the speed-up can never exceed it, and beyond about a thousand processors the span dominates, so further processors add almost nothing.
Exercise 24.4 ★
exercises/ex4_loops.c holds three loops: y[i] = 2 * y[i + 1], y[i] = y[i - 4] + x[i] and y[i] = y[i - 1] + x[i]. Predict which of them gcc -O3 vectorises with 16-byte vectors of floats, then check with -fopt-info-vec-optimized.
Solution
Solution of Exercise 24.4.
(a) is vectorised: each iteration reads before iteration overwrites it, and a vector of four iterations also reads before writing , so the order of reads and writes on each element is kept. (b) is vectorised: the four iterations of a 16-byte vector read , all written by earlier vectors. (c) is not: iteration needs the value iteration has just written, so no two iterations can run at once. GCC reports lines 4 and 10 vectorised, with 16-byte vectors and 8-byte ones for the remainder, and line 16 missed; a test checks it.
Exercise 24.5 ★★
A parallel sum in C has each of its threads run total += a[i] on one global total. Run exercises/ex5_interleave.py, which plays the load, add and store of two threads in a scripted order, and explain the total it prints. Fix the C program so that it is correct for every interleaving without a lock in the loop.
Solution
Solution of Exercise 24.5.
Each += is three steps. In the script, thread 0 loads 0 and adds 5; thread 1 loads total, still 0, before thread 0 stores 5; thread 0 stores 5; thread 1 adds 3 to its register, 0, and stores 3 over the 5. The 5 is lost, and the remaining additions give instead of 19. On real hardware the steps interleave at random, and the total varies from run to run. The fix, exercises/ex5_sum.c, gives each thread a local running sum over its own slice and stores it in its own slot of an array; the main thread adds the slots after joining all the threads, when no thread writes any more. Nothing is shared while the threads run, so no interleaving can lose an update. A C test compares the result with the sequential sum for 55 sizes and to 8.
Exercise 24.6 ★★
Write par_max(a: &[i64], p: usize) -> Option<i64>, which returns the largest element of a computed by scoped threads, and None if a is empty or . Test it against the sequential maximum.
Solution
Solution of Exercise 24.6.
exercises/ex6_max.rs returns None for an empty slice or . Otherwise it cuts the slice into chunks of elements, spawns one scoped thread per chunk returning the chunk’s maximum (never empty, so unwrap is safe), and returns the maximum of the joined results. The scope guarantees that every thread has finished before the slice it borrows can be dropped. The Rust test compares it with a.iter().max() for 300 sizes and to 9, including larger than the slice.
Exercise 24.7 ★★
Prove that Hillis and Steele’s scan is correct, does additions for , and has span . For and 8 processors, compare the two scans by Brent’s bound.
Solution
Solution of Exercise 24.7.
Facts used: induction on rounds. Claim: after the round of stride , position holds . Before the first round, with read as , it holds . A round of stride adds to , for , the old , the sum of the values ending at ; together they cover the values ending at (or all values from , clipped at the left). For , the old value already starts at . After the round , every position holds . The round of stride does additions, in all, in rounds; each addition reads only results of the previous round, so the span is , as workspan.py measures. For and , Brent’s bound is for Hillis and Steele and for Blelloch: 9.5 times less. Even Hillis and Steele’s lower bound, , is above Blelloch’s upper bound: with 8 processors the extra work costs far more than the shorter span saves.
Exercise 24.8 ★★
Prove that the merge sort DAG of elements, with sequential merges as in workspan.py, has work and span . What is its parallelism, and why does the parallelism of psort.c stay small?
Solution
Solution of Exercise 24.8.
Facts used: the DAG’s recursive structure. Merge sort of elements is two sorts of followed by a merge chain of nodes, and one element needs no node. The work satisfies , , so : each of the levels of merges outputs elements. Both halves run in parallel and the merge chain needs both, so the span satisfies , : . The parallelism is a little above : 5.0 for 1,024 elements, and only 12 for , far below . The last merge alone is a chain of steps, half the span; psort.c merges sequentially in the same way, so its parallelism is just as small, and the top merges keep most threads idle (exercise 24.12).
Exercise 24.9 ★★
Starting threads has a cost: model the time on processors as , with apart from the cost. Find the real that minimises , and the best integer and speed-up for and . What does the model say about adding processors beyond it?
Solution
Solution of Exercise 24.9.
vanishes at , and , so it is a minimum. For , : ; exercises/ex9_overhead.py finds the best integer, 31, with , a speed-up of 8.96, against Amdahl’s limit of 20 without the cost. Beyond the cost grows faster than the parallel part shrinks: adding processors makes the program slower, and the speed-up falls. With a cost ten times smaller, the best is 97 and the speed-up 14.39.
Exercise 24.10 ★★★
To merge two sorted arrays in parallel, take the median of the larger one, find by binary search where it falls in the other, and merge the two lower parts and the two upper parts in parallel. Prove that this merge has span and work , and deduce the work and span of the merge sort that uses it.
Solution
Solution of Exercise 24.10.
Facts used: binary search takes steps; a recurrence solves to . Let be the larger input, of elements, and the other. The median of splits it into two halves of at most elements, and binary search splits at the same value; the elements of the lower parts are all at most those of the upper parts, so the two merges of the parts, placed side by side, give the merged output. Each part has at most elements. Span: the two recursive merges run in parallel, so ; unrolling, the sizes shrink geometrically, there are levels, and each costs : . Work: with . Show by induction: the right-hand side is at most , and , so it is at most as soon as , which holds for and ; small are covered by choosing large. So . Merge sort: , the same work as sequentially, and : the parallelism grows as , against with a sequential merge.
Exercise 24.11 ★★★
Prove that the blocked scan of Listing 24.9 is correct for any and . Count its additions, and its time on processors if each block costs its length and the middle scan is sequential. Show that its speed-up over the sequential scan, counted in additions, stays below , and say how to keep the middle step small for very large .
Solution
Solution of Exercise 24.11.
Facts used: induction on the blocks. Let the blocks be , (the last may be shorter, and an empty input gives no block). offset[i] is computed as offset[i-1] + sums[i-1], from offset[0] = 0, so by induction it is the sum of the blocks before . Pass 2 starts each block’s running total from its offset, so the value written at a position of is the sum of the blocks before plus the values of up to it: the inclusive prefix sum. Each block writes only its own part of out, which chunks_mut hands to its thread alone. Additions: pass 1 does (one per value), the middle , pass 2 : , against for the sequential scan. Time: with blocks of , . The speed-up over the sequential scan, in additions, is . For large the middle step dominates once approaches ; it is itself a scan of values and can be done by Blelloch’s tree in rounds, giving .
Exercise 24.12 ★★★
Model psort.c: below the top levels each thread sorts elements alone, and at the top levels each merge is sequential. Derive and the speed-ups the model predicts for and , compare them with Output 24.2, and explain the shape of the gap.
Solution
Solution of Exercise 24.12.
At the top level one merge of elements runs alone; at the next, two merges of run on two threads, and so on for levels: steps. Below, each of the threads sorts elements in steps. So and . For : , , , , predicted speed-ups 1.92, 3.43 and 5.49. Output 24.2 measured 1.89, 3.24 and 4.47 on the author’s laptop: close for 2 threads, then further and further below. The model counts steps as if memory were free, but a merge does almost nothing but read and write memory: two inputs, an output, and a copy back. As more threads merge at once they share the path to memory, as the memory-bound sum of Output 24.1 did, so the gap grows with . The shape to expect is a curve under the model’s, bending away from it as grows.
24.7 Weekend problem
Problem 24.1
Weekend problem — Prefix sums of the town’s weather
The town’s two weather stations record the rain of every day. A running total answers questions such as how much rain fell between two dates: a subtraction of two totals. This problem computes the running totals of days, the town’s two years repeated, sequentially and in parallel, and compares the parallel time with what the theory allows.
pub fn scan_par(a: &[i64], out: &mut [i64], p: usize) {
let block = a.len().div_ceil(p).max(1);
let sums: Vec<i64> = thread::scope(|s| {
let hs: Vec<_> = a
.chunks(block)
.map(|c| s.spawn(move || c.iter().sum()))
.collect();
hs.into_iter().map(|h| h.join().unwrap()).collect()
});
let mut offset = vec![0; sums.len()];
for i in 1..sums.len() {
offset[i] = offset[i - 1] + sums[i - 1];
}
thread::scope(|s| {
for ((c, o), off) in a.chunks(block).zip(out.chunks_mut(block)).zip(offset) {
s.spawn(move || {
let mut run = off;
for (x, v) in o.iter_mut().zip(c) {
run += v;
*x = run;
}
});
}
});
}
$ rustc --edition 2021 -O -o weather_scan weather_scan.rs && ./weather_scan
sequential scan: 13.8 ms
p blocked scan ms speed-up
1 22.2 0.62
2 14.0 0.99
3 10.7 1.29
4 8.7 1.59
5 7.5 1.84
6 7.0 1.96
7 7.1 1.95
8 7.2 1.91
Part I — The sequential scan.
- How many additions does the sequential scan of values do, and what are its work and span as a DAG?
- Which dependency makes it sequential?
- How is the rain between day and day obtained from the totals, and in how many operations?
- Why can the totals be computed in another order at all? Which property of addition is used?
- Rain is stored in tenths of a millimetre, as integers. Why not as floats?
- What do the totals of the 8 days of Output 24.6 say about the first week?
Part II — Blelloch’s algorithm.
- What are the work and the number of rounds of Blelloch’s scan for ?
- Check in Output 24.6 that the work for is .
- Why is the span measured by
workspan.pyone less than the number of rounds? - What is the parallelism of Blelloch’s scan for ?
- How many additions do Hillis and Steele need for , and when would their scan be preferred?
- What does the blocked scan of Listing 24.9 do differently from Blelloch’s tree?
Part III — Brent’s bound.
- Write Brent’s bound for Blelloch’s scan of on processors.
- What speed-up over the sequential scan does it guarantee on processors, counted in additions?
- Compute it for .
- What upper limit does the work law put on the same speed-up?
- Why do the two bounds almost coincide here?
- What would the bounds become on 1,000 processors?
Part IV — Measured.
- Why is the blocked scan on one thread slower than the sequential scan, but faster than half its speed?
- What speed-up does the laptop measure on 8 threads, against the bound of question 16?
- The compute-bound loop of Output 24.1 reaches more than 5. What makes the scan different?
- Why does the scan’s curve flatten at about the same number of threads as the memory-bound sum’s?
- What would make the parallel scan worth it on this machine?
- Sum up: what does the theory predict for 8 cores and , and what does the laptop measure?
Solution
Solution of Problem 24.1.
1. The first total is ; each later one is one addition, in all (the program adds from 0, one more). As a DAG it is a chain: work , span , parallelism 1.
2. Each total is the previous total plus one value: every addition needs the result of the one before.
3. With inclusive totals , the rain from day to day is (or if ): one subtraction, whatever the length of the period.
4. Associativity: can be grouped in any way, so partial sums of blocks or of tree nodes can be computed first and combined later.
5. Integer addition is exact and associative. Floating-point addition rounds, so a parallel scan that groups the additions differently would give totals that differ in their last digits from the sequential ones, and the program’s check of equality would fail.
6. The exclusive totals end at 133 after the eighth day, and the eighth day had no rain: 13.3 mm fell in the first week, 6.2 mm of it on its second day.
7. Work additions, in rounds.
8. , the value printed.
9. The last up-sweep addition computes the total at the root, which the down-sweep replaces by 0: no addition uses it, so the longest path of the DAG has nodes, one fewer than the rounds.
10. .
11. , eleven and a half times as many. Its span is half of Blelloch’s, which pays only when there are about as many processors as values, as on the lanes of a GPU for a short array.
12. It uses blocks instead of a tree of leaves: two passes over the data, each split among the threads, and a sequential scan of the block sums in between. Its work is about , as Blelloch’s, but it has only three phases, and each thread reads consecutive memory.
13. .
14. The sequential scan does about additions, so a guaranteed speed-up of .
15. 0.50, 1.00, 2.00 and 4.00, to two decimals: the span changes nothing visible.
16. , so the speed-up is at most , about : 4 on 8 processors.
17. The parallelism, over 700,000, dwarfs 8: the span term 47 is negligible against , about 4 million, so the upper and lower bounds differ by about one part in 100,000.
18. On 1,000 processors, guaranteed, against 500 at most: still almost equal, since 1,000 is far below the parallelism.
19. It reads the data twice, once to sum each block and once to scan it, where the sequential scan reads it once; but the first pass only reads, with no writes, and so costs less than a scan pass. The result, 0.62, lies between 0.5 and 1.
20. About 1.9 on 8 threads, against the bound of 4.
21. The scan does one addition for each 8-byte value it reads and each it writes: it is limited by memory, like the memory-bound sum. The compute-bound loop does 120 shift-and-xor steps, 240 operations, per value and touches no memory.
22. Both are bound by the same shared path to memory, which a few threads already saturate; beyond that, more threads only queue for it.
23. More computation per value read: a scan fused with the work that produces or consumes the values, while they are in cache, or a scan with an expensive operation. On data that fit in the cores’ caches, too, the threads would not compete for memory.
24. The theory guarantees almost exactly 4 on 8 cores for (Brent’s bound and the work law agree to five digits), half of 8 because the parallel scan does twice the additions. The laptop measures about 1.9 in one run, under half the bound: on this machine the scan is limited by memory, not by additions, and the curve flattens after five or six threads.