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 additions form a chain and execute sequentially. Group differently, , and additions at each level are independent, needing only 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 . They are not: they take rounds and operations, and this primitive, scan, underlies compaction, GPU radix sort and much more.
- A recurrent network cannot be trained in parallel over time because depends on through a nonlinearity. State-space models such as Mamba (Gu and Dao, 2023) use linear recurrences 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 if uses ’s result. A processor can execute 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:
The first holds because at most vertices execute each step; the second because path vertices must execute in distinct steps in order. Hence speedup never exceeds : 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:
| Composition | Work | Span |
|---|---|---|
| then (series) | ||
| and at once (parallel) |
In a divide-and-conquer algorithm solving subproblems in parallel, this gives two recurrences instead of one: for work and for span, with the span of dividing and combining. Both use the master theorem.
Amdahl from the DAG
Amdahl’s law is a special case. If fraction of work forms a chain overlapping nothing (the “sequential” code), the DAG is the serial composition of that chain of length and a perfectly parallel part of work . Then
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 processors is generally NP-hard), but nearly, with a trivial algorithm.
Proof
Group vertices by levels: ’s level is the vertex count of the longest path ending at . There are exactly levels, same-level vertices are independent (if edge existed, ’s level would exceed ’s), and all predecessors lie on earlier levels. Execute levels in order; level with vertices takes steps. Since for any integer ,
∎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 of the ready vertices (whose predecessors have finished) each step, leaving no processor idle while work is available.
Factor 2 follows from , and the maximum lower-bounds any schedule. The guided exercise proves it by separating complete steps (at least ready), of which at most 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 incomplete steps, each executes at least one vertex, so complete steps are at most and . This is Graham’s 1966 list-scheduling bound, attained with equality by a DAG in the figure.
Condition is called parallel slackness. When parallelism is, say, ten times , term is negligible and speedup nearly perfect. Design should therefore minimize span without increasing work, not merely “use processors”: an algorithm with parallelism scales equally well on 8 cores or 10 000.
Three observations. Mergesort with sequential merge has and : the last merge, a 16-step chain, occupies half the critical path, and parallelism supports only two or three processors. The chain with loose tasks shows the bound is attained (not analytical pessimism): arrival order gives for every dividing 48, exactly . Good priority avoids this case, though not generally. And Blelloch scan has not : 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.
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 be a monoid: associative with identity . Given sequence (zero-indexed as in code and figures), its parallel prefix scan is the sequence of all prefixes. Two variants:
Convert with one operation per element: inclusive is exclusive , and exclusive is inclusive shifted one position with in front. The range-query lesson’s prefix sums are case , and the obvious loop costs .
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:
Invariant: after round , contains the aggregate of elements ending at . By induction: if before the round each cell summarizes a window of elements, combining cell with joins two contiguous windows. After rounds every window reaches the start: inclusive scan. Span is optimal , but work is
a factor 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 be a power of 2 (otherwise pad with ) and consider the full binary tree over the array, whose node for each aligned size- block is stored in that block’s last cell.
- Up-sweep. For and each block , with and : . This is tree reduction; afterwards each node stores its block aggregate.
- Root: .
- Down-sweep. For and each block: ; ; .
Proof
Write for using original values, and . After the size- up-sweep round, the last cell of each aligned size- block holds 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- round, for each block , cell holds (the prefix before the block) and retains from up-sweep. Initially (, one block with ) this holds because root is . The round leaves , the prefix before left block , and , the prefix before the right block. These are exactly what the invariant requires for size- blocks next round. After round , each cell ends its size-1 block and holds .
Cost: each size- round has blocks and performs one operation per block, so each sweep performs operations in rounds.
∎Operand order in matters: is prefix and is left-subtree aggregate , which comes after. For a commutative operator such as sum or maximum, writing 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, : with processors time is , linear speedup. Compare Hillis–Steele for :
| Work | Span | Work-efficient | |
|---|---|---|---|
| Sequential loop | yes | ||
| Hillis–Steele | no | ||
| Blelloch | yes |
Can we have both work and span? No: Snir (1986) proved that in any -input prefix circuit, operation count plus span is at least . 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 satisfying a predicate, calculate flags and their exclusive sum scan . If , destination of is : destinations are distinct and consecutive, and all elements write simultaneously. Work , span .
Stable partition (split). To separate zeros and ones by bit while preserving relative order, an exclusive scan of gives each zero’s position, and each one’s position is , where is total zeros: one scan suffices.
Parallel radix sort. Repeating stable partition for each bit, least to most significant, is LSD radix sort: for -bit keys, work and span . Fast GPU sorts vary this idea with multibit digits and a histogram scan.
Linear recurrences as scan
Consider the first-order recurrence
with given. It seems perfectly sequential. But each step is an affine function , and . Represent by pair and define
the pair for : “first , then .” Function composition is associative, so is too, with identity . 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 and then in rounds.
Vectors work likewise: scans with . Cost lies in products : dense matrices cost per operation versus per sequential step; diagonal matrices cost . 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 . 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 (), 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 , maximum and , combines with and . It is associative (representing 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:
Parallelism is only : the final sequential merge of length dominates the critical path, as in the DAG figure with . To scale, parallelize the merge.
Parallel merge (CLRS chapter 26). To merge sorted arrays and with , take median of and binary-search its position in . Everything in and is at most , everything in and at least it. Thus goes to output position , and submerges and are independent and run in parallel. If , each submerge has at most elements because . With binary search of span ,
and work remains (recurrence with solves by substitution). Mergesort with parallel merge has , the same work, and : parallelism . For , thousands rather than about 10 (calculate in the exercises).
Beware constants: for or , 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 permutations is impossible for . The key result reduces this to cases and is also a proof tool.
Proof
Let be monotone nondecreasing. A comparator commutes with : and likewise for maximum, because preserves order. By induction over comparators, if the network transforms into , it transforms (applied componentwise) into .
Suppose the network fails to sort some input : output has for some . Choose if and otherwise, which is monotone. Input consists of zeros and ones and the network transforms it to , with and : 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 or . The basic part is a half-cleaner: comparators 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 fall relative to the midpoint; by the 0–1 principle, zeros and ones suffice.
Recursion gives the rest. An -wire bitonic merger is a half-cleaner followed by two mergers: it sorts any bitonic sequence in stages. A bitonic sorter sorts halves in opposite directions (making their concatenation bitonic) and merges them. Its depth satisfies , i.e.
For , 6 stages and 24 comparators; for , 10 and 80. Work is , factor above the comparison-sorting lower bound, and depth . Depth- networks exist (Ajtai, Komlós and Szemerédi, 1983), but constants are so large they are not used: Batcher remains the implemented choice.
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 has successor , with , and we seek , its distance to the last. Start with (0 for the last) and repeat for every simultaneously, always reading previous-round values:
Invariant: is distance from to in the original list, and after rounds is positions ahead (or last). In 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: operations per round, total, versus for traversal. It is not work-efficient. Work-efficient versions exist with work and 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 (), rule takes every node to its root in rounds, with 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 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:
- 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). - 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 steal attempts reduces potential by a constant fraction with constant probability, so attempts suffice in expectation. The practical consequence is the work-first principle (Frigo, Leiserson and Randall, 1998): if , steals are very rare compared with work (), 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 : the theorem promises , not constant 1.
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 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 rounds, never elements. This expresses a parallel algorithm via vectorization, and counters measure model work and span.
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: operations in rounds for Blelloch, in 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.
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 -length linear recurrence, affine-monoid scan versus loop.
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 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.
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
| Tool | What it does | Note |
|---|---|---|
np.cumsum, np.maximum.accumulate, ufunc.accumulate | inclusive scan | sequential C loop; fast but not parallel |
torch.cumsum, torch.cumprod, torch.cummax | inclusive CPU or GPU scan | parallel scan kernels on GPU |
jax.lax.associative_scan(fn, elems) | parallel scan with any associative operator | user supplies fn; associativity is not checked |
CUB DeviceScan, Thrust inclusive_scan | CUDA scan | single pass with decoupled look-back (Merrill and Garland, 2016) |
concurrent.futures, joblib | Python task parallelism | processes; 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 , where they must agree), sequential loop and float64 reference, in float32 and float16.
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}")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 rounds (22 with ). torch.cumsum beats the homemade scan because it is an optimized one-pass kernel; the homemade version performs operations and writes intermediate tensors each round. Float32 relative errors are order to and float16 order : with 10 mantissa bits, products 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
Step 1 of 4. How many complete steps can there be at most?
Step 1 of 4. What function does represent?
More than one answer may be correct.
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 []Summary
- The computation DAG has work (vertices) and span (longest path). Laws and bound speedup by ; Amdahl is a sequential chain in series with a parallel part.
- Brent and the greedy bound guarantee , within factor 2 of optimum and nearly linear with parallel slackness .
- Tree reduction does operations in rounds. For prefixes, Hillis–Steele has span but work ; Blelloch has work and span , and is correct for any commutative or noncommutative monoid if order is respected.
- Scan solves compaction, partition, radix sort and linear recurrences: is an affine-monoid scan, underlying parallel state-space-model training.
- Mergesort with sequential merge has parallelism ; median-based parallel merge gives .
- Sorting networks fix comparisons without seeing data; by the 0–1 principle inputs suffice to check, and Batcher bitonic sort uses comparators in stages.
- Pointer jumping computes list ranks and forest roots in rounds for factor extra work.
- Work stealing (local deques, random thieves stealing oldest tasks) achieves in expectation with steals, and schedules Cilk, TBB, Rayon and Java
ForkJoinPool.