Module contents
Lesson 26 of 33Advanced 115 min

Parallel algorithms: work, span and scan

Use the machine-independent work–span model for parallel algorithms: work is sequential cost and span the task DAG's critical path. Prove Brent's theorem, design parallel reduction and Blelloch scan, apply scan to associative operators such as affine recurrences behind state-space models, and study sorting networks, pointer jumping and work-stealing scheduling.

After this lesson you can

  • Calculate work, span and parallelism of algorithms expressed as DAGs.
  • Apply Brent's theorem to predict time with p processors.
  • Implement reduction and Blelloch scan and analyze work and span.
  • Reformulate a linear recurrence as a scan over the affine-function monoid.
  • Analyze bitonic sort and pointer jumping and explain work stealing.

Before you start

Motivation: thousands of cores and algorithms that do not speed up

A current desktop CPU has on the order of 24 cores (a Core i9-13900K, for example, combines 8 performance and 16 efficiency cores), and an RTX 4060 has 24 multiprocessors with 128 CUDA cores each: 3072 units running tens of thousands of threads concurrently. But parallel hardware accelerates nothing by itself. Look at this loop:

total = 0
for x in datos:
    total = total + x

Each iteration needs the previous result. No matter how many cores, the nn additions form a chain and execute sequentially. Group differently, ((x0+x1)+(x2+x3))+…((x_0 + x_1) + (x_2 + x_3)) + \dots, and additions at each level are independent, needing only ⌈log⁡2n⌉\lceil\log_2 n\rceil rounds. Same result (in exact arithmetic), same number of additions, and an exponentially shorter dependency chain. What changed is not work, but the shape of computation.

This lesson is about that, and it is not merely academic:

  • Prefix sums appear inherently sequential because yi=yi−1+xiy_i = y_{i-1} + x_i. They are not: they take O(log⁡n)\bigO(\log n) rounds and O(n)\bigO(n) operations, and this primitive, scan, underlies compaction, GPU radix sort and much more.
  • A recurrent network cannot be trained in parallel over time because ht\vb{h}_t depends on ht−1\vb{h}_{t-1} through a nonlinearity. State-space models such as Mamba (Gu and Dao, 2023) use linear recurrences ht=Atht−1+bt\vb{h}_t = \mat{A}_t\vb{h}_{t-1} + \vb{b}_t precisely because those admit a scan: see parallelizable recurrences and associative scan of linear recurrences.
  • Gradient all-reduce across 1024 GPUs is a parallel reduction with communication costs, analyzed with this lesson’s tools (tree collectives and ring collectives).

Reasoning machine-independently requires a cost model separating how much must be computed from how long we must wait.

The computation DAG: work and span

Any algorithm execution on a fixed input can be unfolded as a directed acyclic graph: one vertex per elementary operation and edge u→vu \to v if vv uses uu’s result. A processor can execute vv once all predecessors finish; vertices with no path between them can execute together. Any valid execution traverses the DAG in topological order; the question is how many vertices can be processed each step.

Two lower bounds follow directly from the definition and govern almost everything:

Tp≥T1p⏟ley del trabajoTp≥T∞⏟ley de la profundidad\underbrace{T_p \ge \frac{T_1}{p}}_{\text{ley del trabajo}} \qquad\qquad \underbrace{T_p \ge T_\infty}_{\text{ley de la profundidad}}

The first holds because at most pp vertices execute each step; the second because path vertices must execute in distinct steps in order. Hence speedup never exceeds min⁡(p,  T1/T∞)\min(p,\; T_1/T_\infty): parallelism is the maximum number of processors the algorithm can exploit. Beyond that, adding processors does not help.

For pseudocode with sequential and parallel blocks, both measures compose by two rules:

CompositionWorkSpan
AA then BB (series)T1(A)+T1(B)T_1(A) + T_1(B)T∞(A)+T∞(B)T_\infty(A) + T_\infty(B)
AA and BB at once (parallel)T1(A)+T1(B)T_1(A) + T_1(B)max⁡(T∞(A),T∞(B))\max(T_\infty(A), T_\infty(B))

In a divide-and-conquer algorithm solving aa subproblems in parallel, this gives two recurrences instead of one: W(n)=a W(n/b)+f(n)W(n) = a\,W(n/b) + f(n) for work and S(n)=S(n/b)+g(n)S(n) = S(n/b) + g(n) for span, with gg the span of dividing and combining. Both use the master theorem.

Amdahl from the DAG

Amdahl’s law is a special case. If fraction ff of work forms a chain overlapping nothing (the “sequential” code), the DAG is the serial composition of that chain of length fT1fT_1 and a perfectly parallel part of work (1−f)T1(1-f)T_1. Then

Tp≥f T1+(1−f) T1p⟹T1Tp≤1f+(1−f)/p<1f.T_p \ge f\,T_1 + \frac{(1-f)\,T_1}{p} \quad\Longrightarrow\quad \frac{T_1}{T_p} \le \frac{1}{f + (1-f)/p} < \frac{1}{f}.

With 5% sequential work, speedup never exceeds 20 regardless of cores. The work–span model is finer than Amdahl: it does not classify code as sequential or parallel, but measures the actual graph’s critical path, potentially much shorter than the apparent “sequential” part (as with prefix sums) or much longer.

Brent’s theorem and greedy scheduling

Work and span laws are lower bounds. Can they be attained? Not exactly (optimally scheduling a DAG on pp processors is generally NP-hard), but nearly, with a trivial algorithm.

Proof

Group vertices by levels: vv’s level is the vertex count of the longest path ending at vv. There are exactly T∞T_\infty levels, same-level vertices are independent (if edge u→vu \to v existed, vv’s level would exceed uu’s), and all predecessors lie on earlier levels. Execute levels in order; level ii with mim_i vertices takes ⌈mi/p⌉\lceil m_i/p\rceil steps. Since ⌈m/p⌉≤(m−1)/p+1\lceil m/p\rceil \le (m - 1)/p + 1 for any integer m≥1m \ge 1,

Tp≤∑i=1T∞⌈mip⌉≤∑i=1T∞(mi−1p+1)=T1−T∞p+T∞.T_p \le \sum_{i=1}^{T_\infty}\Big\lceil\frac{m_i}{p}\Big\rceil \le \sum_{i=1}^{T_\infty}\Big(\frac{m_i - 1}{p} + 1\Big) = \frac{T_1 - T_\infty}{p} + T_\infty.∎

This is Brent’s theorem. Brent proved it for arithmetic-expression evaluation, but the argument is general. Level scheduling has a practical drawback: the DAG must be known in advance. Real systems use another nearly equivalent result without this requirement. A greedy scheduler executes min⁡(p,r)\min(p, r) of the rr ready vertices (whose predecessors have finished) each step, leaving no processor idle while work is available.

Factor 2 follows from T1/p+T∞≤2max⁡(T1/p,T∞)T_1/p + T_\infty \le 2\max(T_1/p, T_\infty), and the maximum lower-bounds any schedule. The guided exercise proves it by separating complete steps (at least pp ready), of which at most T1/pT_1/p exist, from incomplete ones, each shortening the longest remaining path by one. “Any” matters: the theorem holds regardless of how ready vertices are chosen. Tighter counting recovers Brent: with I≤T∞I \le T_\infty incomplete steps, each executes at least one vertex, so complete steps are at most (T1−I)/p(T_1 - I)/p and Tp≤T1/p+I(1−1/p)≤(T1−T∞)/p+T∞T_p \le T_1/p + I(1 - 1/p) \le (T_1 - T_\infty)/p + T_\infty. This is Graham’s 1966 list-scheduling bound, attained with equality by a DAG in the figure.

Condition p≪T1/T∞p \ll T_1/T_\infty is called parallel slackness. When parallelism is, say, ten times pp, term T∞T_\infty is negligible and speedup nearly perfect. Design should therefore minimize span without increasing work, not merely “use pp processors”: an algorithm with parallelism 10610^6 scales equally well on 8 cores or 10 000.

