Lecture 8 · Data-Parallel Thinking

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

课程源码 ZIP ↓

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

本篇目录

Maps to: Stanford CS149 Fall 2025, Lecture 8 (Oct 16), slide deck 08_dataparallel (51 slides). Context for Programming Assignment 3 (scan and “find repeats” in CUDA). Sources: the public Fall 2025 slides; the 2023 lecture video; G. Blelloch, “Prefix Sums and Their Applications” (1990). Every experiment and number below was written for these notes and run on the author’s machine (Apple M4 Pro: 8 performance cores, and its GPU through Metal; clang 21, Swift 6.3, macOS 27). Code: code/lecture08/. Reading time: ~75 minutes for the prose; ~15 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Describe a computation as operations on sequences (序列), the data-parallel (数据并行) style, instead of as what each worker does.
  2. Define and parallelize map (映射), fold/reduce (折叠/归约) and scan (扫描, prefix sum 前缀和), inclusive and exclusive, and state what the operator must satisfy (associativity (结合律), an identity element).
  3. Compare scan algorithms by work (工作量) and span (跨度): Hillis–Steele (O(N log N), O(log N)), Blelloch’s work-efficient (工作高效) up-sweep/down-sweep (O(N), O(log N)), and the chunked scan of a few cores. Explain why the “inefficient” one is the right choice inside a warp and the chunked one on a CPU.
  4. Build large scans hierarchically on a GPU (warp → block → grid).
  5. Use segmented scan (分段扫描) to process sequences of sequences, e.g. sparse matrix-vector multiplication (稀疏矩阵向量乘) in CSR format.
  6. Use gather (收集), scatter (分散) and sort (排序) to turn irregular, synchronization-heavy computations (building a grid of particle lists, a histogram) into regular data-parallel ones.

0.2 Prerequisites and scope

  • Prerequisites: Lecture 5 (work and span, load imbalance), Lecture 6 (bandwidth, contention, the histogram demo), Lecture 7 (warps, blocks, shared memory, SIMT).
  • Scope: the primitives and how to implement them efficiently at each level of a machine. PA3 asks you to write an exclusive scan and “find repeats” in CUDA; these notes explain the algorithms and do not give the assignment’s code.

0.3 Section → code map

SectionIdeaDemo in code/lecture08/
§2map and reduce02_primitives_cpu (Part B), dp.h
§3scan algorithms: work, span, warps, blocks, cores01_scan_algorithms.py, 02_primitives_cpu (Part A), 05_metal_scan.swift
§4segmented scan, sparse matrix-vector multiply03_sparse_matvec, dp.h
§5gather, scatter, sort02_primitives_cpu (Part B), dp.h
§6the particle grid, histogram by sort04_particle_grid

Run them all with cd code/lecture08 && make run (~15 seconds).

0.4 Notation

  • N = number of elements, P = number of processors (threads). ⊕ = an associative binary operator with identity I (for +, I = 0). “a2-5” = a2 ⊕ a3 ⊕ a4 ⊕ a5, as on the slides.
  • Work = total operations; span = longest chain of dependent operations (Lecture 5).

1. Thinking in sequences

1.1 A change of viewpoint

Slide 2: so far we described parallel programs by what each worker does and how work is assigned to workers. Today the view changes: describe algorithms as operations on sequences of data: map, filter, fold/reduce, scan and segmented scan, sort, groupBy, join, partition/flatten. The main idea: high-performance parallel implementations of these operations exist. A program written in terms of them can often run efficiently on a parallel machine, if you can avoid being bandwidth-bound (slide 2’s footnote, which returns at the end).

1.2 Why expose so much parallelism?

Slides 3–4. Big machines need it: many cores, many machines, SIMD lanes inside multi-threaded cores. A V100 GPU can run 163,840 CUDA threads at once (Lecture 7). A program that does not expose that much parallelism, and does not have high arithmetic intensity, will not run efficiently on a GPU.

1.3 Dependencies decide

Slide 5: the key part of parallel programming is understanding where dependencies exist between operations. In x = a + b; y = b * 7; z = (x - y) * (x + y); the first two statements are independent; z depends on both. The lack of dependencies implies the potential for parallel execution. Data-parallel operations are, by definition, operations whose structure tells the implementation which dependencies exist.

1.4 Sequences, not arrays

