Skip to content
Skip to lesson
Back to Topics
LearnGPU Systems & LLM InferenceGPU Parallel Primitives Lab
HardInference Optimization12 min read

GPU Parallel Primitives Lab

Eight independent values are easy. Their sum is not. Follow the dependencies that make reduction, scan, and online softmax safe on a GPU.

On this page

Eight numbers sit in GPU memory: [3, -1, 4, 1, 5, -9, 2, 6]. An elementwise ReLU processes each lane independently; a sum cannot. Attention , RMSNorm, cross-entropy loss, and stream compaction all depend on parallel primitives that coordinate values across warp lanes, thread blocks, or the entire grid. While the kernel optimization lab focused on memory layout, this lab focuses on data dependencies and safe publication.

One total or every index?

Match the primitive to what downstream consumers need:

  • Reduction folds nn values into one scalar in ⌈log⁡2n⌉\lceil \log_2 n \rceil levels (n−1n-1 additions): [3,-1,4,1,5,-9,2,6] -> [2,5,-4,8] -> [7,4] -> 11.
  • Prefix scan preserves every running total: exclusive scan sums strictly earlier elements ([0, 3, 2, 6, 7, 12, 3, 5]), while inclusive scan satisfies inclusive⁡[i]=exclusive⁡[i]+xi\operatorname{inclusive}[i] = \operatorname{exclusive}[i] + x_i ([3, 2, 6, 7, 12, 3, 5, 11]).
  • Stream compaction runs an exclusive scan on 0/1 keep flags to compute unique write offsets for retained elements (rejected items must skip writing).
  • Segmented reduction respects half-open segment ranges (assigning identity 0 to empty ranges like [4, 4)), and arg reduction carries (value, index) with an explicit tie-breaking rule (lowest index) and NaN policy.
Top panel shows a reduction tree combining [3, -1, 4, 1, 5, -9, 2, 6] into [2, 5, -4, 8], then [7, 4], then 11. Bottom panel shows aligned 8-column rows for index, input, exclusive prefix [0, 3, 2, 6, 7, 12, 3, 5], and inclusive prefix [3, 2, 6, 7, 12, 3, 5, 11], highlighting index 3 where 6 + 1 = 7.
A reduction folds pairs into one total (11), whereas exclusive and inclusive scans publish a cumulative state at every index.
primitive-reference.py
import numpy as np

x = np.array([3, -1, 4, 1, 5, -9, 2, 6], dtype=np.int64)
inclusive = np.cumsum(x)
exclusive = np.concatenate(([0], inclusive[:-1]))

flags = (x > 0).astype(np.int64)
offsets = np.concatenate(([0], np.cumsum(flags)[:-1]))
compacted = np.empty(int(flags.sum()), dtype=np.int64)
compacted[offsets[flags == 1]] = x[flags == 1]

bounds = [0, 4, 4, 8]
segments = [int(x[a:b].sum()) for a, b in zip(bounds, bounds[1:])]
print("sum:", int(x.sum()), "| argmax:", (int(x.max()), int(np.argmax(x))))
print("exclusive:", exclusive.tolist(), "| compacted >0:", compacted.tolist())
print("segment sums [0,4), [4,4), [4,8):", segments)
Output
sum: 11 | argmax: (6, 7)
exclusive: [0, 3, 2, 6, 7, 12, 3, 5] | compacted >0: [3, 4, 1, 5, 2, 6]
segment sums [0,4), [4,4), [4,8): [7, 0, 4]
Top band shows stream compaction keeping positive elements of [3, -1, 4, 1, 5, -9, 2, 6] at exclusive scan offsets [0, 1, 1, 2, 3, 4, 4, 5] into compacted output [3, 4, 1, 5, 2, 6]. Bottom left shows segmented reduction over half-open ranges [0, 4) = 7, [4, 4) = 0, and [4, 8) = 4. Bottom right shows argmax returning (6, 7) and tie-breaking [6, -1, 6] to (6, 0).
Exclusive scan turns `0/1` flags into compaction destinations; empty half-open segments return identity `0`; argmax returns both value and earliest index.

Warp shuffles and block-level handoff

