Add values across a block
Trace a block reduction and identify the barrier that makes each partial sum safe to read.
Before you run
Keep the input values consecutive, starting at 1.0. This time the block returns one sum. First each thread writes its value to shared memory. The barrier orders those writes before threads read their partners. After each addition stage the whole block meets again.
Definitions
- Reduction
- An operation that combines several values into one.
- Shared memory
- Storage accessible to threads in a block.
- Block barrier
- A synchronisation point reached by every participating thread in the block before any continue.
Read the starter excerpts
Read-only CUDA C++ · sum · starter kernel
__global__ void sum(const float* input, float* output) {
__shared__ float scratch[threads];
int t = threadIdx.x;
scratch[t] = input[t];
__syncthreads();
for (int distance = threads / 2; distance > 0; distance /= 2) {
if (t < distance) scratch[t] += scratch[t + distance];
__syncthreads();
}
if (t == 0) output[0] = scratch[0];
}sum first copies each input to shared scratch storage. A block barrier makes those writes available before partner reads. Each loop stage adds a partner value, and every thread reaches the following barrier, including threads that skipped the addition.
CUDA C++ · launch inside main()
sum<<<1, threads>>>(input, output);The settings inside <<< >>> give the block count and threads per block. Parentheses pass the arguments to the kernel. These read-only excerpts show the starter. The CUDA source editor contains the storage and launch settings.
Edit and run CUDA
The CUDA source editor opens with the complete starter or your saved draft. To run the starter again, use Editor tools → Restore starter. Choose Undo restore there to recover the previous draft.
Click Compile and run with the starter. Find Sum in Console. The starter adds the four values 1.0 through 4.0.
Change the source
In the CUDA source editor, above sum, change threads from 4 to 8. Predict Sum for inputs 1.0 through 8.0, then run again and check Sum in Console. In the kernel, find the barrier that separates one stage’s writes from the next stage’s partner reads.
Read the starter’s execution diagram
- Write inputsEach thread writes one shared array element.
- Block barrierAll threads arrive before any partner read.
- Read and addSelected threads write partial sums.
- Block barrierAll threads arrive before the next stage reads.
The threads that skipped the addition still reach the second barrier.
Hardware context
Shared memory is part of the SM, but each block has a separate allocation. Every thread in this kernel reaches each block barrier, including threads that skip the addition. Those barriers do not synchronise other blocks on this SM or elsewhere.
Read the hardware key
- Resident warp
- A warp has 32 lane positions; a small block can leave some unused. A resident warp has its state and required resources allocated on an SM. Its next instruction may still be waiting for data.
- Instruction
- One operation run by GPU hardware, such as a load, multiply or store.
- Warp scheduler
- Selects ready warp instructions for available execution hardware.
- Registers
- Hold working values associated with individual threads.
- Execution units
- Perform arithmetic and other instructions for threads; they are shared hardware.
- Load/store units
- Execute memory instructions, forming requests from active lanes’ addresses.
- L1 / L2 cache
- Keep recently used data on the GPU chip. L1 is local to an SM; L2 is shared across SMs in this simplified view.
- Shared memory
- SM-local storage allocated to blocks for explicit data exchange. It may share physical storage with L1, depending on the GPU.
CPU side · CUDA host
Host ↔ device · copies move data; launches request execution
GPU device
GPU compute chip
SM · streaming multiprocessor
Logical groups using this SM’s resources
Issue to the appropriate units
Registers ↔ execution units · operands and results
Have their own execution hardware and registers.
Blocks may be assigned to different SMs.
Global-memory requests ↔ on-chip interconnect
Chip ↔ device memory · data transfers
Simplified NVIDIA-style architecture. Boundaries show containment; arrows name relationships. Unit counts, block placement and timing vary by GPU. A thread or warp is not a dedicated physical processor.
Explore the model: shared reduction stages
Predict and run
Try it
Select Four threads and click Run model. Use Next step to pass the initial barrier and inspect the partner reads. Select Eight threads, predict how many threads add in the first stage, then run again. Use Inputs in current partial to track which original values each sum includes.
These controls change only this model and its displayed excerpt; they do not edit the CUDA program above. Enter a prediction to compare with the model result.
CUDA C++ excerpt
// Launch one block of 4 threads with 4 input values.
__global__ void sum(const float* input, float* out) {
__shared__ float scratch[4];
int t = threadIdx.x;
scratch[t] = input[t];
__syncthreads();
for (int d = blockDim.x / 2; d > 0; d /= 2) {
if (t < d) scratch[t] += scratch[t + d];
__syncthreads();
}
if (t == 0) out[0] = scratch[0];
}At distance d, thread t reads its partner at scratch[t + d] and adds that value to scratch[t]. Only threads t < d add. The barrier is outside that condition so every thread reaches it.
Apply what you saw
For eight inputs, which original indices have contributed to scratch[0] after the distance-2 stage?
Compare your explanation
Indices 0, 4, 2 and 6. The distance-4 stage pairs 0 with 4 and 2 with 6. The distance-2 stage combines the two pairs.
Connect shared writes to safe partner reads 1 min 48 sec · Video walkthrough, captions and transcript
Use fullscreen to inspect the code and diagram labels.
Read the transcript
Eight values must become one sum
The block begins with values one through eight. The required total is thirty-six point zero. The important GPU question is how one thread can safely use values produced by other threads.
The block owns a shared workspace
Each thread writes its input into shared memory on the SM. This workspace belongs to this block. A thread’s own working value and the block’s shared array have different ownership.
Complete writes before partner reads
All eight block threads reach the initial block barrier. A following partner read can then use the completed shared writes. The barrier does not synchronise an unrelated block on this or another SM.
Only part of the block adds at a stage
At partner distance four, threads zero through three add the upper four values into the lower four positions. The next stage must use these completed partial sums, so every block thread reaches the following barrier.
The reduction narrows to one addition
The next partner stage leaves two partial sums: sixteen point zero and twenty point zero. Thread zero adds them to form thirty-six point zero. Fewer adding threads does not change the block’s matching barrier participants.
One adds; how many arrive?
Only thread zero performs the final addition. None of the eight threads has exited the kernel. Pause and predict how many threads must reach the matching block barrier. Can the other seven simply skip it?
All eight still participate
All eight must reach the matching barrier. The arithmetic condition selects who adds; it does not remove the other threads from the collective. The safe sequence is shared writes, a block barrier, then dependent reads. That relationship remains true as the reduction narrows.
References shared memory · synchronisation functions
The browser exercises need no installed CUDA documentation version. For local execution, use the documentation matching your toolkit. External references need internet access.
- CUDA · shared memory (new tab)
Ordinary __shared__ arrays belong to one block. Order shared writes before dependent reads with the appropriate barrier.
Two blocks run on the same SM. May one treat the other block’s ordinary __shared__ array as its own?
Compare your answer
No. Ordinary shared arrays have block scope. Sharing an SM does not merge their shared-memory allocations; cross-block cooperation needs an appropriate supported mechanism.
- CUDA · synchronisation functions (new tab)
__syncthreads() is a block barrier. Keep its participation uniform across the block.
Only two of four threads read shared values. Should the other two skip a block barrier before those reads?
Compare your answer
No. Keep the block barrier collective. A condition around __syncthreads must be uniform across the block; the conditional consumers belong after the barrier.
Further GPU investigation Run this CUDA example on an NVIDIA GPU
In the CUDA source editor, open Editor tools and choose Export .cu to save the complete program. Use an NVIDIA GPU and a matching CUDA toolkit to run it outside the browser.
Browser simulation checks program behaviour; physical GPU timing requires a hardware measurement.
Enable JavaScript to save completion.