Slides 6–7. The data-parallel model organizes computation as operations on sequences of elements, e.g. “perform the same function on all elements”. NumPy’s C = A + B is the everyday example. The key data type is the sequence: an ordered collection (C++ Sequence<T>, Scala List[T], Pandas dataframes, PyTorch/JAX tensors, Haskell seq T). The important difference from an array: programs only access elements of a sequence through specific operations, not through direct element access. That restriction is what gives the implementation its freedom.


2. Map and fold

2.1 Map

Slide 8. map is a higher-order function (it takes a function as an argument). It applies a side-effect-free unary function f : a → b to every element of the input sequence and produces an output sequence of the same length:

int f(int x) { return x + 10; }
int a[] = {3, 8, 4, 6, 3, 9, 2, 8};
int b[8];
std::transform(a, a + 8, b, f);      // b = 13 18 14 16 13 19 12 18

It is map :: (a → b) → seq a → seq b in Haskell and vmap in JAX.

Slide 9: because f is a function (no side effects), applying it to the elements in any order gives the same output. The implementation may reorder and parallelize however it sees fit: split s into P pieces, map each in parallel, concatenate. dp::map in dp.h does exactly that with P contiguous chunks.

2.2 Fold and parallel fold

Slide 10: fold (fold left) applies a binary operation f : (b, a) → b to an accumulated value and each element, seeded with an initial value: fold 10 (+) [3 8 4 6 3 9 2 8] = 10 + 3 + 8 + … = 53. Written this way it is a chain of dependent steps.

Slide 11: the parallel fold needs one more thing, a combiner comb : (b, b) → b that merges the results of folding different pieces, and an initial value that is the identity for both f and comb. Each piece is folded from the identity, and the partial results are combined. If f itself is an associative binary operator on one type, f(f(a, b), c) = f(a, f(b, c)), it serves as its own combiner. That is the usual reduce.

Associativity is a real requirement. Integer + and max are associative. Floating-point + is only approximately so: Lecture 3 summed the same numbers in two orders and got different last digits. A parallel reduction of floats therefore gives slightly different, equally valid, results than a serial loop. The demos of this lecture use integer (or exactly representable) data so that every parallel result can be compared with the serial one bit for bit.

02_primitives_cpu, Part B on 64M integers with 8 threads: map 1.8×, reduce 2.5×. Both are bandwidth-bound (Lecture 3), so the gain is what the memory system allows beyond one core’s share.


3. Scan

3.1 Definition

Slides 12 and 14. Given an associative ⊕ with identity I and A = [a0, a1, …, a(n−1)]:

  • inclusive scan: [a0, a0⊕a1, a0⊕a1⊕a2, …]
  • exclusive scan: [I, a0, a0⊕a1, …], where element i holds the combination of everything before a_i.

With ⊕ = +, the inclusive scan is the prefix sum: scan_inclusive(+, [3 8 4 6 3 9 2 8]) = [3 11 15 21 24 33 35 43]. The serial definition is a loop where every output depends on the previous one:

out[0] = in[0];
for (i = 1; i < N; i++) out[i] = op(out[i-1], in[i]);

It looks inherently sequential. The rest of this section shows how it is not.

Why care about scan? Because it answers questions like “where does element i go?” for whole sequences at once. For example: an exclusive scan of the counts of a radix sort gives every element’s destination (§5.2); an exclusive scan of 0/1 flags gives the output position of each kept element in a filter; a segmented scan sums the rows of a sparse matrix (§4). PA3’s “find repeats” is built on an exclusive scan of flags.

3.2 Hillis–Steele: few steps, much work

Slide 15’s “data-parallel inclusive scan”. In step d (d = 1, 2, 4, …), every element i ≥ d adds element i − d, all at once, reading the previous step’s values. 01_scan_algorithms.py traces it symbolically on 16 elements:

a0  a1    a2    a3    a4    a5    a6    a7    a8    a9    a10    a11    a12    a13    a14    a15
a0  a0-1  a1-2  a2-3  a3-4  a4-5  a5-6  a6-7  a7-8  a8-9  a9-10  a10-11 a11-12 a12-13 a13-14 a14-15   (+1)
a0  a0-1  a0-2  a0-3  a1-4  a2-5  a3-6  a4-7  a5-8  a6-9  a7-10  a8-11  a9-12  a10-13 a11-14 a12-15   (+2)
a0  a0-1  a0-2  a0-3  a0-4  a0-5  a0-6  a0-7  a1-8  a2-9  a3-10  a4-11  a5-12  a6-13  a7-14  a8-15    (+4)
a0  a0-1  a0-2  a0-3  a0-4  a0-5  a0-6  a0-7  a0-8  a0-9  a0-10  a0-11  a0-12  a0-13  a0-14  a0-15    (+8)