InteractiveWork, span and processors
step 9 of 9
processors × steps (9 steps, 5 idle slots)1234step 1step 9
  • level 1
  • level 2
  • level 3
  • level 4
  • level 5
  • measured greedy T₁/Tₚ
  • ceiling min(p, T₁/T∞)
  • greedy guarantee T₁/(T₁/p + T∞)
4
Ready queue
Work T1T_131
Span T∞T_\infty5
Parallelism T1/T∞T_1/T_\infty6.20
Greedy time TpT_p9
Bounds: max⁡(T1/p,T∞)\max(T_1/p, T_\infty) and T1/p+T∞T_1/p + T_\infty7.8 ≤ 9 ≤ 12.8
Utilization T1/(p Tp)T_1/(p\,T_p)86 %
pp approaches parallelism (≈6.2\approx 6.2): incomplete steps appear as gaps in the Gantt chart, and speedup T1/Tp=3.44T_1/T_p = 3.44 stays below pp.
Above, a task DAG; middle, a greedy scheduler’s Gantt chart with pp processors (rows are processors, columns steps; gaps are idle processors); below, speedup T1/TpT_1/T_p for all pp between greedy guarantee T1/(T1/p+T∞)T_1/(T_1/p + T_\infty) and ceiling min⁡(p,T1/T∞)\min(p, T_1/T_\infty). Start with tree reduction (T1=31T_1 = 31, T∞=5T_\infty = 5) and increase pp: the curve flattens at parallelism 6.26.2. Sequential sum never speeds up. Compare scans: Hillis–Steele performs 49 operations in 4 rounds and Blelloch 30 in 7, so Blelloch wins with few processors (T2=15T_2 = 15 versus 25) and Hillis–Steele with many (T16=4T_{16} = 4 versus 7). In the chain with loose tasks, arrival-order queue takes T4=28T_4 = 28, exactly Brent’s bound (T1−T∞)/p+T∞=48/4+16(T_1 - T_\infty)/p + T_\infty = 48/4 + 16 (greedy guarantee T1/p+T∞T_1/p + T_\infty gives 32); critical-path priority takes 16, the optimum.

Three observations. Mergesort with sequential merge has T1=80T_1 = 80 and T∞=31T_\infty = 31: the last merge, a 16-step chain, occupies half the critical path, and parallelism 2.62.6 supports only two or three processors. The chain with loose tasks shows the bound is attained (not analytical pessimism): arrival order gives Tp=48/p+16T_p = 48/p + 16 for every pp dividing 48, exactly (T1−T∞)/p+T∞(T_1 - T_\infty)/p + T_\infty. Good priority avoids this case, though not generally. And Blelloch scan has T∞=7T_\infty = 7 not 2log⁡216=82\log_2 16 = 8: the final up-sweep addition computes the array total, unneeded by down-sweep, so it is not on the prefix critical path.

The figure’s experiment at scale: random DAGs, a greedy scheduler selecting randomly among ready vertices, and both bound checks.

[ ]Brent’s bound on random DAGsBrowser
import random

def dag_aleatorio(n, densidad, rng):
    """DAG en orden topológico: arista u -> v (u < v) con probabilidad densidad / (v - u)."""
    return [[u for u in range(max(0, v - 20), v) if rng.random() < densidad / (v - u)] for v in range(n)]

def trabajo_profundidad(preds):
    nivel = []
    for ps in preds:
        nivel.append(1 + max((nivel[u] for u in ps), default=0))
    return len(preds), max(nivel)

def voraz(preds, p, rng):
    n = len(preds)
    succ = [[] for _ in range(n)]
    pendientes = [len(ps) for ps in preds]
    for v, ps in enumerate(preds):
        for u in ps:
            succ[u].append(v)
    listos = [v for v in range(n) if pendientes[v] == 0]
    t = hechos = 0
    while hechos < n:
        rng.shuffle(listos)                       # cualquier elección vale: el teorema no depende de ella
        ahora, listos = listos[:p], listos[p:]
        t += 1
        hechos += len(ahora)
        for v in ahora:
            for w in succ[v]:
                pendientes[w] -= 1
                if pendientes[w] == 0:
                    listos.append(w)
    return t

rng = random.Random(1)
peor_brent = peor_inferior = 0.0
for _ in range(120):
    preds = dag_aleatorio(rng.randint(50, 300), rng.uniform(0.2, 1.5), rng)
    T1, Tinf = trabajo_profundidad(preds)
    for p in (2, 4, 8, 16, 64):
        Tp = voraz(preds, p, rng)
        assert max(T1 / p, Tinf) <= Tp <= T1 / p + Tinf
        peor_brent = max(peor_brent, Tp / (T1 / p + Tinf))
        peor_inferior = max(peor_inferior, Tp / max(T1 / p, Tinf))
print("120 DAGs x 5 valores de p: las dos cotas se cumplen siempre")
print(f"máximo de T_p / (T1/p + Tinf):     {peor_brent:.3f}   (nunca pasa de 1)")
print(f"máximo de T_p / max(T1/p, Tinf):   {peor_inferior:.3f}   (nunca pasa de 2)")

Reduction and scan

Let (M,⊕,e)(M, \oplus, e) be a monoid: associative ⊕\oplus with identity ee. Given sequence x0,…,xn−1x_0, \dots, x_{n-1} (zero-indexed as in code and figures), its parallel prefix scan is the sequence of all prefixes. Two variants:

inclusivo: yi=x0⊕x1⊕⋯⊕xi,exclusivo: yi=x0⊕⋯⊕xi−1,y0=e.\text{inclusivo: } y_i = x_0 \oplus x_1 \oplus \cdots \oplus x_i, \qquad \text{exclusivo: } y_i = x_0 \oplus \cdots \oplus x_{i-1}, \quad y_0 = e.

Convert with one operation per element: inclusive is exclusive ⊕ xi\oplus\, x_i, and exclusive is inclusive shifted one position with ee in front. The range-query lesson’s prefix sums are case ⊕=+\oplus = +, and the obvious loop costs T1=T∞=n−1T_1 = T_\infty = n - 1.

Hillis–Steele: minimum span, extra work

The first idea (Hillis and Steele, 1986, for the Connection Machine; in circuits, Kogge–Stone’s 1973 adder) doubles distance each round:

para d=0,1,…,⌈log⁡2n⌉−1:xi←xi−2d⊕xipara todo i≥2d a la vez.\text{para } d = 0, 1, \dots, \lceil\log_2 n\rceil - 1: \qquad x_i \leftarrow x_{i - 2^d} \oplus x_i \quad \text{para todo } i \ge 2^d \text{ a la vez}.

Invariant: after round dd, xix_i contains the aggregate of min⁡(i+1,2d+1)\min(i+1, 2^{d+1}) elements ending at ii. By induction: if before the round each cell summarizes a window of 2d2^d elements, combining cell i−2di - 2^d with ii joins two contiguous windows. After ⌈log⁡2n⌉\lceil\log_2 n\rceil rounds every window reaches the start: inclusive scan. Span is optimal ⌈log⁡2n⌉\lceil\log_2 n\rceil, but work is

T1=∑d=0log⁡2n−1(n−2d)=nlog⁡2n−(n−1),T_1 = \sum_{d=0}^{\log_2 n - 1}(n - 2^d) = n\log_2 n - (n - 1),

a factor log⁡n\log n more than the loop. It is not work-efficient: with few processors it is slower than the sequential algorithm.

Blelloch: linear work in two sweeps