Within a 32-lane , __shfl_down_sync exchanges registers directly without touching shared memory or incurring bank conflicts.[1][2] Offsets 16, 8, 4, 2, 1 reduce 32 lanes into lane 0:

warp-and-block-sum.cu
__device__ long long warp_sum(long long value) {
    constexpr unsigned kFullMask = 0xffffffffu;
    const unsigned lane = threadIdx.x % warpSize;
    for (int offset = warpSize / 2; offset > 0; offset /= 2) {
        const long long other = __shfl_down_sync(kFullMask, value, offset);
        if (lane + offset < warpSize) value += other;
    }
    return value;  // Valid total in lane 0.
}

// Block reduction (256 threads = 8 warps):
sum = warp_sum(sum);
if (lane == 0) warp_sums[warp] = sum;
__syncthreads();  // Outside all warp/lane conditionals.
if (warp == 0) {
    long long block_sum = warp_sum(lane < 8 ? warp_sums[lane] : 0);
    if (lane == 0) block_sums[blockIdx.x] = block_sum;
}
Left shows all 32 warp lanes with lanes 0 to 19 holding 1 and tail lanes 20 to 31 padded with 0, plus Lane 0 combining offsets 16, 8, 4, 2, and 1 along 1 -> 2 -> 3 -> 5 -> 10 -> 20. Right top shows early tail exit leaving Lane 20 undefined when Lane 4 reads it at offset 16. Right bottom shows Lane 16 at offset 16 rejecting source 32 >= 32 and keeping total 20.
All 32 warp lanes execute every shuffle with padded zero tails; early tail exit leaves partner reads undefined.
Left traces warp 0 holding [1..8] in lanes 0 to 7 and zeros in lanes 8 to 31: offsets 16, 8, 4, 2, and 1 bring lane 0 from 1 through 1, 1, 6, and 16 to 36. Right shows eight warp leaders publishing [1..8] into shared warp_sums before __syncthreads(), then warp 0 padding lanes 8 to 31 with zero and summing to 36.
Eight warp leaders deposit partials in shared memory, `__syncthreads()` publishes them, and warp 0 reduces lanes `0..7` (padding `8..31` with zero) into the block total.

Grid aggregation and non-associative floats

Ordinary launches cannot wait on a grid-wide barrier because resident blocks can stall forever waiting for unscheduled blocks in the queue (Cooperative Groups requires an explicit co-resident cooperative launch).[3] Instead, reduce across blocks either with multi-pass hierarchical kernels (512 inputs/block shrinks 4,194,304 elements -> 8,192 -> 16 -> 1 in three same-stream passes[4]) or global atomics (matching signed/unsigned accumulator types and profiling contention).

Left hardware residency diagram shows an ordinary launch of eight blocks on a 4-SM GPU: Blocks B0 through B3 occupy all four SM slots and stall at a grid.sync barrier waiting for Blocks B4 through B7, while B4 through B7 sit in the hardware queue waiting for a free SM slot, forming a circular deadlock. Right diagram shows a cooperative launch with eight co-resident SM slots holding B0 through B7 simultaneously so every block reaches grid.sync and resumes.
Resident blocks deadlock if they wait for queued blocks in an ordinary launch; grid barriers require co-resident cooperative launches.