Span O(log N): 4 steps for 16 elements. Work N log₂ N − (N − 1): 49 additions instead of the serial 15, and about 19× the serial work for N = 1M. Slide 15 calls it “inefficient compared to the sequential algorithm”.

3.3 Blelloch’s work-efficient scan

Slides 16–17 (an exclusive scan, N a power of 2) uses two phases on a tree laid over the array:

up-sweep:   for d = 0 to log2(n) - 1:
              forall k = 0 to n-1 by 2^(d+1):
                a[k + 2^(d+1) - 1] = a[k + 2^d - 1] + a[k + 2^(d+1) - 1]
            a[n-1] = 0
down-sweep: for d = log2(n) - 1 down to 0:
              forall k = 0 to n-1 by 2^(d+1):
                tmp = a[k + 2^d - 1]
                a[k + 2^d - 1] = a[k + 2^(d+1) - 1]
                a[k + 2^(d+1) - 1] = tmp + a[k + 2^(d+1) - 1]

The up-sweep builds partial sums of growing ranges (a0-1, a0-3, a0-7, a0-15) like a reduction tree. The down-sweep sets the root to the identity and pushes each prefix back down: at every node, the left child gets the parent’s prefix, and the right child gets the parent’s prefix plus the left subtree’s total. Demo 01 prints every step; the final line is 0 a0 a0-1 a0-2 … a0-14, the exclusive scan.

Work 2(N − 1) additions (30 for 16 elements): O(N), like the serial loop. Span 2 log₂ N steps. Slide 17 asks for the constants and about locality. The constants are 2 for work and 2 for span. Locality is poor: in the upper levels only a few elements are active, far apart in memory.

3.4 Scan on two cores, or P cores

Slides 18–19. With only two processors, the tree algorithm wastes almost all its parallelism: it has thousands of independent additions per level but only 2 processors to run them. Instead:

  1. P1 scans elements 0–7 sequentially while P2 scans 8–15 sequentially;
  2. let base = a0-7 (P1’s total);
  3. both add the base to the second half: P1 to elements 8–11, P2 to 12–15.

Work ≈ 1.5N, and the data access has very high spatial locality (contiguous scans). dp.h implements the P-chunk generalization as reduce, then scan: (1) each thread reduces its chunk to a total; (2) a serial exclusive scan of the P totals gives each chunk its base; (3) each thread scans its chunk starting from its base. Every element is read twice and written once.

02_primitives_cpu, Part A measures all three on 64M integers with 8 threads (results identical to the serial loop):

algorithmthreadstimevs. serial looppasses over the data
serial loop117.9 ms1.00×1
chunked, reduce-then-scan (dp.h)85.3 ms3.4×2
Hillis–Steele8158 ms0.11×26
Blelloch (work-efficient)835 ms0.52×52, strided

Hillis–Steele does 26 full passes over 256 MiB with a barrier after each, an O(log N) span for a machine that needs only 8-way parallelism. Blelloch does O(N) additions and still loses to one core: 52 passes, and at the upper levels each addition touches two elements far apart, a new cache line each, with few updates per barrier. Work-efficiency counts additions; this machine charges for passes, cache lines and synchronization.

One more surprise: the serial loop runs at only ~30 GB/s, far below what one core can stream. A serial scan is limited by its chain of dependent additions (~1 cycle each), not by memory. Splitting that chain is exactly what the parallel scan does.

3.5 Scan inside a warp

Slide 20’s CUDA code scans 32 elements with one warp, as an SPMD program on 32-wide SIMD:

__device__ int scan_warp(int *ptr, const unsigned int idx) {
    const unsigned int lane = idx % 32;           // index of thread in warp (0..31)
    for (int i = 0; i < 5; i++) {                 // 5 steps because 2^5 = 32
        int shift = 1 << i;
        if (lane >= shift) {
            int tmp1 = ptr[idx - shift];
            int tmp2 = ptr[idx];
            __syncwarp();
            ptr[idx] = tmp1 + tmp2;
            __syncwarp();
        }
    }
    return (lane > 0) ? ptr[idx - 1] : 0;
}

That is Hillis–Steele, with work N log N. Slide 21’s point: the work-efficient formulation is not beneficial in this context, because it results in low SIMD utilization. It would require more than twice the number of instructions. Demo 01, Part D runs both on Lecture 7’s SIMT simulator:

