CUDA C++ LabGPU architecture

Carry a prefix across blocks

Combine local scans, block totals and block starts in an ordered GPU pipeline.

A token selection mask needs an exclusive offset for every token. A block-local scan cannot supply the preceding totals from other blocks. Keep the same prefix rule and add a second level.

PyTorch

import torch
flags = (torch.arange(70) % 3 == 0).to(torch.int64)
offsets = torch.cumsum(flags, dim=0) - flags
print(offsets)

flags contains 70 integer selection flags, with one at indices divisible by three. cumsum is inclusive; subtracting each original flag makes the offset exclusive. Its value is the number of selected tokens at earlier indices.

Download the complete PyTorch example

Definitions

Block total
The sum of valid flags in one block.
Block start
The exclusive sum of all earlier block totals.

Connect the local scans

Each 32-thread block scans its flags in shared memory. Invalid tail positions contribute zero and still reach every barrier. The first launch writes local exclusive offsets and one total per block. A second launch scans those totals. A third adds the corresponding block start to every valid local offset.

For 70 flags there are three blocks. Their valid counts are 32, 32 and 6; their totals are 11, 11 and 2. Block starts are 0, 11 and 22. A local offset of 0 in block 2 becomes global offset 22.

All three kernels use the same stream, so each consuming phase follows its producer. __syncthreads() orders one block only. Never implement a grid-wide barrier by spinning on other blocks: waiting blocks can occupy all resources needed by their producers.

This runnable construction supports up to 1024 flags: at most 32 block totals fit its one-block second level. For larger inputs, recursively scan totals until the upper level fits, then propagate starts down. A multi-block reduction uses a similar hierarchy of partial sums, but needs only a final total rather than an offset for every element.

Execution relationships · order, not measured duration
  1. Local scansFlags → local offsets + one total per block.
  2. Scan totalsBlock totals → exclusive block starts.
  3. Add startsLocal offsets + block starts → global offsets.

Run the complete CUDA program

The CUDA source editor opens with the starter or your saved draft. To run the starter again, use Editor tools → Restore starter. Use Undo restore there to recover the saved draft. The browser runs the compiled program in a functional GPU simulator. Console shows the independent CPU checks printed by main().

Read-only CUDA C++ · starter excerpt

__global__ void localScan(const int* flags, int* offsets, int* totals, int n) {
    __shared__ int values[32];
    int t = threadIdx.x, i = blockIdx.x * 32 + t;
    int flag = i < n ? flags[i] : 0;
    values[t] = flag;
    __syncthreads();
    for (int distance = 1; distance < 32; distance *= 2) {
        int previous = t >= distance ? values[t - distance] : 0;
        __syncthreads();
        values[t] += previous;
        __syncthreads();
    }
    if (i < n) offsets[i] = values[t] - flag;
    if (t == 31) totals[blockIdx.x] = values[t];
}

CUDA C++ · ordered launches inside main()

localScan<<<blocks, 32>>>(input, offsets, totals, count);
scanTotals<<<1, 32>>>(totals, starts, blocks);
addStarts<<<blocks, 32>>>(offsets, starts, count);

The read-only excerpt shows the starter kernel. main() supplies array sizes, launches the kernel, copies the results back and checks them against a CPU calculation.

Try it

Click Compile and run with count = 70. In Console, find the checked exclusive offsets, blocks, total and mismatches. The starter checks every offset against an independent sum. Above localScan in the CUDA source editor, change count to 0, 31, 33, 65 and 1024, running after each edit. The program checks every offset automatically. For count = 0, Console reports Empty scan and confirms that no allocation or launch occurs. To inspect block starts, open Explore cross-block offsets and try Flag count = 97.

Download this CUDA starter

Explore cross-block offsets

Combine block starts and local offsets

Set Flag count to 97 and predict the last block’s start, then click Run model. In Cross-block prefix construction, compare Total and Start. Use Global offsets to check how a block start contributes to its first valid output. For zero flags, predict 0; no block is launched.

These controls change only this practice tool. They do not edit or run the CUDA program above.

Enter a block-start prediction, then click Run model.

Hardware context

Each SM provides block-local shared scratch storage. Device-memory totals carry results between ordered kernel launches across SMs. No assumption about simultaneous block residency is needed.

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.
Computer / system · inside one SM

CPU side · CUDA host

CPUmain() and CUDA calls.
System RAMCPU memory for arrays.

GPU device

GPU compute chip

SM · streaming multiprocessor
Assigned blocks → resident warps → threads
Logical groups using this SM’s resources
Warp schedulersReady warp instructions.
RegistersThread working values.
Execution unitsShared arithmetic hardware.
Tensor coresSupported matrix multiply-accumulate instructions.
Load/store unitsMemory instructions and addresses.
L1 cacheRecently used data.
Shared memory · banksThis lessonPer-block data exchange.
Other SMs

Have their own execution hardware and registers.

Blocks may be assigned to different SMs.

Shared L2 cacheData cached for multiple SMs.
Copy enginesTransfer data independently of SM arithmetic when supported.
Device memoryGPU arrays; separate from the compute chip.

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.

Apply what you found

If all 65 flags are zero, what should every offset, block total and block start be? Which phases can the host skip for an empty input?

Compare your explanation

Every offset, total and start is zero. Padding also contributes zero. For an empty input the host skips allocation and all three launches. For a nonempty all-zero input it still needs the phases unless it knows the data independently.

For toolkit installation and optional local execution, use desktop CUDA setup. The browser examples have been checked in functional simulation.

References synchronisation functions · streams

External references open in a new tab and need internet access. Browser activities have no installed toolkit version; match documentation to your toolkit for native execution.

  • 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 · streams (new tab)

    Operations in one stream are ordered. Separate streams need an explicit dependency when one consumes the other’s output.

    A producer and consumer use separate streams. Does their order in CPU source alone establish the GPU dependency?

    Compare your answer

    No. Use a supported dependency such as a recorded event and a stream wait. Operations in the same stream are ordered; independent streams need the required cross-stream ordering.

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.

GPU setup and tools

Browser simulation checks program behaviour; physical GPU timing requires a hardware measurement.

Enable JavaScript to save completion.

App status

Course status

Checking for updates

Version and download details

Downloads include all lessons, recordings, diagrams, examples, browser simulators and the CUDA compiler. Browser storage overhead is additional. External links need internet access.

Running examples outside the browser needs separate PyTorch or CUDA/GPGPU-Sim tools.

Add CUDA C++ Lab to your apps

Use your browser’s install option for an app icon and a separate window. Course status shows whether the course is downloaded and ready to use offline.