Reductions
Summing a large array is the "hello world" of parallel cooperation. It is simple enough to reason about completely, and it exposes nearly every performance issue a kernel can have: serial bottlenecks, shared memory, barriers, divergence, occupancy, and bandwidth.
The naive kernel#
One thread per element, one global atomic per element:
__global__ void reduce(const float* in, float* out, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) atomicAdd(out, in[i]);
}Correct, and terrible: n atomics to one address, fully serialised. For 16 million floats this is orders of magnitude slower than the memory system allows.
Step 1: one serial sum per block#
A better first step: each block sums its own chunk in shared memory, then performs a single global atomic.
#include <cstdio>
#include <cuda_runtime.h>
constexpr int BLOCK = 256;
__global__ void reduce(const float* in, float* out, int n) {
__shared__ float sdata[BLOCK];
int tid = threadIdx.x;
int i = blockIdx.x * blockDim.x + tid;
sdata[tid] = (i < n) ? in[i] : 0.0f;
__syncthreads();
// Tree reduction: 256 values -> 1 in eight steps.
for (int s = BLOCK / 2; s > 0; s >>= 1) {
if (tid < s) {
sdata[tid] += sdata[tid + s];
}
__syncthreads();
}
if (tid == 0) atomicAdd(out, sdata[0]);
}
int main() {
const int n = 1 << 20;
float *in, *out;
cudaMallocManaged(&in, n * sizeof(float));
cudaMallocManaged(&out, sizeof(float));
for (int i = 0; i < n; ++i) in[i] = 1.0f;
*out = 0.0f;
int blocks = 4096;
reduce<<<blocks, BLOCK>>>(in, out, n);
cudaDeviceSynchronize();
printf("n = %d, blocks = %d\n", n, blocks);
printf("sum = %.1f\n", *out);
cudaFree(in); cudaFree(out);
return 0;
}n = 1048576, blocks = 4096 sum = 1048576.0
Why the tree works#
Instead of one thread adding 256 values, the block halves the active set each step:
step 0: 256 values
step 1: 128 partial sums (thread i adds i + 128)
step 2: 64
step 3: 32
...
step 8: 1That is log₂(256) = 8 steps instead of 256. All 256 threads participate for the first step, 128 for the second, and so on. The work is n additions in total — the same as a serial loop — but spread across threads.
The __syncthreads() inside the loop is required: step k+1 reads partial sums written in step k. Without it, some threads read stale values.
Step 2: stop using shared memory for the last warp#
When s < 32, only the first warp is still active. It is using shared memory and block barriers to exchange values between lanes — but lanes can exchange values directly with __shfl_down_sync:
__device__ __forceinline__ float warpReduce(float v) {
#pragma unroll
for (int offset = 16; offset > 0; offset >>= 1) {
v += __shfl_down_sync(0xffffffffu, v, offset);
}
return v;
}Each lane receives a value from lane + offset, adds it, and after five steps lane 0 holds the warp total. No shared memory, no barrier, no bank conflicts.
Step 3: one kernel, many blocks#
Combine a grid-stride accumulation with the warp reduction. Each thread first adds several elements into a register, so the expensive cooperation happens once per block rather than once per element.
#include <cstdio>
#include <cuda_runtime.h>
constexpr int BLOCK = 256;
__device__ __forceinline__ float warpReduce(float v) {
#pragma unroll
for (int offset = 16; offset > 0; offset >>= 1) {
v += __shfl_down_sync(0xffffffffu, v, offset);
}
return v;
}
__global__ void reduce(const float* in, float* out, int n) {
float sum = 0.0f;
for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n;
i += blockDim.x * gridDim.x) {
sum += in[i];
}
__shared__ float warpSums[BLOCK / 32];
sum = warpReduce(sum);
if ((threadIdx.x & 31) == 0) warpSums[threadIdx.x >> 5] = sum;
__syncthreads();
if (threadIdx.x < 32) {
float v = (threadIdx.x < BLOCK / 32) ? warpSums[threadIdx.x] : 0.0f;
v = warpReduce(v);
if (threadIdx.x == 0) atomicAdd(out, v);
}
}
int main() {
const int n = 1 << 20;
float *in, *out;
cudaMallocManaged(&in, n * sizeof(float));
cudaMallocManaged(&out, sizeof(float));
for (int i = 0; i < n; ++i) in[i] = 1.0f;
*out = 0.0f;
reduce<<<1024, BLOCK>>>(in, out, n);
cudaDeviceSynchronize();
printf("sum = %.1f\n", *out);
cudaFree(in); cudaFree(out);
return 0;
}sum = 1048576.0
Each block now performs exactly one global atomic instead of 256 or 1,024. The grid is free to use any number of blocks; the loop absorbs the extra elements.
What the three versions cost#
Illustrative numbers for 16.7 million floats (64 MiB) on an A100-class GPU:
| Version | Time | Bottleneck |
|---|---|---|
| One thread, serial | ~3.9 ms | One lane doing 16M adds |
| One thread per element, global atomics | ~2.5 ms | Atomic serialisation |
| Shared tree, one block per 256 elements | ~0.09 ms | Global memory bandwidth |
| Grid-stride + warp shuffle | ~0.06 ms | Global memory bandwidth |
| Theoretical floor (64 MiB ÷ 1.5 TB/s) | ~0.043 ms | DRAM |
The last two versions are within noise of each other because the kernel is now memory-bound. Once every byte is read at full bandwidth, no amount of arithmetic tuning helps.
Determinism and two-pass reductions#
atomicAdd gives a different summation order on every run. For integers the result is exact; for floats, the last bits may wobble. If you need reproducibility:
- Write one partial sum per block to a temporary array.
- Launch a second kernel to reduce the partials.
float* partials;
cudaMalloc(&partials, blocks * sizeof(float));
reduce<<<blocks, 256>>>(in, partials, n); // writes partials[b]
reduce<<<1, 256>>>(partials, out, blocks); // fixed orderThe second kernel is tiny; the extra launch costs microseconds. Many libraries use this pattern.
Reduction is a shape, not just a sum#
The same tree works for:
- Max/min: replace
+withfmaxf/fminf. - Product: multiply instead of add, initialise to 1.
- Dot product: accumulate
a[i] * b[i]before the tree. - Argmax: carry
(value, index)pairs and compare values.
Warp shuffle supports all of these; it just shuffles a different payload.
Common mistakes#
- Barrier inside the guard.
if (tid < s) { ...; __syncthreads(); }deadlocks. - Reading the wrong half.
sdata[tid] += sdata[tid + s]requirestid + s < BLOCK; thetid < sguard ensures it. - Starting the tree at
BLOCKinstead ofBLOCK/2. The first step would read out of bounds. - Forgetting
volatileor a fence when sharing without barriers. Use__syncthreads(). - Assuming the last block is full.
nis rarely a multiple of the block size; use the bounds check when loading. - Using 1,024-thread blocks "for more parallelism". Fewer, larger blocks can reduce occupancy. 256 is a good default.
Exercises#
- Change
nto 1,000,003. Does the answer stay correct? Which line handles the tail? - Replace the shared tree with a serial sum by thread 0. Measure both. How close is the tree to the memory floor?
- Implement a max reduction with the same structure. Initialise empty lanes to
-INFINITY. - Make the final kernel write one partial per block, then reduce the partials in a second launch. Compare the result to the atomic version over ten runs.
- Why does the warp-shuffle version need the
threadIdx.x < 32guard before the secondwarpReduce? What happens if all 256 threads call it withwarpSumsonly 8 elements long?
Next: keeping the GPU busy while data is still in flight.