algorithm (one warp, 32 values)correctwarp instructionsSIMD utilization
Hillis–Steele (slide 20)yes1783%
work-efficient (Blelloch)yes3823%
work-efficient without __syncwarpNO3823%

A SIMD unit pays per instruction, not per active lane: the work-efficient steps keep only 1, 2, 4, 8 or 16 lanes busy. The last row is a lesson about warps. Without its warp barriers, lanes that skipped a step of the down-sweep run ahead into the next step and read values their neighbours have not written yet. Since NVIDIA’s Volta generation, the threads of a warp are not guaranteed to stay in lockstep, so warp-level code must say where it needs them in step (__syncwarp()). The simulator behaves the same way.

3.6 Building larger scans

Slides 22–24. A block scan of 128 elements with 4 warps (slide 23’s scan_block):

  1. every warp scans its 32 elements (scan_warp);
  2. lane 31 of each warp writes its warp’s total into ptr[warp_id]; __syncthreads();
  3. warp 0 scans the 4 totals (a scan of the bases); __syncthreads();
  4. every warp except warp 0 adds its base, ptr[warp_id − 1].

Demo 01, Part E runs it on the simulator: correct, 119 warp instructions, 81% SIMD utilization. For a million elements (slide 24): each block scans 1,024 elements and writes its total (kernel launch 1); one block scans the block totals (launch 2); every block adds its base (launch 3). More than a million elements needs another level.

05_metal_scan builds exactly this on the Apple GPU for 16M elements: 16M → 16,384 block totals → 16, three levels of group scans plus two passes that add bases:

timeGB/s (8 bytes per element)
full scan, SIMD-group scan = hardware instruction1.11 ms121
full scan, SIMD-group scan = slide 20’s loop1.18 ms113
level-0 group scans alone0.57 ms236
a plain copy of the array0.57 ms238
serial scan on one CPU core6.8 ms20

The level-0 kernel already runs at copy speed: the scan arithmetic is nearly free, and even Apple’s single-instruction SIMD-group prefix sum (simd_prefix_exclusive_sum) saves only 6% over slide 20’s loop. What costs is the second pass that adds bases (read and write the whole output again): the full scan takes 2× a copy. Production GPU scans avoid it with “reduce-then-scan” or with a single pass in which each block looks back at its predecessors’ published totals (“decoupled look-back”, Merrill and Garland, 2016).

3.7 Summary of scan

Slide 25:

  • Parallelism: the scan algorithm features O(N) parallel work, but efficient implementations only leverage as much parallelism as required to make good use of the machine. The goal is to reduce work and communication/synchronization.
  • Locality: a multi-level implementation matches the memory hierarchy (per-block scans in on-chip memory).
  • Heterogeneity in algorithm: a different strategy at each level of the machine. On a GPU: Hillis–Steele within a warp, a different scan across warps and blocks. On a low-core-count CPU: mostly the sequential scan, in chunks.

4. Segmented scan and sparse matrices

4.1 Sequences of sequences

Slide 27: a common problem is operating on a sequence of sequences: for each vertex, its edges; for each particle, its neighbours within distance D; for each document, its words. There are two levels of parallelism, and the inner sequences are irregular: their lengths vary wildly from item to item.

Segmented scan (slide 28) performs independent scans on contiguous partitions of one long sequence. With A = [[1,2],[6],[1,2,3,4]] and ⊕ = +, the exclusive segmented scan is [[0,1],[0],[0,1,3,6]]. A simple representation is start flags: data 1 2 3 4 5 6 7 8 with flags 1 0 0 1 0 0 0 0 means [[1,2,3],[4,5,6,7,8]].

Slides 29–30 give a work-efficient segmented scan: the up-sweep/down-sweep of §3.3, plus flags that stop sums from crossing segment starts (the down-sweep must keep a copy of the original flags). On a multi-core CPU, dp::segmented_inclusive_scan uses the chunked approach instead. A chunk’s summary is a pair: the sum since the chunk’s last segment start, and whether the chunk contains a start. The middle phase carries a sum into a chunk only until its first segment start. Demo 02: 64M elements in ~32K segments, 2.9× on 8 threads, identical to the serial loop.

Slide 31: segmented scan expresses computation on irregular data structures (lists of lists) in a regular, data-parallel way.

4.2 Sparse matrix-vector multiplication