Blelloch’s algorithm (1990), based on Ladner and Fischer circuits (1980), is a tree reduction followed by a return traversal. Let nn be a power of 2 (otherwise pad with ee) and consider the full binary tree over the array, whose node for each aligned size-2s2s block is stored in that block’s last cell.

  1. Up-sweep. For s=1,2,4,…,n/2s = 1, 2, 4, \dots, n/2 and each block [k,k+2s)[k, k + 2s), with l=k+s−1l = k + s - 1 and r=k+2s−1r = k + 2s - 1: xr←xl⊕xrx_r \leftarrow x_l \oplus x_r. This is tree reduction; afterwards each node stores its block aggregate.
  2. Root: xn−1←ex_{n-1} \leftarrow e.
  3. Down-sweep. For s=n/2,…,2,1s = n/2, \dots, 2, 1 and each block: t←xlt \leftarrow x_l; xl←xrx_l \leftarrow x_r; xr←xr⊕tx_r \leftarrow x_r \oplus t.
InteractiveBlelloch scan
row 9 of 9
x7325864371724851↑ 17102781447787941256↑ 271021781442178717412518↑ 471021781443878717412535↑ 871021781443878717412573root7102178144387871741250↓ 87102178144078717412538↓ 47102081441778738412555↓ 270210817431738746455567↓ 1071012172531353845465355596772loop071012172531353845465355596772
  • upsweep: xr←xl⊕xrx_r \leftarrow x_l \oplus x_r
  • downsweep: xr←P⊕Lx_r \leftarrow P \oplus L
  • downsweep: xl←Px_l \leftarrow P
Operator ⊕
Show
Size n
Applications of ⊕\oplus30 of 30
Parallel rounds8 of 8
Matches with loop16 / 16
Associative operatoryes
Commutative operatoryes
All 16 cells match the sequential exclusive scan, with 2(n−1)=302(n-1) = 30 operations in 2log⁡2n=82\log_2 n = 8 rounds.
Each row is the array after a parallel round: with n=16n = 16 (8 on narrow screens), four up-sweep rounds (↑), identity at root and four down-sweep rounds (↓); the last row is the exclusive scan from the sequential loop, with each matching or mismatching cell finally green or red. Play from the start with addition. Switch to ‘Ranges’: each cell shows which array segment it summarizes, and in the last round cell ii summarizes exactly 0,…,i−10, \dots, i-1 with any operator. Try maximum, then affine functions (x↦±x+bx \mapsto \pm x + b, combined by composition), which do not commute: scan remains correct. Reverse operand order in down-sweep: addition is unchanged, affine functions fail. Finally subtraction: it is not associative and the tree differs from the loop.
Proof

Write agg[a,b)\mathrm{agg}[a, b) for xa⊕⋯⊕xb−1x_a \oplus \cdots \oplus x_{b-1} using original values, and agg[a,a)=e\mathrm{agg}[a, a) = e. After the size-ss up-sweep round, the last cell of each aligned size-2s2s block holds agg\mathrm{agg} of the block: by induction it combines aggregates of its two halves in order, and associativity removes dependence on grouping within each half. Cells that are not ends of larger blocks are not touched again.

For down-sweep, the invariant is: at the start of the size-ss round, for each block [k,k+2s)[k, k+2s), cell r=k+2s−1r = k + 2s - 1 holds agg[0,k)\mathrm{agg}[0, k) (the prefix before the block) and l=k+s−1l = k + s - 1 retains agg[k,k+s)\mathrm{agg}[k, k+s) from up-sweep. Initially (s=n/2s = n/2, one block with k=0k = 0) this holds because root is e=agg[0,0)e = \mathrm{agg}[0, 0). The round leaves xl=agg[0,k)x_l = \mathrm{agg}[0, k), the prefix before left block [k,k+s)[k, k+s), and xr=agg[0,k)⊕agg[k,k+s)=agg[0,k+s)x_r = \mathrm{agg}[0, k) \oplus \mathrm{agg}[k, k+s) = \mathrm{agg}[0, k+s), the prefix before the right block. These are exactly what the invariant requires for size-ss blocks next round. After round s=1s = 1, each cell ii ends its size-1 block and holds agg[0,i)\mathrm{agg}[0, i).

Cost: each size-ss round has n/(2s)n/(2s) blocks and performs one operation per block, so each sweep performs n/2+n/4+⋯+1=n−1n/2 + n/4 + \cdots + 1 = n - 1 operations in log⁡2n\log_2 n rounds.

∎

Operand order in xr←xr⊕tx_r \leftarrow x_r \oplus t matters: xrx_r is prefix PP and tt is left-subtree aggregate LL, which comes after. For a commutative operator such as sum or maximum, writing t⊕xrt \oplus x_r changes nothing; for noncommutative operations such as function composition or matrix product it is wrong. The figure demonstrates this. Associativity is always required: the tree groups terms differently from the loop, and only associativity guarantees equal results.

By Brent’s theorem, Tp≤2(n−1)/p+2log⁡2nT_p \le 2(n-1)/p + 2\log_2 n: with p≤n/log⁡2np \le n/\log_2 n processors time is O(n/p)\bigO(n/p), linear speedup. Compare Hillis–Steele for n=220n = 2^{20}:

Work T1T_1Span T∞T_\inftyWork-efficient
Sequential loopn−1≈1.0×106n - 1 \approx 1.0\times 10^6n−1n - 1yes
Hillis–Steelenlog⁡2n−n+1≈2.0×107n\log_2 n - n + 1 \approx 2.0\times 10^72020no
Blelloch2(n−1)≈2.1×1062(n - 1) \approx 2.1\times 10^64040yes

Can we have both n−1n - 1 work and log⁡2n\log_2 n span? No: Snir (1986) proved that in any nn-input prefix circuit, operation count plus span is at least 2n−22n - 2. Choose a point on that frontier; GPUs combine both ideas: sequential scan within each thread, Hillis–Steele within a 32-thread warp (extra operations are free because all 32 lanes execute anyway), and work-efficient interblock scheduling.

Scan as a tool

What makes scan a primitive rather than just another algorithm is how many problems reduce to it with linear work.

Stream compaction (parallel filter). To retain xix_i satisfying a predicate, calculate flags fi∈{0,1}f_i \in \{0, 1\} and their exclusive sum scan sis_i. If fi=1f_i = 1, destination of xix_i is sis_i: destinations are distinct and consecutive, and all elements write simultaneously. Work O(n)\bigO(n), span O(log⁡n)\bigO(\log n).

Stable partition (split). To separate zeros and ones by bit bib_i while preserving relative order, an exclusive scan of 1−bi1 - b_i gives each zero’s position, and each one’s position is n0+i−(ceros antes de i)n_0 + i - (\text{ceros antes de } i), where n0n_0 is total zeros: one scan suffices.

Parallel radix sort. Repeating stable partition for each bit, least to most significant, is LSD radix sort: for bb-bit keys, work O(bn)\bigO(bn) and span O(blog⁡n)\bigO(b\log n). Fast GPU sorts vary this idea with multibit digits and a histogram scan.

Linear recurrences as scan

Consider the first-order recurrence

xt=at xt−1+bt,t=1,…,T,x_t = a_t\,x_{t-1} + b_t, \qquad t = 1, \dots, T,

with x0x_0 given. It seems perfectly sequential. But each step is an affine function ft(x)=atx+btf_t(x) = a_t x + b_t, and xt=(ft∘⋯∘f1)(x0)x_t = (f_t \circ \cdots \circ f_1)(x_0). Represent ftf_t by pair (at,bt)(a_t, b_t) and define

(a1,b1)⊕(a2,b2)=(a2a1,  a2b1+b2),(a_1, b_1) \oplus (a_2, b_2) = (a_2 a_1,\; a_2 b_1 + b_2),

the pair for f2∘f1f_2 \circ f_1: “first f1f_1, then f2f_2.” Function composition is associative, so ⊕\oplus is too, with identity (1,0)(1, 0). This affine monoid is the central example of associative scan operators: any associative operation with an identity, even noncommutative or unlike a sum, can be scanned in parallel. Inclusive scan gives every prefix (At,Bt)=(a1,b1)⊕⋯⊕(at,bt)(A_t, B_t) = (a_1, b_1) \oplus \cdots \oplus (a_t, b_t) and then xt=Atx0+Btx_t = A_t x_0 + B_t in O(log⁡T)\bigO(\log T) rounds.

