ELLMEngineering Large
Language Models
Download PDF

Chapter 30

Reductions, Prefix Scans, and Histograms

On this page

Collective primitives expose the essential GPU issues: participation masks, associative structure, synchronization scope, contention, and the boundary between local and device-wide coordination.

GEMM builds the large linear maps. Softmax, normalization, sampling, and expert routing still need collective operations: maxima, sums, prefix offsets, and bin counts. This section develops those primitives once, with ownership and masks stated carefully, so later kernels can compose them instead of inventing synchronization ad hoc.

Reduction as a tree

A reduction replaces a linear dependency with a tree. Within a warp, shuffle instructions exchange register values. Across warps, one common pattern writes a partial per warp to shared memory and lets the first warp finish.

Example status: CUDA excerpt; not compiled or benchmarked.

// Contract: all 32 lanes participate; invalid data contributes zero.
__device__ float warp_sum(float x) {
  int lane = threadIdx.x & 31;
  for (int offset = 16; offset > 0; offset >>= 1) {
    float other = __shfl_down_sync(0xffffffffu, x, offset);
    if (lane + offset < 32) x += other;
  }
  return x;
}

__device__ float block_sum(float x) {
  __shared__ float partial[32];
  int lane = threadIdx.x & 31;
  int warp = threadIdx.x >> 5;
  x = warp_sum(x);
  if (lane == 0) partial[warp] = x;
  __syncthreads();

  int warp_count = blockDim.x >> 5;
  float value = (threadIdx.x < warp_count) ? partial[lane] : 0.0f;
  if (warp == 0) {
    value = warp_sum(value);
  }
  __syncthreads();  // protect shared partials before a subsequent call
  return value;  // valid in lane 0 of warp 0
}

This excerpt requires a one-dimensional block with 32 to 1,024 threads in a multiple of 32, and every block thread must call it. Threads outside the logical input contribute zero rather than exit. This explicit full-warp contract avoids treating an arbitrary sparse mask as a valid shuffle reduction tree. Only thread zero owns the final value. A caller that lets every thread store value is incorrect; a caller that needs the sum everywhere must broadcast it through shared memory and a block barrier.

Establish a reduction invariant before using shuffles

The down-shuffle tree has a useful invariant: after stages with offsets 16, 8, 4, 2, and 1, lane zero covers all 32 original values exactly once. Other lanes may hold overlapping suffixes; those values are not independent partial sums to add again. All lanes named in the synchronization mask must execute the corresponding shuffle with the same mask, and a consumed source lane must participate. A predicate that excludes invalid data is not permission to exclude its physical lane from the collective.

For a final tile of 19 valid values executed by a full warp, put zero in lanes 19 through 31 and retain full-warp participation. A sparse mask containing 19 lanes does not make an offset-16 tree a general sparse reduction. Compaction to consecutive logical ranks or a primitive with a documented active-lane contract is needed for arbitrary membership.

For block reduction, use one partial per warp, synchronize the block, then let a complete warp reduce those partials with neutral values in unused lanes. Only the documented result lane may consume the answer. If the same scratch storage is reused by another reduction, all readers must finish before the next writers begin. This final lifetime edge matters when reductions are called repeatedly inside softmax or normalization.

Device-wide reduction

Blocks cannot generally synchronize with arbitrary other blocks in one ordinary launch. Common strategies are:

  • first kernel writes one partial per block; second kernel reduces partials;
  • blocks atomically accumulate into one or several outputs;
  • a persistent/cooperative kernel performs a grid-wide protocol on supported launches;
  • use a production primitive such as CUB.

Atomics are attractive when there are few blocks or contention is low. A two-pass reduction has extra launch and workspace cost but scales predictably.

Numerical reduction

Floating-point addition is not associative. A parallel tree changes result order and can vary across launch shape. Accumulating FP16 or BF16 values in FP32 improves stability. Pairwise trees often have better error than one long linear sum. Compensated summation improves accuracy but adds instructions and state.

Determinism may require a fixed partition and reduction order, which can reduce performance. State whether reproducibility means bitwise identity, stable tolerance, or stable model-level metrics.

Prefix scan

An exclusive scan of [a, b, c, d] produces [identity, a, a+b, a+b+c]. An inclusive scan includes the current element. Scan powers stream compaction, radix sort, cumulative offsets, token packing, and sparse indexing.

A work-efficient block scan has an upsweep that builds partial sums and a downsweep that propagates prefixes. Warp-shuffle scans reduce shared-memory traffic within warps; shared memory carries warp totals.

Example status: CUDA excerpt; not compiled or benchmarked.