Slide 35: y = A x with a matrix whose values are mostly zero, stored in compressed sparse row (CSR, 压缩稀疏行) format:

values     = [ [3,1], [2], [4], [2,6,8] ]      (nonzeros, row by row)
cols       = [ [0,2], [1], [2], [1,2,3] ]      (their column indices)
row_starts = [ 0, 2, 3, 4 ]                    (where each row begins in values)

The easy parallelization is one dot product per row in parallel. But rows have different amounts of work, which complicates load balance and wide SIMD execution. Slide 36 does it with sequence operations over the nonzeros:

  1. gather from x by cols: gathered[i] = x[cols[i]];
  2. map (multiply): products[i] = values[i] × gathered[i];
  3. build flags from row_starts: flags = [1,0,1,1,1,0,0];
  4. inclusive segmented scan of (products, flags) with +;
  5. take the last element of each segment: y = [3x0+x2, 2x1, 4x2, 2x1+6x2+8x3].

03_sparse_matvec runs this on a matrix with 1M rows and 17M nonzeros whose row lengths follow a power law. The longest row has 3.2M nonzeros, and the first eighth of the rows hold 95% of them, like the “hub” vertices of a social network. All methods produce y identical to the serial loop:

methodtimespeedup
serial, one row after another15.0 ms1.00×
rows, static blocks14.6 ms1.03×
rows, dynamic, 256 rows per grab11.1 ms1.35×
rows, dynamic, 1 row per grab71.7 ms0.21×
nonzeros: gather + map + segmented scan (slide 36)12.1 ms1.24×
nonzeros: the same fused into one pass3.8 ms3.99×
  • Rows are the wrong unit of work. Static blocks put 95% of the work in one thread. Dynamic grabs of 256 rows put most of it in the first grab. Grabbing one row at a time pays a million grabs (Lecture 5’s granularity trade-off) and still cannot split the longest row, a 2.1-ms long pole.
  • Slide 36’s version balances perfectly, since every thread gets an equal share of nonzeros, but it moves a lot of data: 4 passes and 3 temporary arrays of 130 MiB for 2 FLOPs per nonzero. On this bandwidth-bound machine it barely beats serial.
  • Fusing the passes keeps the balance and drops the traffic. Split the nonzeros evenly; each thread computes its whole rows directly; the few rows cut at a boundary get partial sums from neighbouring threads, which are added afterwards in order. These are the segmented scan’s carries. Production libraries call this “merge-based” SpMV.

The lesson generalizes: the data-parallel formulation tells you how to balance an irregular computation. A good implementation then fuses the primitives so that the balance does not cost extra passes.


5. Gather, scatter and sort

5.1 Gather and scatter

Slides 32–33:

  • gather(index, input, output): output[i] = input[index[i]]: “gather data from input according to the indices”;
  • scatter(index, input, output): output[index[i]] = input[i].

Slide 34: CPUs have a SIMD gather instruction (AVX2, 2013; Lecture 3 used NEON’s lane loads). AVX2 has no scatter; AVX-512 does, and GPUs support both in hardware. Both remain expensive compared with loading or storing a contiguous vector. Demo 02 on 64M elements with a random permutation: gather 228 ms serially, 4.7× on 8 threads; scatter 294 ms, 4.3×. They are limited by memory latency (a random line per element), so more cores, with more misses in flight, help more than they do for streaming kernels.

5.2 Turning a scatter into a sort

Slide 37: if index is a permutation (unique indices covering every position), scatter(index, input, output) is the same as “sort input by index”. Slide 38 handles non-unique indices with an operation, e.g. output[index[i]] = atomicAdd(output[index[i]], input[i]), which needs synchronization for atomicity. A data-parallel replacement without atomics:

  1. sort input by index (now equal indices are adjacent);
  2. compute starts of each run of equal indices (a map comparing neighbours);
  3. segmented scan with ⊕ over each run, and take each run’s last element.

This is how you combine values per key without locks: a reduce-by-key.

Sorting is itself built from data-parallel steps. dp::sort_by_key is a parallel radix sort (基数排序). For each 8-bit digit, every thread counts the digits in its chunk; an exclusive scan of the counts in (digit, thread) order gives every thread the position where its elements with each digit go; every thread scatters its chunk there. There are no locks and no atomics: the scan computes every element’s destination. GPU sort libraries work the same way. Demo 02 sorts 16M (key, value) pairs in 32 ms on 8 threads, 24× faster than std::stable_sort on one core. 5.4× of that comes from the algorithm (a few counting passes instead of N log N comparisons) and 4.5× from parallelism.