Vectors work likewise: ht=Atht−1+bt\vb{h}_t = \mat{A}_t\vb{h}_{t-1} + \vb{b}_t scans with (A1,b1)⊕(A2,b2)=(A2A1,A2b1+b2)(\mat{A}_1, \vb{b}_1) \oplus (\mat{A}_2, \vb{b}_2) = (\mat{A}_2\mat{A}_1, \mat{A}_2\vb{b}_1 + \vb{b}_2). Cost lies in products A2A1\mat{A}_2\mat{A}_1: dense d×dd\times d matrices cost O(d3)\bigO(d^3) per operation versus O(d2)\bigO(d^2) per sequential step; diagonal matrices cost O(d)\bigO(d). This is one reason modern state-space models use diagonal transitions: Mamba’s selective SSM is essentially a scan of this monoid with input-dependent diagonal At\mat{A}_t. Martin and Cundy (2018) had already proposed training linear RNNs this way via sequence scan.

Other useful monoids with the same pattern (small state plus associative combination):

  • Mean and variance: mean is not associative as a binary operation (12(12(a+b)+c)≠12(a+12(b+c))\tfrac{1}{2}(\tfrac{1}{2}(a + b) + c) \neq \tfrac{1}{2}(a + \tfrac{1}{2}(b + c))), but (sum, count) is. For variance combine (count, mean, centered sum of squares) triples with Chan, Golub and LeVeque’s 1979 formula.
  • Online softmax: pair (m,s)(m, s), maximum and ∑jezj−m\sum_j e^{z_j - m}, combines with M=max⁡(m1,m2)M = \max(m_1, m_2) and s=s1em1−M+s2em2−Ms = s_1 e^{m_1 - M} + s_2 e^{m_2 - M}. It is associative (representing s ems\,e^{m} without overflow) and underlies FlashAttention online softmax.
  • Binary-addition carries: each position’s (generate, propagate) pair forms a monoid; fast CPU adders (Kogge–Stone, Brent–Kung) are scan circuits over it.

Parallel mergesort and parallel merge

Mergesort seems made for parallelism: halves are independent. Sort them in parallel and merge with the usual loop:

W(n)=2W(n/2)+Θ(n)=Θ(nlog⁡n),S(n)=S(n/2)+Θ(n)=Θ(n).W(n) = 2W(n/2) + \Theta(n) = \Theta(n\log n), \qquad S(n) = S(n/2) + \Theta(n) = \Theta(n).

Parallelism is only Θ(log⁡n)\Theta(\log n): the final sequential merge of length nn dominates the critical path, as in the DAG figure with n=16n = 16. To scale, parallelize the merge.

Parallel merge (CLRS chapter 26). To merge sorted arrays AA and BB with ∣A∣≥∣B∣\abs{A} \ge \abs{B}, take median x=A[q]x = A[q] of AA and binary-search its position jj in BB. Everything in A[0,q)A[0, q) and B[0,j)B[0, j) is at most xx, everything in A(q,⋅)A(q, \cdot) and B[j,⋅)B[j, \cdot) at least it. Thus xx goes to output position q+jq + j, and submerges (A[0,q),B[0,j))(A[0, q), B[0, j)) and (A(q,⋅),B[j,⋅))(A(q, \cdot), B[j, \cdot)) are independent and run in parallel. If n=∣A∣+∣B∣n = \abs{A} + \abs{B}, each submerge has at most ∣A∣/2+∣B∣≤n−n/4=3n/4\abs{A}/2 + \abs{B} \le n - n/4 = 3n/4 elements because ∣A∣≥n/2\abs{A} \ge n/2. With binary search of span O(log⁡n)\bigO(\log n),

Smezcla(n)≤Smezcla(3n/4)+O(log⁡n)=O(log⁡2n),S_{\text{mezcla}}(n) \le S_{\text{mezcla}}(3n/4) + \bigO(\log n) = \bigO(\log^2 n),

and work remains Θ(n)\Theta(n) (recurrence W(n)=W(αn)+W((1−α)n)+O(log⁡n)W(n) = W(\alpha n) + W((1 - \alpha)n) + \bigO(\log n) with α∈[1/4,3/4]\alpha \in [1/4, 3/4] solves by substitution). Mergesort with parallel merge has W(n)=Θ(nlog⁡n)W(n) = \Theta(n\log n), the same work, and S(n)=S(n/2)+O(log⁡2n)=O(log⁡3n)S(n) = S(n/2) + \bigO(\log^2 n) = \bigO(\log^3 n): parallelism Θ(n/log⁡2n)\Theta(n/\log^2 n). For n=106n = 10^6, thousands rather than about 10 (calculate in the exercises).

Beware constants: for n=16n = 16 or 3232, counting each binary-search step as an operation, parallel merge has more work and more span than sequential (searches and partition nodes pay off only for large sizes). Real implementations switch to sequential merge below a threshold, just as recursive algorithms use insertion on small arrays. GPUs use a more regular variant, merge path (Green, McColl and Bader, 2012), splitting merge into equal-sized ranges by binary search on a diagonal.

Sorting networks

Mergesort and quicksort choose comparisons based on previous results. A sorting network does not: comparisons are fixed in advance, ideal for hardware and GPU (no diverging branches) and useful in security because memory-access patterns do not depend on data.

How do you check a network sorts? Testing n!n! permutations is impossible for n=32n = 32. The key result reduces this to 2n2^n cases and is also a proof tool.

Proof

Let gg be monotone nondecreasing. A comparator commutes with gg: min⁡(g(a),g(b))=g(min⁡(a,b))\min(g(a), g(b)) = g(\min(a, b)) and likewise for maximum, because gg preserves order. By induction over comparators, if the network transforms x\vb{x} into y\vb{y}, it transforms g(x)g(\vb{x}) (applied componentwise) into g(y)g(\vb{y}).

Suppose the network fails to sort some input x\vb{x}: output y\vb{y} has yi>yi+1y_i > y_{i+1} for some ii. Choose g(z)=1g(z) = 1 if z≥yiz \ge y_i and g(z)=0g(z) = 0 otherwise, which is monotone. Input g(x)g(\vb{x}) consists of zeros and ones and the network transforms it to g(y)g(\vb{y}), with g(yi)=1g(y_i) = 1 and g(yi+1)=0g(y_{i+1}) = 0: unsorted 0–1 output. Contradiction.

∎

Batcher’s bitonic sort (1968). A sequence is bitonic if it increases then decreases, or is a cyclic rotation of one; zero–one versions have form 0a1b0c0^a1^b0^c or 1a0b1c1^a0^b1^c. The basic part is a half-cleaner: n/2n/2 comparators [i:i+n/2][i : i + n/2] in one stage. For bitonic 0–1 input, both output halves are bitonic, every upper-half element is at most every lower-half element, and at least one half is clean (all zeros or all ones). Check cases by where blocks of form 0a1b0c0^a1^b0^c fall relative to the midpoint; by the 0–1 principle, zeros and ones suffice.

Recursion gives the rest. An nn-wire bitonic merger is a half-cleaner followed by two n/2n/2 mergers: it sorts any bitonic sequence in log⁡2n\log_2 n stages. A bitonic sorter sorts halves in opposite directions (making their concatenation bitonic) and merges them. Its depth satisfies D(n)=D(n/2)+log⁡2nD(n) = D(n/2) + \log_2 n, i.e.

D(n)=log⁡2n (log⁡2n+1)2,comparadores=n2 D(n)=nlog⁡2n (log⁡2n+1)4.D(n) = \frac{\log_2 n\,(\log_2 n + 1)}{2}, \qquad \text{comparadores} = \frac{n}{2}\,D(n) = \frac{n\log_2 n\,(\log_2 n + 1)}{4}.