// Contract: all 32 lanes participate; valid items form a lane prefix.
__device__ int warp_inclusive_scan(int x) {
  int lane = threadIdx.x & 31;
  for (int offset = 1; offset < 32; offset <<= 1) {
    int y = __shfl_up_sync(0xffffffffu, x, offset);
    if (lane >= offset) x += y;
  }
  return x;
}

Unused data lanes contribute zero but still execute the scan. This is not an arbitrary-mask scan: a sparse participation pattern requires a different lane mapping or a collective with that contract. For a device-wide scan, each block scans a tile, block totals are scanned, and the resulting offsets are added to each tile. A library handles edge cases, recursion, tuning, and temporary storage.

Stream compaction

Compaction keeps elements whose predicate is true:

  1. compute a zero-or-one flag;
  2. exclusive-scan flags into output positions;
  3. scatter selected elements;
  4. derive output count from the last prefix and flag.

This avoids one atomic per selected item. For very sparse or small workloads, atomics can be simpler and competitive. Compare contention and scan overhead.

Histograms

A naive histogram performs one global atomic per sample. If many samples choose the same bin, contention serializes updates. Common improvements:

  • privatize bins per warp or block in shared memory;
  • aggregate repeated values within a warp before one atomic;
  • use a sort-and-run-length strategy for highly concentrated inputs;
  • partition bins or data across blocks, then merge partial histograms.

Shared-memory atomics are not free, and a large bin count may not fit. The input distribution controls the best method. Benchmark uniform, skewed, and adversarial distributions.

These primitives reappear later when mixture-of-experts routing counts tokens per expert and scans those counts into expert-buffer offsets.

Segmented reductions

A segmented reduction combines values within variable-length groups. Segments may be represented by offsets, keys, or boundary flags. Short segments waste blocks if assigned one per block; long segments need multi-block cooperation.

Sort or bucket by size, combine tiny segments per block, and split very long segments. The overhead of preprocessing must be amortized across repeated operations or large workloads.

Gather, scatter, and irregular access

Gather reads out[i] = input[index[i]]; scatter writes to indexed destinations. Address locality, duplicate indices, and output conflicts dominate. Sort or reorder indices to improve locality when semantics allow. For scatter with duplicates, define whether updates are last-writer, atomic sum, max, or invalid.

Caching helps repeated gather indices, but random accesses can remain latency-bound. Vectorizing random accesses does not make them coalesced.

Use production primitives deliberately

CUB provides warp-, block-, and device-wide reductions, scans, histograms, and selection. Use it unless a fused operator, unusual data type, fixed small shape, or special semantics justify custom code.

The value of implementing a primitive is understanding its invariants. The production decision still favors a maintained library when the boundary fits.

Design Exercises

  1. Write and explain a warp-plus-block sum reduction.
  2. When would you choose atomics over a two-pass device reduction?
  3. Explain a device-wide exclusive scan.
  4. Design stream compaction and derive the output count.
  5. How would you optimize a histogram with severe hot-bin contention?
  6. What does deterministic reduction cost?

Worked Solutions

1. Warp-plus-block reduction

Each warp reduces its lanes with shuffles under the correct active mask. Lane zero writes a warp partial to shared memory. A block barrier ensures all partials are visible. The first warp loads those partials, filling inactive entries with the identity, and reduces again. Lane zero of the first warp owns the block result. The answer must state mask construction, identity values, barrier placement, and result ownership.

2. Atomics versus two passes

Use atomics when the number of blocks is modest, contention is low, the hardware supports the type efficiently, or the output has several independent bins. Use a two-pass reduction when many blocks target one location, deterministic order matters, or atomic serialization dominates. The two-pass method costs workspace, another launch, and another read/write of partials.

3. Device-wide scan

Each block scans a tile and writes its total. Recursively scan block totals to produce a prefix offset for each tile. Launch a uniform-add phase that adds the tile offset to every local prefix. Production single-pass variants exist, but this three-stage decomposition is easy to reason about and test. The operator must be associative and the identity must be correct.

4. Stream compaction

Map the predicate to flags. Exclusive-scan the flags; each true element writes to output[prefix[i]]. The final count is prefix[n-1] + flag[n-1] for nonempty input. Handle n = 0, avoid duplicate writers, and choose stable or unstable semantics explicitly.

5. Hot-bin histogram

Reduce the number of contending atomics. Privatize bins per warp or block, aggregate equal values inside a warp, then merge partial histograms. If the bin range is large or the distribution is extremely concentrated, sort or partition keys and reduce runs. Measure shared-memory footprint, merge traffic, and skewed cases; a uniform-only benchmark hides the problem.

6. Deterministic reduction

Determinism fixes partitioning and operation order, restricts atomic races, and may require extra passes or workspace. This can reduce load balancing, eliminate faster nondeterministic atomics, and lower parallelism. The cost is justified only when bitwise reproducibility is a real requirement; many applications need a numerical tolerance rather than identical bits.