5.3 More sequence operations

Slide 39: group by key (Seq(key, T) → Seq(key, Seq T)), filter (keep the elements matching a predicate; implemented as a scan of 0/1 flags followed by a scatter), and sort. Together with map, reduce, scan and join, these are the vocabulary of data-parallel systems: Thrust, Pandas, JAX, Spark (slide 51).


6. Building data structures in parallel

6.1 A grid of particles

Slides 40–41: place 1M point particles into the cells of a uniform 2D grid, i.e. build a 2D array of lists. N-body simulations do this so that “find all particles within radius R of p” only inspects the grid cells around p. On a V100 the task must keep up to 163,840 threads busy. Slides 42–46 give five solutions; 04_particle_grid implements all of them for 16 cells (the slides) and 4,096 cells, with 8 threads, and checks every cell’s contents against a serial build:

solution16 cells4,096 cells
serial reference2.4 ms4.6 ms
1. parallel over particles, one lock for the grid (slide 42)0.08×0.04×
2. a lock per cell (slide 43)0.05×0.24×
3. parallel over cells, each cell scans all particles (slide 44)0.35×not run: 4,096× the work
4. private grids per thread, then merge (slide 45)3.3×1.3×
5. map + sort + find starts (slide 46)2.5×3.5×
  1. One lock: “massive contention”, as slide 42 says: thousands of threads contending for one shared data structure.

  2. A lock per cell: slide 43 expects ~16× less contention with 16 cells. Measured, it is no better than one lock. The 16 locks share 8 cache lines and the 16 list headers share 3, so the cores still fight over lines (Lecture 6, demo 05). With 4,096 cells it is 5.7× faster than one lock and still 4× slower than serial: every append pays a lock and a cache miss.

  3. Parallel over cells: no synchronization, but insufficient parallelism (16 tasks) and work-inefficient (16× the particle-in-cell tests).

  4. Partial results + merge: build P private grids, then combine. Synchronization disappears, at the cost of extra memory (P grids) and extra work (the merge). It is best for 16 cells, worse for 4,096: P × 4,096 little lists to merge.

  5. Data-parallel (slide 46):

    • step 1 (map): compute each particle’s cell;
    • step 2 (sort): sort particle ids by cell;
    • step 3 (map over the sorted array): element i starts a cell if its cell differs from element i − 1’s, so it writes cell_starts[this_cell] = i and cell_ends[prev_cell] = i.

    The result is one array of particle ids grouped by cell, plus start/end per cell: a compact layout that the neighbour search reading it next also prefers. It maintains a large amount of parallelism and removes fine-grained synchronization, “at the cost of a sort and extra passes over the data”. It also costs the same for 16 and 4,096 cells, once the sort is told that the keys have only 4 or 12 bits. In the first version it sorted all 32 bits and was slower than serial (README).

6.2 A histogram from map and sort

Slides 47–49: compute a histogram given only map and sort on sequences:

  1. map each value to its bin id;
  2. sort the bin ids;
  3. find_starts (map over the sorted ids): bin_starts[b] = first position of bin b, or −1 if the bin is empty;
  4. bin_sizes (map over bins): size = start of the next non-empty bin − own start.

The “tricky edge case” of slide 49: if the next bin is empty, its start is −1, so a thread must search forward to the next non-empty bin, or use N at the end. Demo 04 builds a histogram of 1M values in 1,024 bins with a third of the bins deliberately empty: correct. Compare Lecture 6’s demo 05, which built histograms with shared atomics (contended) and private copies (fast). The sort-based version needs neither atomics nor per-thread copies of the bins.


7. Summary of the lecture

Slide 50: data-parallel thinking means implementing algorithms in terms of simple, often widely parallelizable, efficiently implemented operations on large data collections.

  • Turn irregular parallelism into regular parallelism: segmented scan and nonzero-based SpMV.
  • Turn fine-grained synchronization into coarse synchronization: sort + find starts instead of locks.
  • But most solutions require multiple passes over the data, which is bandwidth-hungry. Our SpMV and GPU scan measured exactly this, and fusion is the cure (Lectures 6 and 9).

Slide 51: data-parallel primitives are the basis of many parallel and distributed systems today: CUDA’s Thrust (and CUB), Pandas dataframes, JAX, Apache Spark / Hadoop.