For n=8n = 8, 6 stages and 24 comparators; for n=16n = 16, 10 and 80. Work is Θ(nlog⁡2n)\Theta(n\log^2 n), factor log⁡n\log n above the comparison-sorting lower bound, and depth Θ(log⁡2n)\Theta(\log^2 n). Depth-O(log⁡n)\bigO(\log n) networks exist (Ajtai, Komlós and Szemerédi, 1983), but constants are so large they are not used: Batcher remains the implemented choice.

InteractiveBitonic sorting network
stage 6 of 6
of 2of 4of 8blocks1011001000001111
  • ascending comparator (minimum above)
  • descending (maximum above)
  • wire carrying a 1
Wires n
Inputs
Active comparators24 of 24
Stages (depth)6
Sorted outputyes
Correctly sorted 0–1 inputs256 of 256
Unsorted random permutations0 of 200
The complete network sorts all 28=2562^{8} = 256 zero–one inputs; by the zero–one principle it sorts every input. Click a comparator to break it.
Horizontal wires with index 0 at top; each comparator is vertical and its arrow points to the wire receiving the maximum (orange: ascending; purple: descending). Shaded bands mark phases: first blocks of 2, then 4, then 8. Advance stage by stage: ones (thick blue wires) fall down. Click inputs to change bits. Switch to ‘Permutation’ for integers. Break a comparator with a click: exhaustive testing of 2n2^n 0–1 inputs finds failures, and ‘Load counterexample’ shows one. No break is harmless, but some fail on very few inputs: with n=16n = 16, removing the first comparator of the last phase, [0:8][0 : 8], fails on only 1 of 65 536 0–1 inputs, undetected by 200 random permutations.

Pointer jumping

Linked lists and trees with parent pointers seem even more sequential than arrays: finding a node’s distance to the end requires traversing the list. Pointer jumping (Wyllie, 1979) avoids this by having every node take longer jumps in parallel.

List ranking. Each node vv has successor sig[v]\mathrm{sig}[v], with sig[uˊltimo]=uˊltimo\mathrm{sig}[\text{último}] = \text{último}, and we seek rango[v]\mathrm{rango}[v], its distance to the last. Start with rango[v]=1\mathrm{rango}[v] = 1 (0 for the last) and repeat for every vv simultaneously, always reading previous-round values:

rango[v]←rango[v]+rango[sig[v]],sig[v]←sig[sig[v]].\mathrm{rango}[v] \leftarrow \mathrm{rango}[v] + \mathrm{rango}[\mathrm{sig}[v]], \qquad \mathrm{sig}[v] \leftarrow \mathrm{sig}[\mathrm{sig}[v]].

Invariant: rango[v]\mathrm{rango}[v] is distance from vv to sig[v]\mathrm{sig}[v] in the original list, and after kk rounds sig[v]\mathrm{sig}[v] is 2k2^k positions ahead (or last). In ⌈log⁡2n⌉\lceil\log_2 n\rceil rounds all pointers reach the end and ranks are distances. This is a scan over a list instead of an array: structure no longer supplies the tree, and jumps build it.

The price is work: nn operations per round, Θ(nlog⁡n)\Theta(n\log n) total, versus Θ(n)\Theta(n) for traversal. It is not work-efficient. Work-efficient versions exist with O(n)\bigO(n) work and O(log⁡n)\bigO(\log n) span: first reduce the list by removing an independent node set (randomly chosen or via Cole–Vishkin deterministic coin tossing, 1986), solve the smaller list and reinsert.

Forest roots. With parent pointers (padre[raıˊz]=raıˊz\mathrm{padre}[\text{raíz}] = \text{raíz}), rule padre[v]←padre[padre[v]]\mathrm{padre}[v] \leftarrow \mathrm{padre}[\mathrm{padre}[v]] takes every node to its root in ⌈log⁡2h⌉\lceil\log_2 h\rceil rounds, with hh maximum height. This is parallel union-find path compression, underlying parallel connected-components algorithms (Shiloach and Vishkin, 1982) that alternate hooking trees and jumping pointers.

Schedulers: fork–join and work stealing

The greedy-scheduler theorem assumes someone knows all ready vertices at every instant and distributes them free. A real system has pp threads, each with work; coordinating through a central queue would bottleneck. The standard solution is decentralized.

In fork–join, a program creates tasks (spawn) that can run concurrently with their creator and waits for completion (sync). Work stealing executes it as follows:

  1. Each thread has a deque of ready tasks. On spawn, it pushes a task at the bottom; when needing work, it pops the most recent from the bottom (like a stack, preserving sequential locality).
  2. An idle thread becomes a thief: it picks another thread randomly and tries to steal its top, oldest task. In a divide-and-conquer tree the oldest task is largest, so a steal transfers much work at once.

The proof uses a potential function over deque tasks: each batch of pp steal attempts reduces potential by a constant fraction with constant probability, so O(p T∞)\bigO(p\,T_\infty) attempts suffice in expectation. The practical consequence is the work-first principle (Frigo, Leiserson and Randall, 1998): if T1/T∞≫pT_1/T_\infty \gg p, steals are very rare compared with work (p T∞≪T1p\,T_\infty \ll T_1), so optimize spawn on the no-steal path even if steals cost more. Variants of this scheme power Cilk, oneTBB, Java ForkJoinPool, Rust Rayon and Go and Tokio schedulers.

The next simulation runs the fork–join DAG of a recursive 4096-leaf sum with work stealing. Each steal attempt costs a step, so this is not a greedy scheduler and time can slightly exceed T1/p+T∞T_1/p + T_\infty: the theorem promises T1/p+O(T∞)T_1/p + \bigO(T_\infty), not constant 1.

[ ]Simulated work stealingBrowser
import random
from collections import deque

def fork_join(n_hojas):
    """DAG de una suma recursiva: cada nodo divide su rango en dos tareas y un join las combina."""
    hijos, continua = [], []                      # continua[v]: join que espera a v
    def nodo(join):
        hijos.append([]); continua.append(join)
        return len(hijos) - 1
    def rec(lo, hi, join):
        v = nodo(join)
        if hi - lo > 1:
            j = nodo(join)                        # el join de v hereda la continuación de v
            mid = (lo + hi) // 2
            hijos[v] = [rec(lo, mid, j), rec(mid, hi, j)]
        return v
    return hijos, continua, rec(0, n_hojas, None)

def robo_de_trabajo(n_hojas, p, semilla):
    hijos, continua, raiz = fork_join(n_hojas)
    n = len(hijos)
    faltan = {}
    for v in range(n):
        if hijos[v]:
            faltan[continua[hijos[v][0]]] = 2
    rng = random.Random(semilla)
    deques = [deque() for _ in range(p)]
    deques[0].append(raiz)
    hechos = pasos = intentos = robos = 0
    while hechos < n:
        pasos += 1
        for w in range(p):
            if deques[w]:
                v = deques[w].pop()               # el dueño trabaja por abajo
                hechos += 1
                if hijos[v]:                      # spawn: la segunda mitad queda arriba, para robar
                    deques[w].append(hijos[v][1])
                    deques[w].append(hijos[v][0])
                elif continua[v] is not None:     # el último hijo en terminar continúa con el join
                    faltan[continua[v]] -= 1
                    if faltan[continua[v]] == 0:
                        deques[w].append(continua[v])
            else:
                intentos += 1
                victima = rng.randrange(p)
                if victima != w and deques[victima]:
                    deques[w].append(deques[victima].popleft())   # el ladrón roba por arriba
                    robos += 1
    return n, pasos, intentos, robos

N = 4096
T_inf = 2 * 12 + 1                                # 12 niveles de spawn, la hoja y 12 joins
print(" p    T_p   T1/p+Tinf  aceleración  intentos  intentos/(p·Tinf)  robos")
for p in (1, 2, 4, 8, 16, 32):
    T1, Tp, intentos, robos = robo_de_trabajo(N, p, semilla=p)
    print(f"{p:2d}  {Tp:5d}   {T1/p + T_inf:9.1f}   {T1/Tp:10.2f}  {intentos:8d}  {intentos/(p*T_inf):17.2f}  {robos:5d}")
