
Recall first from Roofline and register blocking for GEMM
- Shared-memory tiling increases DRAM arithmetic intensity by reusing input values across outputs.
- The roofline bounds throughput by the smaller of the compute ceiling and bandwidth times arithmetic intensity.
- A 2 by 2 register block can perform four fused multiply-adds per four logical shared-memory operand reads at each inner-loop step.
Sum an array within one block
3 min readYou spent the last lesson optimising a single GEMM. Now you meet the workhorses that build on the same shared-memory tricks, and this lesson answers how to sum an array fast from one block up to the whole grid.
A program that measures the mean value of an image channel needs the sum of its samples. The CPU can add them in index order. On the GPU, threads can compute separate sums concurrently, then combine them. A A reduction combines many values into one result using an operation such as addition. For addition, a thread with no input contributes zero, which leaves the sum unchanged.
Start with a one-dimensional launch of 256 threads per block. Each thread starts at blockIdx.x * blockDim.x + threadIdx.x and advances by gridDim.x * blockDim.x. This grid-stride loop assigns every input index to exactly one thread. Within each iteration, neighbouring threads read neighbouring elements as long as those elements exist. With one block, the same loop covers an entire large array, and each thread accumulates many elements in a register before the block combines the register sums.
Store one sum per thread in shared memory and synchronize the block. At stride 128, thread 0 adds slot 128 to slot 0, thread 1 adds slot 129 to slot 1, and so on through thread 127. After a barrier, the first 128 slots each hold a sum of two original slots. At stride 64, the first 64 threads combine those sums. The same rule continues through stride 1, after which slot 0 contains the block's sum. The fixed power-of-two block size makes every round split the live entries into two equal halves.
The following CUDA C++ kernel uses B threads and one output slot per block. Save the snippets in a .cu file with <cuda_runtime.h> and <cstddef>, and build your host harness with nvcc. The runtime needs access to a CUDA-capable NVIDIA GPU.
constexpr unsigned B = 256;
__global__ void sum_blocks(const float* input, std::size_t n, float* output)
{
__shared__ float sums[B];
const unsigned t = threadIdx.x;
const std::size_t step = std::size_t(gridDim.x) * blockDim.x;
float value = 0.0f;
for (std::size_t i = std::size_t(blockIdx.x) * blockDim.x + t;
i < n; i += step)
value += input[i];
sums[t] = value;
__syncthreads();
for (unsigned stride = B / 2; stride > 0; stride /= 2) {
if (t < stride)
sums[t] += sums[t + stride];
__syncthreads();
}
if (t == 0)
output[blockIdx.x] = sums[0];
}
The first __syncthreads() makes the initial stores visible before threads read their partners' slots. There is one __syncthreads() per loop step, outside the if, so even threads that stop adding still reach each barrier. An early return for threads beyond the end of the array would break this requirement. Those threads store zero and follow the same barrier sequence. This also handles an empty input if you launch at least one block.
For this array of 32-bit floats, adjacent shared-memory words map to adjacent banks. In each step, the active lanes of a warp access consecutive slots for sums[t] and consecutive slots for sums[t + stride]. Each of these accesses uses distinct banks across active lanes. Both ranges can use the same banks in separate instructions without creating a conflict. A tree that uses 2 * t and 2 * t + 1 instead makes adjacent lanes access every other word at the first step, so lanes in a full warp can request different words from the same bank in one instruction.
Sum register values within a warp
2 min readOnce values are in registers within a warp, __shfl_down_sync lets each participating lane read a register value from a higher-numbered lane. The operation exchanges values directly between lanes, so the shuffle sequence needs zero shared-memory accesses and zero separate barrier calls. The mask specifies the participating lanes. In this example, all 32 lanes execute every shuffle with the same full mask.
__device__ float warp_sum(float value)
{
for (int offset = 16; offset > 0; offset /= 2)
value += __shfl_down_sync(0xffffffffu, value, offset);
return value;
}
At offset 16, lane 0 adds the value from lane 16, while lane 1 adds the value from lane 17. At offset 8, lane 0 reads lane 8's updated sum, covering four original values in total. Offsets 4, 2, and 1 complete the reduction in lane 0. Only use lane 0's result from this helper. Lanes without input contribute zero and still execute every shuffle. A full mask requires a full warp to participate. Calling this helper inside a branch taken by only the lanes with valid input can violate that requirement. Reading a value from a nonparticipating source lane yields an undefined value.
On devices of compute capability 8.0 or higher, __reduce_add_sync(mask, value) provides a warp sum for signed or unsigned 32-bit integers, with the sum available in every participating lane. Use the shuffle helper for the floating-point array in this lesson. If you measure the integer intrinsic separately, choose inputs whose sums fit the selected integer type and compile for a target that supports the intrinsic.
A block can combine warp reductions with a single block barrier. In a 256-thread block, eight warps each reduce their register values. Each warp's lane 0 writes one sum into a distinct shared-memory slot, indexed by threadIdx.x / 32. All threads then reach __syncthreads(). After the barrier, every lane of the first warp calls warp_sum again. Lanes 0 through 7 load the eight shared sums, and lanes 8 through 31 supply zeros. Lane 0 now has the block result. The shared memory and barrier belong to the transfer between warps. Each individual warp reduction uses registers.
The shared-memory tree is a useful baseline because its intermediate sums have explicit indices. The warp version reduces the number of block-wide barriers and shared-memory accesses. A large array still requires the same input reads, so a speedup in the final steps of each block can have a small effect on total runtime. Measure the complete reduction to see how much those steps cost for your input.
Combine the block sums across the grid
3 min readWith several blocks, sum_blocks writes one value per block at output[blockIdx.x]. The block barrier coordinates only threads in the same block. A block that has finished its own sum has no guarantee that the other blocks have written theirs. To combine the results, launch a second reduction in the same CUDA stream. The second launch consumes the partial array after the first kernel has finished.
sum_blocks<<<blocks, B>>>(d_input, n, d_partials);
sum_blocks<<<1, B>>>(d_partials, blocks, d_total);
Here blocks is a positive grid size, d_partials holds blocks floats, and d_total holds one float. These launches use the default stream. In the final pass, the same grid-stride loop lets each thread consume several partial sums if blocks exceeds B. If the partial array is large enough that the single final block dominates the time, reduce it with another multi-block pass into a separate buffer, then finish with one block. Each pass takes the preceding pass's output count as its input length.
You can also accumulate each block's sum directly into a single device float. Make a variant of the kernel whose final statement is if (t == 0) atomicAdd(output, sums[0]);. Before every run of that variant, zero the accumulator with cudaMemsetAsync(d_total, 0, sizeof(float), 0) in the same default stream. atomicAdd updates the value without losing concurrent additions. The host can read the total after the kernel completes. The updates all target one address, so contention can grow as you add blocks. In the two-pass version, the first kernel writes distinct addresses, and the final kernel adds a launch and reads the partial array.
For verification, accumulate the same host array into a double reference. Start with all ones and a length that leaves a tail. For counts up to 16,777,216 (2 to the power 24), all the nonnegative integer intermediate sums in these float kernels are exactly representable, so the result should equal the count exactly. For fractional inputs, the CPU loop, the tree, and the atomic updates can add in different orders. Compare the absolute error using fabs and a condition such as fabs(gpu - reference) <= atol + rtol * fabs(reference). Choose and report tolerances for your input range and accuracy requirement. The absolute term matters when the reference is near zero. The atomic version can also produce different rounded results across runs because blocks can update the accumulator in different orders.
For timing, keep the input on the device and warm up each variant before recording trials. Record CUDA events around the full operation in the same stream using cudaEventRecord. Wait for the stop event with cudaEventSynchronize, then get elapsed milliseconds with cudaEventElapsedTime. Check cudaGetLastError after each launch and check the runtime calls, including the synchronization that can report execution failures. Include both launches in the two-pass time and include the accumulator reset in the atomic time. Keep allocation and host-device copies outside those timings. Use clock_gettime with CLOCK_MONOTONIC for a separate CPU interval around the reference loop and check both clock calls. Report repeated timings with the same input and launch settings, along with the result checks.
A reduction returns the total for the array. The next lesson, Prefix sum and its uses, asks how to obtain a running total at every position while still computing in parallel.
Key takeaways
- A shared-memory tree halves its stride each round and uses a block barrier before the next round consumes the results.
- Warp reduction intrinsics combine lane values in registers without shared memory or a separate barrier.
- A grid reduction can write one partial sum per block for a final pass or atomically add each block sum to a zeroed accumulator.
- Floating-point sums can differ when parallel execution changes the addition order.
Reflect
- Explain to a colleague, in two sentences: implement a shared-memory block sum using stride halving.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pageclock_gettime(3): monotonic clocks for host timing
- Man pagefabs(3): floating-point absolute value for result verification
Official documentation first. Links checked when the lesson was published.