Summary

  • Data-parallel programs are written as operations on sequences: map, reduce, scan, segmented scan, gather, scatter, sort. Because elements are accessed only through these operations, the implementation is free to parallelize them.
  • map parallelizes trivially; reduce needs an associative operator (or a combiner) and an identity. Floating-point + is only approximately associative.
  • Scan looks sequential but is not. Hillis–Steele has O(log N) span and O(N log N) work; Blelloch’s up-/down-sweep has O(N) work and 2 log N span; on a few cores, chunked reduce-then-scan does ~2N operations in two contiguous passes. Measured on 8 cores: chunked 3.4×, Blelloch 0.5×, Hillis–Steele 0.1× of the serial loop.
  • Inside a warp, Hillis–Steele beats the work-efficient scan (17 vs. 38 instructions): a SIMD unit pays per instruction. Warp-level code needs __syncwarp() because modern GPUs do not keep warps in lockstep.
  • Large GPU scans are hierarchical: warp scans → block scans → scans of block totals → add bases, a different algorithm at each level. On the Apple GPU a 16M scan takes 2× the time of a copy; the arithmetic is nearly free.
  • Segmented scan handles sequences of sequences regularly. Slide 36’s SpMV over nonzeros balances power-law rows that defeat row-based scheduling; fusing its passes gives 4× where its unfused form gives 1.2×.
  • Gather/scatter move data by index; sort (a radix sort built from counts and a scan) turns scatters with conflicts and data-structure construction into lock-free data-parallel steps.
  • Data-parallel solutions often cost extra passes. Measure, and fuse.

Common pitfalls

  • Using a non-associative operator (or floats, expecting bit-identical results) with a parallel reduce or scan.
  • Choosing an algorithm by its work bound alone. Blelloch’s O(N) scan lost to one core; Hillis–Steele’s O(N log N) scan is the right choice in a warp. Count instructions, passes, cache lines and barriers on the actual machine.
  • Exposing more parallelism than the machine needs at the cost of extra passes (slide 25).
  • Warp-synchronous code without __syncwarp(), or a barrier inside a divergent branch.
  • Forgetting empty segments or empty bins. Start flags cannot represent empty segments, and the histogram’s bin_sizes must skip empty bins.
  • Sorting all 32 bits when the keys need 4. Tell the sort the key range.
  • Assuming per-object locks remove contention when the objects share cache lines.
  • Stopping at the data-parallel formulation. It shows how to balance the work; fusing the primitives is what removes the extra traffic.

Exercises

  1. Scan by hand. Compute the inclusive and exclusive +-scans of [2, 0, 5, 1, 3, 4], and the inclusive segmented +-scan of the same data with flags [1, 0, 1, 0, 0, 1].

    AnswerInclusive: [2, 2, 7, 8, 11, 15]. Exclusive: [0, 2, 2, 7, 8, 11]. Segments [2, 0], [5, 1, 3], [4]: segmented inclusive [2, 2, 5, 6, 9, 4].
  2. Work and span. For N = 2^20 elements, compute the additions and steps of Hillis–Steele and Blelloch, and the time of each on a machine with P = 1,024 processors, if a step with k additions takes ⌈k/P⌉ time units.

    AnswerHillis–Steele: 20 steps, step d does N − 2^d additions ≈ N, so ≈ 20 × 1,024 = 20,480 units (work ≈ 20.0M). Blelloch: up-sweep step d does N/2^(d+1) additions, needing ⌈N/(2^(d+1) P)⌉ units: 512 + 256 + … + 1 + 1 + … (once fewer than P additions, 1 unit) ≈ 1,023 + 10 units; the down-sweep the same, so ≈ 2,066 units. Blelloch wins by ~10× when P ≪ N. With P = N, Hillis–Steele takes 20 units and Blelloch 40.
  3. Why exclusive? Show how an exclusive scan of 0/1 flags implements filter: given A = [5, 8, 1, 9, 4] and the predicate “even”, produce [8, 4] with only map, scan and scatter.

    Answermap: flags = [0, 1, 0, 0, 1]; exclusive scan: pos = [0, 0, 1, 1, 1]; scatter: for every i with flags[i] = 1, out[pos[i]] = A[i], so out[0] = 8 and out[1] = 4. The output length is the last pos plus the last flag = 2. This is "stream compaction", the core of PA3's find-repeats.
  4. Segmented scan carries. Four chunks of a +-segmented scan report (tail sum, contains a start): (5, yes), (7, no), (3, yes), (2, no). What carry-in does each chunk get?

    AnswerChunk 0: 0. Chunk 1: chunk 0 contains a start, so its tail: 5. Chunk 2: chunk 1 has no start, so 5 + 7 = 12. Chunk 3: chunk 2 contains a start, so its tail: 3.
  5. SpMV balance. A matrix has 1,000 rows of 10 nonzeros and one row of 100,000 nonzeros. With 8 threads, what is the best possible speedup for row-based dynamic scheduling, and for nonzero-based splitting?

    AnswerTotal 110,000 nonzeros. Row-based: the long row takes 100,000 units on one thread; everything else can run beside it, so the time is ≥ 100,000 and the speedup ≤ 1.1. Nonzero-based: 110,000 / 8 = 13,750 per thread plus a little fix-up, close to 8×.
  6. Scatter with conflicts. index = [1, 1, 0, 2, 0, 0] and input = [a, b, c, d, e, f]. Apply slide 38’s sort + starts + segmented scan with ⊕ = + to compute output[k] = sum of inputs whose index is k.

    AnswerSort by index (stably): indices [0, 0, 0, 1, 1, 2] with inputs [c, e, f, a, b, d]. Starts: [1, 0, 0, 1, 0, 1]. Segmented inclusive scan: [c, c+e, c+e+f, a, a+b, d]. The last of each run gives output = [c+e+f, a+b, d].