print(f"T1 = {T1}, Tinf = {T_inf}, paralelismo = {T1/T_inf:.0f}")

With parallelism near 500, speedup is virtually linear up to 16 threads; at 32 the span term becomes visible. Steal attempts remain a small multiple of p T∞p\,T_\infty as predicted and a tiny fraction of work: about 500 attempts versus 12 286 tasks with 16 threads.

Lab: parallel primitives from scratch

Blelloch scan with one vectorized operation per round: the Python loop traverses 2log⁡2n2\log_2 n rounds, never elements. This expresses a parallel algorithm via vectorization, and counters measure model work and span.

[ ]Vectorized Blelloch and Hillis–Steele scansBrowser
import time
import numpy as np

def blelloch_exclusivo(x, op=np.add, e=0):
    """Scan exclusivo de Blelloch. Cada ronda es UNA operación vectorizada: un paso paralelo."""
    x = np.array(x, copy=True)
    n = len(x)
    assert n > 0 and n & (n - 1) == 0, "n debe ser potencia de 2"
    trabajo = profundidad = 0
    s = 1
    while s < n:                                  # subida: reducción en árbol
        r = np.arange(2 * s - 1, n, 2 * s)
        x[r] = op(x[r - s], x[r])
        trabajo += len(r); profundidad += 1
        s *= 2
    x[n - 1] = e                                  # neutro en la raíz
    s = n // 2
    while s >= 1:                                 # bajada
        r = np.arange(2 * s - 1, n, 2 * s)
        t = x[r - s].copy()                       # L: agregado del subárbol izquierdo
        x[r - s] = x[r]                           # el hijo izquierdo hereda el prefijo P
        x[r] = op(x[r], t)                        # el derecho recibe P ⊕ L, en este orden
        trabajo += len(r); profundidad += 1
        s //= 2
    return x, trabajo, profundidad

def hillis_steele_inclusivo(x, op=np.add):
    x = np.array(x, copy=True)
    n = len(x)
    trabajo = profundidad = 0
    s = 1
    while s < n:
        x[s:] = op(x[:-s], x[s:])                 # NumPy evalúa el lado derecho entero antes de escribir
        trabajo += n - s; profundidad += 1
        s *= 2
    return x, trabajo, profundidad

rng = np.random.default_rng(0)
for n in (8, 1024, 2**20):
    x = rng.integers(0, 10, n)
    ex, w, d = blelloch_exclusivo(x)
    inc, w2, d2 = hillis_steele_inclusivo(x)
    ok = np.array_equal(ex, np.concatenate([[0], np.cumsum(x)[:-1]])) and np.array_equal(inc, np.cumsum(x))
    print(f"n = {n:>7}: correctos={ok}  Blelloch: trabajo {w:>8} prof {d:>2}   Hillis-Steele: trabajo {w2:>8} prof {d2:>2}")

x = rng.integers(0, 100, 16)
mx = blelloch_exclusivo(x, np.maximum, np.iinfo(x.dtype).min)[0]
print("máximo prefijo correcto:", np.array_equal(mx[1:], np.maximum.accumulate(x)[:-1]))

# coma flotante: el árbol acumula menos error que el bucle
x = rng.random(2**20).astype(np.float32)
exacto = np.concatenate([[0.0], np.cumsum(x.astype(np.float64))[:-1]])
bucle = np.concatenate([[0.0], np.cumsum(x)[:-1]]).astype(np.float64)    # cumsum acumula en float32, en orden
arbol = blelloch_exclusivo(x, np.add, np.float32(0))[0].astype(np.float64)
err = lambda y: np.max(np.abs(y - exacto)[1:] / exacto[1:])
print(f"float32, error relativo máximo de los prefijos: bucle {err(bucle):.1e}, Blelloch {err(arbol):.1e}")

On one core, Blelloch scan performs twice as many operations as np.cumsum plus scattered indexing, so is several times slower: parallelism is simulated and only work is paid. The cell checks structure: 2(n−1)2(n - 1) operations in 2log⁡2n2\log_2 n rounds for Blelloch, nlog⁡2n−n+1n\log_2 n - n + 1 in log⁡2n\log_2 n for Hillis–Steele, and float32 error about fifty times lower than the loop, for the reason in the warning.

Now scan as a tool: compaction, stable partition and radix sort, all using sum scans.

[ ]Compaction, partition and radix sort with scansBrowser
import time
import numpy as np

def scan_suma(f):
    """Scan exclusivo de sumas para cualquier n: se rellena con el neutro hasta la potencia de 2."""
    n = len(f)
    m = 1 << max(0, (n - 1).bit_length())
    relleno = np.zeros(m, dtype=np.int64)
    relleno[:n] = f
    return blelloch_exclusivo(relleno)[0][:n]

def compactar(x, quedarse):
    destino = scan_suma(quedarse.astype(np.int64))
    out = np.empty(int(quedarse.sum()), dtype=x.dtype)
    out[destino[quedarse]] = x[quedarse]          # escrituras independientes: un paso paralelo
    return out

def particion(claves, bit):
    """Partición estable por un bit: primero los ceros, luego los unos, con un único scan."""
    b = (claves >> bit) & 1
    ceros_antes = scan_suma(1 - b)
    n0 = len(claves) - b.sum()
    destino = np.where(b == 1, n0 + np.arange(len(claves)) - ceros_antes, ceros_antes)
    out = np.empty_like(claves)
    out[destino] = claves
    return out

def radix_sort(claves, bits):
    for bit in range(bits):                       # LSD: del bit menos significativo al más
        claves = particion(claves, bit)
    return claves

rng = np.random.default_rng(1)
x = rng.integers(-50, 50, 23)
print("compactar los positivos:", compactar(x, x > 0))
print("igual que x[x > 0]:", np.array_equal(compactar(x, x > 0), x[x > 0]))

claves = rng.integers(0, 2**16, 100_000)
t0 = time.perf_counter()
ordenadas = radix_sort(claves, 16)
t = time.perf_counter() - t0
print(f"radix sort de 100 000 claves de 16 bits: correcto={np.array_equal(ordenadas, np.sort(claves))}, {t:.2f} s")
print("trabajo del modelo: 16 bits x 2(n-1) operaciones de scan =", 16 * 2 * (2**17 - 1), "(con n rellenado a 2^17)")
print("profundidad del modelo: 16 bits x 2 log2(2^17) rondas =", 16 * 2 * 17)

And the 10610^6-length linear recurrence, affine-monoid scan versus loop.

[ ]A million-step linear recurrence as scanBrowser
import time
import numpy as np

def scan_afin(a, b):
    """Prefijos inclusivos (A_t, B_t) con (a1, b1) ⊕ (a2, b2) = (a2·a1, a2·b1 + b2): Blelloch sobre pares."""
    n = len(a)
    m = 1 << max(0, (n - 1).bit_length())
    A = np.ones(m); B = np.zeros(m)               # relleno con el neutro (1, 0)
    A[:n] = a; B[:n] = b
    s = 1
    while s < m:                                  # subida
        r = np.arange(2 * s - 1, m, 2 * s); l = r - s
        A[r], B[r] = A[r] * A[l], A[r] * B[l] + B[r]
        s *= 2
    A[m - 1], B[m - 1] = 1.0, 0.0
    s = m // 2
    while s >= 1:                                 # bajada: P ⊕ L, primero el prefijo
        r = np.arange(2 * s - 1, m, 2 * s); l = r - s
        tA, tB = A[l].copy(), B[l].copy()
        A[l], B[l] = A[r], B[r]
        A[r], B[r] = tA * A[r], tA * B[r] + tB
        s //= 2
    return a * A[:n], a * B[:n] + b               # exclusivo ⊕ propio elemento = inclusivo

T = 10**6
rng = np.random.default_rng(0)
a = rng.uniform(0.9, 1.0, T)
b = rng.normal(size=T)
x0 = 2.0

