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 softmax, 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 values into one scalar in levels ( 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 ([3, 2, 6, 7, 12, 3, 5, 11]). - Stream compaction runs an exclusive scan on
0/1keep flags to compute unique write offsets for retained elements (rejected items must skip writing). - Segmented reduction respects half-open segment ranges (assigning identity
0to 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.](https://assets.leetllm.com/v1/eba90c2ed817/fundamentals/gpu-parallel-primitives-lab/illustrations/_generated/primitive_dependency_shapes_dark.png)
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)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).](https://assets.leetllm.com/v1/58397b87383e/fundamentals/gpu-parallel-primitives-lab/illustrations/_generated/compaction_segments_argmax_dark.png)
Warp shuffles and block-level handoff
Within a 32-lane CUDA warp, __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:
__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 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.](https://assets.leetllm.com/v1/17a39d6867e1/fundamentals/gpu-parallel-primitives-lab/illustrations/_generated/block_warp_handoff_dark.png)
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).

Watch two numerical traps in parallel reductions:
- Signed integer partial overflow:
[I64_MAX, 1, -1, 0]has a valid final sum (I64_MAX), yet the first tree pairI64_MAX + 1overflows immediately. - Floating-point non-associativity: . 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, CUBDeviceReduce'srun_to_rundefault[5][6]) separate from accuracy (distance to the exact sum).

Parallel scan: Hillis-Steele, Blelloch, and decoupled look-back
Scan must preserve input order. Inside a block of items:
- Hillis-Steele (step-efficient): steps, additions (good for short 32-lane warp shuffles: 5 steps, 129 adds).
- Blelloch (work-efficient): steps, additions via an Up-Sweep reduction tree, setting the root to
0, and a Down-Sweep distribution pass. At , Hillis-Steele executes 4,097 additions vs. Blelloch's 1,022 (4.01x fewer).[7]
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))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).](https://assets.leetllm.com/v1/aa938bbf53c5/fundamentals/gpu-parallel-primitives-lab/illustrations/_generated/blelloch_phase_trace_dark.png)
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 (512 block totals, 1 metadata block) vs. (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].](https://assets.leetllm.com/v1/66a143c5b29e/fundamentals/gpu-parallel-primitives-lab/illustrations/_generated/scan_block_offsets_dark.png)

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 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.

Online softmax carries a scale with its sum
Naive safe softmax makes three passes over logits : find , sum , and emit . The online normalizer (Milakov & Gimelshein) combines the first two passes by carrying and merging partial chunks with a common scale:[10]
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})")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.](https://assets.leetllm.com/v1/a7bf888f2891/fundamentals/gpu-parallel-primitives-lab/illustrations/_generated/online_normalizer_dark.png)
Standalone online softmax still reads logits twice (once to compute , once to emit probabilities). FlashAttention eliminates that second HBM pass by carrying the unnormalized weighted-value accumulator alongside in SRAM, rescaling both together and dividing by once at the end.[11]

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:
from assets.primitives_model import run_checks
run_checks()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 claimWhen interpreting benchmark rates, report logical byte rate ( for int32 reduction; for int32 -> int64 scan) separately from Nsight Compute physical DRAM bandwidth.