PA3 starts with exclusive scan in CUDA, then find repeats: output the indices i where A[i] = A[i+1], built from a map (flag the repeats), an exclusive scan (output positions) and a scatter, exactly the stream compaction of exercise 3. Its circle renderer then needs data-parallel thinking to avoid fine-grained locking while keeping circles in order. These notes implement scans in dp.h, on the SIMT simulator and in Metal, but not the assignment’s CUDA code. Write your own.

Further reading

  • The Fall 2025 slides for this lecture and the 2023 lecture video.
  • G. E. Blelloch, “Prefix Sums and Their Applications”, CMU-CS-90-190, 1990. The up-sweep/down-sweep scan, segmented scan and their uses.
  • W. D. Hillis and G. L. Steele, “Data Parallel Algorithms”, CACM 29(12), 1986.
  • M. Harris, S. Sengupta and J. D. Owens, “Parallel Prefix Sum (Scan) with CUDA”, GPU Gems 3, chapter 39 (2007). Includes bank-conflict-free scans in shared memory.
  • D. Merrill and M. Garland, “Single-pass Parallel Prefix Scan with Decoupled Look-back”, NVIDIA technical report, 2016; and “Merge-Based Parallel Sparse Matrix-Vector Multiplication”, SC 2016.
  • The Thrust and CUB documentation (NVIDIA), the C++17 parallel algorithms (std::transform_reduce, std::inclusive_scan with execution policies), JAX’s jax.lax.associative_scan.

Preview of Lecture 9 — Efficiently evaluating DNNs

Lecture 9 applies the last three lectures to the computation that dominates today’s machines: deep neural networks. Convolutions and transformers reduce to dense matrix multiplication, whose arithmetic intensity can be raised enormously by blocking, and their elementwise layers to maps whose extra passes over memory are removed by fusion. The demos build a matrix multiply step by step toward the roofline of Lecture 6, and compute attention without ever storing the attention matrix (FlashAttention).


术语表 (Glossary, English → 中文)

English中文
data-parallel model数据并行模型
sequence序列
higher-order function高阶函数
map映射
fold / reduce折叠 / 归约
combiner合并函数
associativity / identity element结合律 / 单位元
scan / prefix sum扫描 / 前缀和
inclusive / exclusive scan包含式 / 排除式扫描
work / span工作量 / 跨度
work-efficient工作高效
up-sweep / down-sweep上扫 / 下扫
reduce-then-scan先归约后扫描
hierarchical scan分层扫描
warp-synchronous programming线程束同步编程
segmented scan分段扫描
start flags段起始标志
sparse matrix / CSR (compressed sparse row)稀疏矩阵 / 压缩稀疏行格式
sparse matrix-vector multiplication (SpMV)稀疏矩阵向量乘
power-law distribution幂律分布
gather / scatter收集 / 分散
permutation置换
reduce-by-key按键归约
radix sort基数排序
stable sort稳定排序
stream compaction / filter流压缩 / 过滤
group by key按键分组
uniform grid / N-body problem均匀网格 / N 体问题
histogram直方图
fusion (of passes)(多遍计算的)融合
← 返回课程目录