t0 = time.perf_counter()
xs = np.empty(T)
x = x0
for t in range(T):
    x = a[t] * x + b[t]
    xs[t] = x
t_bucle = time.perf_counter() - t0

t0 = time.perf_counter()
A, B = scan_afin(a, b)
xs_scan = A * x0 + B
t_scan = time.perf_counter() - t0

print(f"bucle de Python: {t_bucle:.2f} s   scan afín vectorizado: {t_scan:.2f} s")
print(f"diferencia máxima: {np.max(np.abs(xs - xs_scan)):.1e}   (valores de tamaño {np.max(np.abs(xs)):.0f})")
print("rondas del scan:", 2 * 20, "  operaciones de pares:", 2 * (2**20 - 1))

Here scan wins even on one core for a reason unrelated to parallelism: the loop pays the Python interpreter on each of 10610^6 steps, while scan pays it only once per each of 40 rounds. Both agree up to rounding, though product association differs.

Finally, bitonic sort as a network, the 0–1 principle in action, and pointer jumping.

[ ]Bitonic network, 0–1 principle and pointer jumpingBrowser
import numpy as np

def red_bitonica(n):
    """Lista de etapas; cada etapa, lista de comparadores (i, l, ascendente) sobre cables disjuntos."""
    etapas = []
    k = 2
    while k <= n:
        j = k // 2
        while j >= 1:
            etapas.append([(i, i ^ j, (i & k) == 0) for i in range(n) if (i ^ j) > i])
            j //= 2
        k *= 2
    return etapas

def aplicar(X, etapas):
    """Aplica la red a la vez a todas las filas de X: cada comparador es una operación vectorizada."""
    X = X.copy()
    for etapa in etapas:
        for i, l, asc in etapa:
            a, b = X[:, i].copy(), X[:, l].copy()
            lo, hi = np.minimum(a, b), np.maximum(a, b)
            X[:, i], X[:, l] = (lo, hi) if asc else (hi, lo)
    return X

ordenada = lambda Y: np.all(np.diff(Y.astype(np.int64), axis=1) >= 0, axis=1)
for n in (8, 16, 1024):
    et = red_bitonica(n)
    print(f"n = {n:4d}: {len(et)} etapas, {sum(map(len, et))} comparadores")

n = 16
et = red_bitonica(n)
todas = ((np.arange(2**n)[:, None] >> np.arange(n)) & 1).astype(np.uint8)   # las 65 536 entradas 0-1
print("ordena las 2^16 entradas 0-1:", bool(ordenada(aplicar(todas, et)).all()))
X = np.random.default_rng(1).normal(size=(200, n))
print("y por tanto cualquier entrada, por ejemplo 200 de floats:", bool(ordenada(aplicar(X, et)).all()))

for etapa, k in [(5, 0), (9, 3)]:                 # quitar un comparador
    rota = [list(e) for e in et]
    del rota[etapa][k]
    fallos = int((~ordenada(aplicar(todas, rota))).sum())
    print(f"sin el comparador {k} de la etapa {etapa}: fallan {fallos} de 65 536 entradas 0-1")

def list_ranking(sig):
    """Distancia de cada nodo al final de la lista; sig[último] = último."""
    n = len(sig)
    sig = sig.copy()
    rango = (sig != np.arange(n)).astype(np.int64)
    rondas = 0
    while np.any(sig[sig] != sig):
        rango = rango + rango[sig]                # los dos lados leen la ronda anterior
        sig = sig[sig]
        rondas += 1
    return rango, rondas

rng = np.random.default_rng(2)
for n in (10, 1000, 10**6):
    orden = rng.permutation(n)                    # orden[k] = nodo que ocupa la posición k
    sig = np.empty(n, dtype=np.int64)
    sig[orden[:-1]] = orden[1:]
    sig[orden[-1]] = orden[-1]
    rango, rondas = list_ranking(sig)
    ok = np.array_equal(rango[orden], np.arange(n - 1, -1, -1))
    print(f"list ranking, n = {n:>7}: correcto={ok}, rondas={rondas}, trabajo ≈ {n * rondas:.1e}")

The library version

ToolWhat it doesNote
np.cumsum, np.maximum.accumulate, ufunc.accumulateinclusive scansequential C loop; fast but not parallel
torch.cumsum, torch.cumprod, torch.cummaxinclusive CPU or GPU scanparallel scan kernels on GPU
jax.lax.associative_scan(fn, elems)parallel scan with any associative operatoruser supplies fn; associativity is not checked
CUB DeviceScan, Thrust inclusive_scanCUDA scansingle pass with decoupled look-back (Merrill and Garland, 2016)
concurrent.futures, joblibPython task parallelismprocesses; communication cost decides

jax.lax.associative_scan is used by research state-space-model implementations: write the affine-monoid operator and JAX generates the tree. PyTorch has no equivalent stable primitive, but Hillis–Steele scan takes a few lines of whole-tensor operations, and each GPU round is a few kernels.

The next cell runs locally (using GPU if available, otherwise CPU at smaller size). Compare logarithmic affine scan with torch.cumsum (case at=1a_t = 1, where they must agree), sequential loop and float64 reference, in float32 and float16.

[ ]Affine scan in PyTorch: timings and numerical errorLocal GPU
import time
import torch

dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
T = 2**22 if dev.type == "cuda" else 2**16        # longitud de la secuencia
T_BUCLE = min(T, 4096)                            # el bucle secuencial solo se mide en un trozo

def scan_afin_hs(a, b):
    """Prefijos inclusivos de x_t = a_t x_{t-1} + b_t en log2(T) rondas (Hillis-Steele sobre pares)."""
    A, B = a.clone(), b.clone()
    s = 1
    while s < A.shape[-1]:
        B = torch.cat([B[..., :s], A[..., s:] * B[..., :-s] + B[..., s:]], dim=-1)
        A = torch.cat([A[..., :s], A[..., s:] * A[..., :-s]], dim=-1)
        s *= 2
    return A, B

def bucle(a, b, x0):
    x = x0
    out = torch.empty_like(b)
    for t in range(b.shape[-1]):
        x = a[t] * x + b[t]
        out[t] = x
    return out

def cronometra(f, reps=3):
    f()                                           # calentamiento
    if dev.type == "cuda":
        torch.cuda.synchronize()
    t0 = time.perf_counter()
    for _ in range(reps):
        r = f()
    if dev.type == "cuda":
        torch.cuda.synchronize()                  # sin esto se mediría solo el encolado de kernels
    return r, (time.perf_counter() - t0) / reps

g = torch.Generator().manual_seed(0)
a64 = torch.empty(T, dtype=torch.float64).uniform_(0.95, 1.0, generator=g)
b64 = torch.randn(T, dtype=torch.float64, generator=g) * 0.1
x0 = 1.0
A_ref, B_ref = scan_afin_hs(a64, b64)             # referencia en float64, en la CPU
x_ref = A_ref * x0 + B_ref
print(f"dispositivo: {dev}, T = {T:,}")

unos = torch.ones(T, device=dev)
b32 = b64.to(dev, torch.float32)
(_, B1), t_scan = cronometra(lambda: scan_afin_hs(unos, b32))
c, t_cum = cronometra(lambda: torch.cumsum(b32, 0))
print(f"a = 1: |scan - cumsum| máx = {(B1 - c).abs().max().item():.1e};  scan {1e3*t_scan:.2f} ms, cumsum {1e3*t_cum:.2f} ms")

a32 = a64.to(dev, torch.float32)
_, t_bucle = cronometra(lambda: bucle(a32[:T_BUCLE], b32[:T_BUCLE], torch.tensor(x0, device=dev)), reps=1)
print(f"bucle secuencial: {1e6*t_bucle/T_BUCLE:.1f} µs por paso, unos {t_bucle/T_BUCLE*T:.1f} s para la secuencia entera")

