Build positions from prefix sums
Step through shared-memory scan stages and convert inclusive totals to exclusive offsets.
Before you run
The eight input flags are 1, 0, 1, 0, 0, 1, 0, 1. A flag is 1 for a selected token and 0 otherwise. A prefix sum counts selected tokens before or through a position. Each stage reads from a completed snapshot of the previous stage.
Definitions
- Inclusive scan
- Each output includes the value at its own position.
- Exclusive scan
- Each output includes only the earlier values.
Read the starter excerpts
Read-only CUDA C++ · scan · starter kernel
__global__ void scan(const int* flags, int* result) {
int t = threadIdx.x;
__shared__ int values[8];
values[t] = flags[t];
for (int step = 1; step < 8; step *= 2) {
__syncthreads();
int previous = t >= step ? values[t - step] : 0;
__syncthreads();
values[t] += previous;
}
result[t] = inclusive ? values[t] : values[t] - flags[t];
}scan stores eight flags in shared values. For each step, all threads finish the old stage, read a partner into previous, and reach another barrier before updating shared storage. Subtracting flags[t] converts the inclusive prefix to an exclusive offset.
CUDA C++ · launch inside main()
scan<<<1, 8>>>(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 Index 5 and index 7 in Console. Both totals include the flag at their own position.
Change the source
In the CUDA source editor, above scan, change inclusive from true to false. Predict Index 5 and index 7, then run again and inspect both fields in Console. Explain why the exclusive value at index 5 omits that position’s own flag.
Read the starter’s execution diagram
- Read old stageKeep the partner value in previous.
- SynchroniseFinish old reads before any thread updates.
- Write new stageAdd the partner; repeat at the next distance.
Conceptual dependencies in this example; placement and timing are not specified.
Hardware context
A shared-memory stage lets a block exchange prefix values. Registers keep the partner value separate while a barrier protects the old shared snapshot. A block barrier does not order a multi-block scan.
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.
- Bank
- A subdivision of shared memory that serves a group of word addresses.
- Tensor cores
- Matrix execution units used by supported warp-wide matrix instructions.
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: prefix stages
Predict and run
Try it
Select Inclusive under Prefix returned by the block and click Run model. Use Next step to follow the staged prefixes. Select Exclusive, predict the completed value at index 5, then run again. Which input flag is omitted from that output?
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
// Body for one block of eight threads; output has 8 slots.
__shared__ int s[8];
int t = threadIdx.x;
s[t] = flags[t];
__syncthreads();
for (int d = 1; d < 8; d *= 2) {
int add = t >= d ? s[t - d] : 0;
__syncthreads();
s[t] += add;
__syncthreads();
}
out[t] = s[t];Every thread copies its partner to a register before any writes for that stage. The second barrier completes those writes before the next stage reads.
Apply what you saw
Where can a thread get the count of all eight flags if it has only the exclusive output and the original flags?
Compare your explanation
Add the final flag to the final exclusive prefix. The last prefix counted all flags except the one at index 7.
Further practice: Extend a prefix across blocks.
Keep old shared state separate from new scan values 1 min 44 sec · Video walkthrough, captions and transcript
Use fullscreen to inspect the code and diagram labels.
Read the transcript
Offsets count earlier selected positions
A scan combines a row of flags into prefixes. An exclusive offset counts selected positions strictly before the current position. The GPU question is how every thread reads the old stage while the block builds a new one.
The shared array is a completed stage
The block’s shared values begin as the eight flags. At each partner distance, a thread needs a value from the preceding stage. Shared memory lets threads exchange values, but it does not automatically keep those values unchanged during the exchange.
Capture the partner in private working state
Each participating thread first captures its old partner value in the private variable previous. All threads then reach a barrier before any thread is allowed to overwrite the old shared stage.
Publish the new stage before reading it
After that barrier, threads update shared storage. Another block barrier completes those writes before the next partner distance begins. The barriers protect two different boundaries: old reads before overwrites, and new writes before later reads.
Can a later barrier protect an earlier read?
Imagine thread one has already replaced its old flag with one, while thread two still needs thread one’s old flag of zero. Pause and predict whether a barrier only after the writes would protect that old value. This is a possible race illustration, not an executed unsafe kernel.
Protect the snapshot before overwriting it
A later barrier cannot restore a value that was already overwritten. Capturing partners first, then collectively ordering the writes, preserves the intended stage. The private working value and the block’s shared array solve different parts of that dependency.
References synchronisation functions · shared memory
The browser exercises need no installed CUDA documentation version. For local execution, use the documentation matching your toolkit. External references need internet access.
- 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.
- 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.
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.