Watch two numerical traps in parallel reductions:

  1. Signed integer partial overflow: [I64_MAX, 1, -1, 0] has a valid final sum (I64_MAX), yet the first tree pair I64_MAX + 1 overflows immediately.
  2. Floating-point non-associativity: (a+b)+c≠a+(b+c)(a + b) + c \ne a + (b + c). In FP32, (1e8 + 1.0) + (-1e8) = 0.0, while (1e8 + -1e8) + 1.0 = 1.0. Two race-free reduction trees can therefore disagree without a synchronization bug. Keep repeatability (same bits across runs, CUB DeviceReduce's run_to_run default[5][6]) separate from accuracy (distance to the exact sum).
Top number line shows IEEE-754 float32 spacing near 1e8, where ULP(1e8) = 8.0 and the rounding midpoint sits at 1e8 + 4.0. Adding 1.0 lands at 1e8 + 1.0, inside the snap-back zone, so it rounds back to 1e8 and loses 1.0 completely. Bottom left reduction tree evaluates (1e8 + 1.0) + (-1e8) = 0.0 (100% error). Bottom right tree evaluates (1e8 + -1e8) + 1.0 = 1.0 (exact), illustrating why pairwise or Kahan grouping preserves small terms.
Near 10810^8, FP32 ULP spacing is 8.08.0, so adding 1.01.0 falls below the +4.0+4.0 midpoint and rounds away; grouping (108−108)+1.0(10^8 - 10^8) + 1.0 or using Kahan compensation preserves the small term.

Parallel scan: Hillis-Steele, Blelloch, and decoupled look-back

Scan must preserve input order. Inside a block of nn items:

scan-phases.py
from assets.primitives_model import block_scan, device_scan

trace = []
local, total = block_scan([3, -1, 4, 1], width=4, trace=trace)
for phase, vals in trace:
    print(f"{phase:8}: {vals}")
print("Device-wide:", device_scan([3, -1, 4, 1, 5, -9, 2, 6], width=4))
Output
up 1    : [3, 2, 4, 5]
up 2    : [3, 2, 4, 7]
root = 0: [3, 2, 4, 0]
down 2  : [3, 0, 4, 2]
down 1  : [0, 3, 2, 6]
Device-wide: [0, 3, 2, 6, 7, 12, 3, 5]
Left traces Blelloch exclusive scan on [3, -1, 4, 1]: up-sweep reduces to 7, clearing the root to 0 seeds down-sweep outputs [0, 3, 2, 6], while Hillis-Steele computes [3, 2, 3, 5] then [3, 2, 6, 7]. Right charts addition counts: at N = 32 Hillis-Steele uses 129 vs 62 for Blelloch (2.08x), and at N = 512 it uses 4,097 vs 1,022 (4.01x).
Blelloch computes exclusive scan in two sweeps over one array, cutting additions 4.01x vs. Hillis-Steele at N=512N=512.

To stitch blocks device-wide, multi-pass scan writes block_sums, recursively scans block_sums, and adds each block's base offset back to its local prefixes. Always test recursion boundaries such as 5122=262,144512^2 = 262{,}144 (512 block totals, 1 metadata block) vs. 262,145262{,}145 (513 totals, 2 metadata blocks).

Top panel shows Pass 1 running local exclusive scans on Block 0 [3, -1, 4, 1] -> [0, 3, 2, 6] (total 7) and Block 1 [5, -9, 2, 6] -> [0, 5, -4, -2] (total 4). Middle scans block_totals [7, 4] into offsets [0, +7]. Bottom panel shows Pass 3 adding +0 to Block 0 and +7 to Block 1 to yield [0, 3, 2, 6, 7, 12, 3, 5].
Multi-pass scan scans block totals `[7, 4]` into offsets `[0, +7]` and adds `+7` to Block 1's local outputs.
Top band shows integer reduction shrinking 4,194,304 int32 inputs at 512 elements per block into 8,192 int64 partials, 16 partials, and 1 final sum. Bottom band shows the scan hierarchy threshold at 512^2 = 262,144 elements: 262,144 yields 512 block totals fitting one metadata block, while 262,145 (+1) yields 513 totals spanning 2 blocks and adding a recursion level.
Testing 5122+1=262,145512^2 + 1 = 262{,}145 elements exercises the extra metadata recursion level that power-of-two tests miss.

Decoupled look-back (used by CUB DeviceScan) avoids the extra full-array write/read pass.[7][8][9] Each tile publishes status X (uninitialized), A (local aggregate ready), or P (inclusive prefix ready) using release/acquire memory ordering. Tile kk walks left through tiles k-1, k-2, ..., accumulating A aggregates until hitting the first P prefix, then publishes its own P and writes final outputs in one pass.

Top band shows Tile 3 starting with local aggregate 2, walking left to read Tile 2 aggregate A=3 (running 5), Tile 1 aggregate A=4 (running 9), and Tile 0 prefix P=7 (inclusive prefix 16, exclusive offset 14). Bottom band shows write-before-release on the writer side matching acquire-before-read on the consumer side; plain flag polling lacks ordering and progress guarantees.
Tile 3 walks left until status `P` to get exclusive offset 14 and inclusive prefix 16, relying on release/acquire visibility rather than plain flag polling.

Online softmax carries a scale with its sum

Naive safe softmax makes three passes over logits xx: find m=max⁡jxjm = \max_j x_j, sum d=∑jexj−md = \sum_j e^{x_j - m}, and emit pi=exi−m/dp_i = e^{x_i - m} / d. The online normalizer (Milakov & Gimelshein) combines the first two passes by carrying (m,d)(m, d) and merging partial chunks with a common scale:[10]

m=max⁡(ma,mb),d=daema−m+dbemb−mm = \max(m_a, m_b), \qquad d = d_a e^{m_a - m} + d_b e^{m_b - m}
softmax-partitions.py
from math import exp, isclose, fsum
from assets.primitives_model import softmax_state, merge_states, softmax

x = [3, -1, 4, 1, 5, -9, 2, 6]
left, right = softmax_state(x[:4]), softmax_state(x[4:])
m, d = merge_states(left, right)
assert m == 6 and isclose(d, fsum(exp(v - 6) for v in x), rel_tol=1e-15)
assert isclose(fsum(softmax(x)), 1.0, abs_tol=1e-15)
print(f"left=({left[0]}, {left[1]:.6f}), right=({right[0]}, {right[1]:.6f}) -> merged=({m}, {d:.6f})")
Output
left=(4, 1.424404), right=(6, 1.386195) -> merged=(6, 1.578968)
Top band merges Chunk A [3, -1, 4, 1] (m=4, d=1.424404) rescaled by exp(4-6)=0.135335 with Chunk B [5, -9, 2, 6] (m=6, d=1.386195) into global m=6 and d=1.578968. Bottom left charts unscaled Chunk A (1.424), rescaled Chunk A (0.193), Chunk B (1.386), and merged d (1.579). Bottom right shows the proportional share split: 12.2% rescaled A and 87.8% Chunk B.
Rescaling Chunk A by e4−6e^{4-6} aligns both chunks to maximum 6 before summing to d=1.578968d = 1.578968.

Standalone online softmax still reads logits twice (once to compute (m,d)(m, d), once to emit probabilities). FlashAttention eliminates that second HBM pass by carrying the unnormalized weighted-value accumulator OO alongside (m,d)(m, d) in SRAM, rescaling both together and dividing by dd once at the end.[11]

Left bar chart compares HBM element transfers per row: naive 3-pass softmax moves 4N elements (three reads of x plus one write of P), standalone online 2-pass softmax moves 3N elements (two reads of x plus one write of P), and fused SRAM online softmax moves 1N elements in a single streaming pass. Right stacked bars align all three methods on a shared 4N scale, showing how keeping (m, d, O) in SRAM avoids 3N of intermediate HBM traffic.
Naive 3-pass softmax moves 4N4N elements through HBM and standalone online softmax moves 3N3N; fusing (m,d,O)(m, d, O) in SRAM cuts traffic to a single 1N1N streaming pass.

Sanitize, benchmark against CUB, and run the lab

Always run compute-sanitizer (memcheck, racecheck, synccheck) on odd edge sizes like 4099 alongside numerical reference checks: a warp barrier orders only its own warp, so cross-warp shared-memory handoffs require a block barrier (__syncthreads()), while clean memory checks never catch a missing block-offset addition.[12]

For standalone whole-array reductions or scans, start with CUB (cub::DeviceReduce, cub::DeviceScan, widening int32 via thrust::make_transform_iterator in CCCL 3.0+[13][14]). Write custom CUDA only when fusing a primitive with surrounding producers/consumers (often using cub::BlockReduce/BlockScan inside the fused kernel), and compare full-pipeline wall times with reused scratch buffers.

Download primitives_lab.cu, primitives_host.hpp, primitives_model.py, and benchmark-log.md. Run edge shapes (1, 31, 32, 33, 255..257, 511..513, 4099, 262145) and verify the Python hierarchy model on CPU right now:

primitive-model-checks.py
from assets.primitives_model import run_checks
run_checks()
Output
CPU models: 17 hierarchy sizes and 260 recursive scan cases pass
Overflow, absent shuffle sources, invalid widths and masked/nonfinite rows checked
No CUDA compilation, GPU synchronization, sanitizer or performance claim

When interpreting benchmark rates, report logical byte rate (4N/t4N / t for int32 reduction; (4N+8N)/t=12N/t(4N + 8N) / t = 12N / t for int32 -> int64 scan) separately from Nsight Compute physical DRAM bandwidth.

Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 6 answered
1.A 32-lane CUDA warp runs __shfl_down_sync(0xffffffff, val, 16). Lanes 0..22 hold 1 and lanes 23..31 hold 0. In Run 1 all lanes execute; in Run 2 lane 24 exits before the shuffle. What does lane 8 receive in each run?
2.Three scan blocks have totals [3, -2, 5]. Block 2's local exclusive scan is [0, 4, 1]. What are Block 2's global exclusive outputs?
3.Merge online-softmax states (m=1, d=2) and (m=3, d=1.5) onto one common scale.
4.Exact reference is 1.00 (atol 0.02). Kernel X always returns 0.00. Kernel Y returns 0.99 or 1.01 across runs. How do repeatability and accuracy classify each kernel?
5.Stream compaction keeps positive values from [5, 0, -2, 8, 3] via exclusive scan of 0/1 flags. Where does 8 land, and which items write?
6.Values [2, 4, 1, -3, 8] have half-open segment boundaries [0, 2, 2, 5]. What segmented sums preserve all groups including the empty segment?

6 questions remaining.

References

C/C++ Language Extensions

NVIDIA · 2026

https://docs.nvidia.com/cuda/cuda-programming-guide/05-appendices/cpp-language-extensions.html

CUDA Programming Guide

NVIDIA · 2026

https://docs.nvidia.com/cuda/cuda-programming-guide/

CUDA: Device-Callable APIs and Intrinsics

NVIDIA · 2026

https://docs.nvidia.com/cuda/cuda-programming-guide/05-appendices/device-callable-apis.html

Optimizing Parallel Reduction in CUDA

Harris, M. · 2007 · NVIDIA Developer Technology

https://developer.download.nvidia.com/compute/cuda/1.1-Beta/x86_website/projects/reduction/doc/reduction.pdf

cub::DeviceReduce

NVIDIA · 2026 · CUDA Core Compute Libraries documentation

https://nvidia.github.io/cccl/unstable/cub/api/structcub_1_1DeviceReduce.html

CCCL: Determinism

NVIDIA · 2026

https://nvidia.github.io/cccl/unstable/cccl/determinism.html

Single-pass Parallel Prefix Scan with Decoupled Look-back

Merrill, D. and Garland, M. · 2016 · NVIDIA Technical Report NVR-2016-002

https://research.nvidia.com/sites/default/files/pubs/2016-03_Single-pass-Parallel-Prefix/nvr-2016-002.pdf

cub::DeviceScan

NVIDIA · 2026 · CUDA Core Compute Libraries documentation

https://nvidia.github.io/cccl/unstable/cub/api/structcub_1_1DeviceScan.html

CUB Look-Back Scan Agent Source

NVIDIA · 2026

https://github.com/NVIDIA/cccl/blob/main/cub/cub/agent/agent_scan.cuh

Online normalizer calculation for softmax.

Milakov, M. & Gimelshein, N. · 2018

https://arxiv.org/abs/1805.02867

FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness

Dao, T., Fu, D. Y., Ermon, S., Rudra, A., Ré, C. · 2022 · NeurIPS 2022

https://arxiv.org/abs/2205.14135

Compute Sanitizer

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/compute-sanitizer/ComputeSanitizer/

CUB Developer Overview

NVIDIA · 2026 · CUDA Core Compute Libraries documentation

https://nvidia.github.io/cccl/unstable/cub/developer_overview.html

CCCL 2.x - CCCL 3.0 migration guide

NVIDIA · 2026

https://nvidia.github.io/cccl/unstable/cccl/3.0_migration_guide.html

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.