for dt in (torch.float32, torch.float16):
    (A, B), t = cronometra(lambda: scan_afin_hs(a64.to(dev, dt), b64.to(dev, dt)))
    x = (A.double() * x0 + B.double()).cpu()
    err = ((x - x_ref).abs() / x_ref.abs().clamp_min(1.0)).max().item()
    print(f"{str(dt):14s}: scan {1e3*t:7.2f} ms, error relativo máximo {err:.1e}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

What to watch: the sequential loop costs microseconds per step even on GPU because each step launches tiny kernels and launch latency dominates; scan launches a few kernels per round and there are only log⁡2T\log_2 T rounds (22 with T=222T = 2^{22}). torch.cumsum beats the homemade scan because it is an optimized one-pass kernel; the homemade version performs Tlog⁡2TT\log_2 T operations and writes intermediate tensors each round. Float32 relative errors are order 10−710^{-7} to 10−610^{-6} and float16 order 10−310^{-3}: with 10 mantissa bits, products AtA_t of many factors near 1 quickly lose digits. Thus state-space scan kernels accumulate in float32 even with float16 or bfloat16 inputs (see hardware-aware scan).

Common mistakes

Exercises

ProofThe greedy scheduler bound
Prove: Every greedy scheduler executes a DAG with work T1T_1 and span T∞T_\infty on pp processors in time Tp≤T1/p+T∞T_p \le T_1/p + T_\infty.
0
At every step the scheduler executes min⁡(p,r)\min(p, r) of the rr ready vertices. Call a step complete with r≥pr \ge p and incomplete with r<pr < p.

Step 1 of 4. How many complete steps can there be at most?

ProofLinear recurrences are a scan
Prove: With (a1,b1)⊕(a2,b2)=(a2a1,a2b1+b2)(a_1, b_1) \oplus (a_2, b_2) = (a_2a_1, a_2b_1 + b_2), set R2\R^2 is a monoid, and the solution of xt=atxt−1+btx_t = a_tx_{t-1} + b_t is xt=Atx0+Btx_t = A_tx_0 + B_t, where (At,Bt)(A_t, B_t) is the inclusive scan of pairs (at,bt)(a_t, b_t).
0
Identify (a,b)(a, b) with function f(x)=ax+bf(x) = ax + b.

Step 1 of 4. What function does (a1,b1)⊕(a2,b2)(a_1, b_1) \oplus (a_2, b_2) represent?

NumericMergesort parallelism with sequential merge
Model mergesort with sequential merge as W(n)=2W(n/2)+nW(n) = 2W(n/2) + n and S(n)=S(n/2)+nS(n) = S(n/2) + n, with W(1)=S(1)=1W(1) = S(1) = 1. For n=220n = 2^{20}, what is parallelism W(n)/S(n)W(n)/S(n)?
NumericAnd with parallel merge
With parallel merge, the span of merging nn elements is order log⁡2n\log^2 n. Model S(n)=S(n/2)+(log⁡2n)2S(n) = S(n/2) + (\log_2 n)^2 with S(1)=1S(1) = 1 and the same previous work, W(n)=220⋅21W(n) = 2^{20}\cdot 21 for n=220n = 2^{20}. What is parallelism W(n)/S(n)W(n)/S(n)?
NumericWhat Brent guarantees
An algorithm has T1=109T_1 = 10^9 and T∞=104T_\infty = 10^4. With a greedy scheduler and p=64p = 64 processors, what minimum speedup T1/TpT_1/T_p is guaranteed?
NumericWhen does Hillis–Steele win?
For n=220n = 2^{20}, estimate each scan’s time using Tp≈T1/p+T∞T_p \approx T_1/p + T_\infty: Hillis–Steele with T1=nlog⁡2n−n+1T_1 = n\log_2 n - n + 1 and T∞=20T_\infty = 20; Blelloch with T1=2(n−1)T_1 = 2(n - 1) and T∞=40T_\infty = 40. From what processor count pp (round to nearest integer) is Hillis–Steele faster?
QuizWhat can be scanned?
Which binary operations, exactly as written, can be used directly in a parallel Blelloch scan and give the same result as the loop (in exact arithmetic)?

More than one answer may be correct.

QuizThe 0–1 principle argument
In the 0–1 principle proof, what comparator property makes the argument work?
QuizA suspicious speedup
You parallelize a scan with Hillis–Steele on 32 cores and measure it 20 times faster than the same code on 1 core. What conclusion is correct?
NumericBitonic network size
How many comparators does an n=1024n = 1024-wire bitonic sorter have?
NumericPointer-jumping rounds
A linked list has 10610^6 nodes. How many pointer-jumping rounds calculate all node ranks?
CodeExclusive Blelloch scan for any operator
Implement blelloch_exclusivo(xs, op, e), returning the list of the exclusive scan of xs with associative operator op (a two-argument function) and identity e. It must work for any length (pad with e to the next power of 2), with noncommutative operators (the result must be exactly e, x0, x0⊕x1, ... with operands in that order) and follow up-sweep and down-sweep: tests count op applications and check partial aggregates are combined, not merely an accumulator with individual elements.
def blelloch_exclusivo(xs, op, e):
  """Scan exclusivo de xs con el operador asociativo op y neutro e (subida y bajada de Blelloch)."""
  n = len(xs)
  if n == 0:
      return []
  m = 1
  while m < n:
      m *= 2
  x = list(xs) + [e] * (m - n)
  # tu código: subida (x[r] = op(x[l], x[r])), neutro en la raíz y bajada
  return []
Shift+Enter to run

Summary

Key idea
A parallel algorithm is measured by work T1T_1 and span T∞T_\infty; a greedy scheduler achieves Tp≤T1/p+T∞T_p \le T_1/p + T_\infty, so the goal is to shorten the critical path without increasing work, and Blelloch scan does so for any associative operator.
  • The computation DAG has work T1T_1 (vertices) and span T∞T_\infty (longest path). Laws Tp≥T1/pT_p \ge T_1/p and Tp≥T∞T_p \ge T_\infty bound speedup by min⁡(p,T1/T∞)\min(p, T_1/T_\infty); Amdahl is a sequential chain in series with a parallel part.
  • Brent and the greedy bound guarantee Tp≤T1/p+T∞T_p \le T_1/p + T_\infty, within factor 2 of optimum and nearly linear with parallel slackness T1/T∞≫pT_1/T_\infty \gg p.
  • Tree reduction does n−1n - 1 operations in ⌈log⁡2n⌉\lceil\log_2 n\rceil rounds. For prefixes, Hillis–Steele has span log⁡2n\log_2 n but work nlog⁡2nn\log_2 n; Blelloch has work 2(n−1)2(n-1) and span 2log⁡2n2\log_2 n, and is correct for any commutative or noncommutative monoid if order P⊕LP \oplus L is respected.
  • Scan solves compaction, partition, radix sort and linear recurrences: xt=atxt−1+btx_t = a_tx_{t-1} + b_t is an affine-monoid scan, underlying parallel state-space-model training.
  • Mergesort with sequential merge has parallelism Θ(log⁡n)\Theta(\log n); median-based parallel merge gives Θ(n/log⁡2n)\Theta(n/\log^2 n).
  • Sorting networks fix comparisons without seeing data; by the 0–1 principle 2n2^n inputs suffice to check, and Batcher bitonic sort uses n4log⁡2n(log⁡2n+1)\tfrac{n}{4}\log_2 n(\log_2 n + 1) comparators in 12log⁡2n(log⁡2n+1)\tfrac{1}{2}\log_2 n(\log_2 n + 1) stages.
  • Pointer jumping computes list ranks and forest roots in ⌈log⁡2n⌉\lceil\log_2 n\rceil rounds for factor log⁡n\log n extra work.
  • Work stealing (local deques, random thieves stealing oldest tasks) achieves T1/p+O(T∞)T_1/p + \bigO(T_\infty) in expectation with O(p T∞)\bigO(p\,T_\infty) steals, and schedules Cilk, TBB, Rayon and Java ForkJoinPool.