Artificial Intelligence & Data Science is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Parallel prefix sum

Parallel prefix sum (scan): what it is, why GPUs are good for it, and how to implement work-efficient parallel scans (Blelloch) on CUDA with examples and exam-focused notes.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Parallel prefix sum (also called scan) is a basic building block used in many GPU algorithms: stream compaction, sorting, histogram building, radix sort, building CSR for sparse matrices, and parallel algorithms where offsets or running totals are needed. An engineer uses efficient scans to convert irregular problems into regular GPU-friendly work and to reduce global-memory traffic by using shared-memory scans inside blocks.

Key ideas

  • Neutral element (identity) — e such that e ⊕ x = x ⊕ e = x for all x (for addition e = 0, for multiplication e = 1).

  • Problem assumptions — Many textbook presentations (especially the in-place Blelloch tree formulation) assume the operator is associative and that the array length n is a power of two. If n is not a power of two, either pad the input to the next power of two with identity elements or add bounds checks to handle the tail safely. State these assumptions explicitly in exam answers.

  • Two common parallel algorithms:

    • Hillis–Steele (inclusive): In log2(n) steps each element gathers values from elements at distances 1,2,4,... doubling each step. It is simple but does O(n log n) work (less work-efficient).
    • Blelloch (exclusive, work-efficient): Two-phase algorithm (up-sweep / reduce, then down-sweep). It does O(n) work (constant factor about 2n) and O(log n) span (parallel depth). This is the usual choice on GPUs because it balances work-efficiency and regular memory access.
  • Exact Blelloch description (step-by-step derivation — write this on the exam):

    1. Represent the array elements as leaves of a full binary tree of size n (draw horizontally: leaves are A[0]..A[n-1]; internal nodes store partial sums). Label tree levels from leaves (level 0) up to root (level log2(n)).
    2. Up-sweep (reduce) phase: for d = 0 to log2(n)-1 do:
      • For each k = 0..(n / 2^{d+1}) - 1 in parallel compute index = (2^{d+1})*k + (2^{d+1} - 1) and set T[index] = T[index - 2^d] ⊕ T[index]. This accumulates pairwise sums up the tree so the root gets the total sum.
      • After this phase the root contains the total (A[0] ⊕ ... ⊕ A[n-1]).
    3. Set the root value to the identity e (for exclusive scan) to prepare for down-sweep.
    4. Down-sweep phase: for d = log2(n)-1 down to 0 do:
      • For each k = 0..(n/2^{d+1}) - 1 in parallel compute index = (2^{d+1})*k + (2^{d+1} - 1);
        • let t = T[index - 2^d];
        • set T[index - 2^d] = T[index];
        • set T[index] = t ⊕ T[index];
      • This redistributes partial sums down the tree to compute exclusive prefix sums at leaves.
    5. The leaves now hold the exclusive prefix sums. If an inclusive result is required, shift or convert accordingly (e.g., S_incl[i] = S_excl[i] ⊕ A[i]; conversely S_excl[0] = e and for i > 0, S_excl[i] = S_incl[i-1]).
  • Diagram to draw (exam): draw a horizontal array of n leaves, show parent nodes above combining two children with arrows labeled “+” (or ⊕). For up-sweep, show upward arrows combining pairs at each level; for down-sweep, show downward arrows with values swapped to compute prefixes. Label indices used in formulas (index, index-2^d).

  • Complexity measures used in parallel algorithms:

    • Work (T1): total number of primitive operations across all processors (serial cost); ideally O(n).
    • Span (T∞, parallel depth): length of the longest chain of dependencies; equals time with infinite processors; for Blelloch T∞ = O(log n).
    • Work-efficiency: algorithm is work-efficient if its work equals the best sequential algorithm up to constant factors. With P processors, the parallel time satisfies T_P ≥ max(T1/P, T∞) (Brent's theorem), a bound often cited in exam justifications.

Formulas

S_incl[i] = A[0] ⊕ A[1] ⊕ ... ⊕ A[i] — inclusive prefix; A[k] are input elements; unit depends on ⊕; applies for associative ⊕.

S_excl[i] = e ⊕ A[0] ⊕ ... ⊕ A[i-1] — exclusive prefix; e is operator identity (for addition e = 0).

Work_HillisSteele = Θ(n log n) — total operations for Hillis–Steele scan; n is number of elements.

Span_HillisSteele = Θ(log n) — parallel depth for Hillis–Steele.

Work_Blelloch = Θ(n) — total operations for Blelloch scan (exactly 2n - 2 applications of ⊕ for n ≥ 2).

Span_Blelloch = Θ(log n) — parallel depth for Blelloch.

CUDA syntax to remember (each as its own short line): __global__ void kernelName(...) — declares a device kernel callable from host.

__shared__ Type arrayName[size]; — declares shared memory array inside a kernel (fast, per-block).

int tid = threadIdx.x; — thread's index inside its block (0..blockDim.x-1).

kernel<<<numBlocks, threadsPerBlock>>>(...); — kernel launch syntax from host.

cudaMalloc(&d_ptr, size) / cudaMemcpy(dst, src, size, cudaMemcpyHostToDevice) / cudaFree(d_ptr) — basic device memory management.

Use these snippets when writing CUDA scan kernels; they are what examiners expect to see in code sketches.

Worked examples

Example 1 — manual small array (theory, numeric): compute exclusive sum for A = [3,1,7,0]

  1. Write definition: S_excl[i] = sum of elements before i, with e = 0.
  2. Compute stepwise:
    • S_excl[0] = 0 (no elements before index 0).
    • S_excl[1] = 3.
    • S_excl[2] = 3 + 1 = 4.
    • S_excl[3] = 3 + 1 + 7 = 11. Answer: [0, 3, 4, 11].

Example 2 — CUDA C++ program (runs for n a power of two <= 1024). This implements Blelloch exclusive scan in one block using shared memory. Compile with nvcc.

#include <cstdio>
#include <cstdlib>
#include <cuda_runtime.h>

__global__ void blelloch_exclusive_scan(int *data, int n) {
  extern __shared__ int s[]; // size n
  int tid = threadIdx.x;
  // load into shared memory
  if (tid < n) s[tid] = data[tid];
  __syncthreads();

  int offset = 1;
  // Up-sweep (reduce)
  for (int d = n >> 1; d > 0; d >>= 1) {
    __syncthreads();
    if (tid < d) {
      int ai = offset*(2*tid+1)-1;
      int bi = offset*(2*tid+2)-1;
      s[bi] += s[ai];
    }
    offset <<= 1;
  }

  if (tid == 0) {
    // set root to identity (0 for addition)
    s[n-1] = 0;
  }

  // Down-sweep
  for (int d = 1; d < n; d <<= 1) {
    offset >>= 1;
    __syncthreads();
    if (tid < d) {
      int ai = offset*(2*tid+1)-1;
      int bi = offset*(2*tid+2)-1;
      int t = s[ai];
      s[ai] = s[bi];
      s[bi] = t + s[bi];
    }
  }
  __syncthreads();
  if (tid < n) data[tid] = s[tid];
}

int main() {
  int n;
  if (scanf("%d", &n) != 1) return 1;
  // Check power-of-two
  int p = 1; while (p < n) p <<= 1;
  if (p != n) {
    fprintf(stderr, "Error: n must be power of two (<=1024)\n");
    return 1;
  }
  int *h = (int*)malloc(n * sizeof(int));
  for (int i = 0; i < n; ++i) scanf("%d", &h[i]);

  int *d;
  cudaMalloc((void**)&d, n * sizeof(int));
  cudaMemcpy(d, h, n * sizeof(int), cudaMemcpyHostToDevice);

  blelloch_exclusive_scan<<<1, n, n * sizeof(int)>>>(d, n);
  cudaMemcpy(h, d, n * sizeof(int), cudaMemcpyDeviceToHost);

  // print output
  for (int i = 0; i < n; ++i) printf(i? " %d" : "%d", h[i]);
  printf("\n");

  cudaFree(d);
  free(h);
  return 0;
}

Sample input (stdin): 8 3 1 7 0 4 1 6 3

Exact output (stdout): 0 3 4 11 11 15 16 22

Notes about the code: it assumes n is a power of two and fits in one block (n <= maximum threads per block, commonly 1024; the actual maximum is device-dependent—query cudaDeviceProp.maxThreadsPerBlock). In production you must handle larger n by doing block-level scans and a second pass to add block offsets (prefix-sum of block sums). Also watch for shared-memory bank conflicts caused by power-of-two strides in the tree; mitigate with conflict-free padding or by using warp-level shuffles (e.g., __shfl_up_sync) for intra-warp scans.

Common mistakes

  • Confusing exclusive vs inclusive scan — always state which you will compute and show how to convert.
  • In CUDA kernel: using __syncthreads() incorrectly (not in all threads of a block or inside divergent branches) causes undefined behaviour.
  • Not handling multi-block scans: many students write a single-block kernel and forget that n may exceed block size; correct exam answers mention a two-pass approach (per-block scan + scan of block sums + add offsets).
  • Off-by-one errors in index calculations in up-sweep/down-sweep.

For your exam

Kinds of questions you will see:

  • Definitions: define prefix sum (inclusive/exclusive), associative operator, neutral element.
  • Short notes: explain Blelloch algorithm with a diagram; state complexity (work, span) and justify.
  • Derivations: step-by-step show the up-sweep and down-sweep index formulas and why they compute exclusive scan.
  • Numericals: compute a small scan by hand or show intermediate arrays after each up-sweep/down-sweep step.
  • Programs/diagrams: write kernel pseudocode or a full single-block CUDA kernel and explain how to extend to multi-block with block-sums.

What a full-marks answer includes:

  • Clear definition (inclusive vs exclusive) and assumptions (associative operator, identity element, power-of-two or padding).
  • Correct algorithm description (Hillis–Steele vs Blelloch) with complexity statements Work and Span and brief justification.
  • A correct diagram for up-sweep/down-sweep or the exact loop indices used.
  • For code questions: correct use of shared memory, __syncthreads(), correct index math, and mention of how to handle n > block size.

Quick check

  1. What property of the operator is required for parallel scans to be correct?
  2. Which scan algorithm does O(n log n) work but O(log n) span?
  3. For Blelloch exclusive scan, what value do you put at the root before the down-sweep?

Answers: 1) Associativity. 2) Hillis–Steele. 3) The identity (neutral) element, e (for addition e = 0).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?