CUDA C++ LabGPU architecture

Count token destinations safely

Trace competing updates and compare global atomics with per-block partial counts.

Before you run

Eight tokens each name one of four destinations. Two blocks of four threads count the tokens. Several threads may increment the same counter. An atomic addition makes each increment contribute once.

Definitions

Histogram
A count for each destination.
Atomic addition
A read, addition and write that acts as one update to the target counter.

Read the starter excerpts

Read-only CUDA C++ · histogram · kernel body excerpt

    __shared__ int partial[4];
    partial[t] = 0;
    __syncthreads();
    atomicAdd(&partial[category], 1);
    __syncthreads();
    if (partial[t]) atomicAdd(&counts[t], partial[t]);

Inside histogram, partial holds four counters shared by one four-thread block. Each thread clears one counter; a barrier precedes atomic updates. A second barrier completes those updates before nonzero partials are added to the global counts. main initialises global counts to zero.

CUDA C++ · launch inside main()

histogram<<<2, 4>>>(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 Counts in Console. They give the number of tokens in each of the four destinations.

Change the source

In main() in the CUDA source editor, replace the eight entries of categories with zeroes. Predict Counts, then run again and read Counts in Console. Next change blockCounts from true to false above histogram and rerun: should switching from per-block partial counters to direct global updates change the four bin totals?

Read the starter’s execution diagram

Follow the starter’s execution
  1. Initialise countersClear shared and global counts.
  2. Count atomicallySeveral threads may target the same category.
  3. Merge partialsAdd completed per-block counts globally.

Conceptual dependencies in this example; placement and timing are not specified.

Hardware context

Per-block shared counters combine local contributions before a merge to device-memory counters. An atomic update protects one supported update; it does not replace the block barriers around initialisation and merging.

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.
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.

Explore the model: atomic counter updates

Predict and run

Try it

Select Global counters, predict global atomic additions and click Run model. Repeat with Separate block counters. Follow the updates in the trace: which categories still receive a global addition from both blocks?

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

// One thread per token. All global counts start at 0.
int i = blockIdx.x * 4 + threadIdx.x;
atomicAdd(&counts[category[i]], 1);

The input category IDs in order are 0, 1, 0, 2, 1, 0, 3, 0. In the block variant each thread first zeroes one counter, counts its assigned token, then may merge one non-zero partial.

Optionally enter a prediction, then click Run model.

Apply what you saw

If every token has category 0, how many global additions does the block-private version make?

Compare your explanation

Two. Each of the two blocks sends one non-zero partial for category 0.

Follow local counts into global counters 1 min 46 sec · Video walkthrough, captions and transcript

Use fullscreen to inspect the code and diagram labels.

Read the transcript

Several threads can target one counter

The eight token categories include four zeros. Several threads therefore update the same category-zero count. An atomic addition makes one supported update indivisible. It does not make the block’s other operations a collective barrier.

Each block has its own shared counters

With local aggregation, each block clears its own four-counter shared array on its SM. All four threads arrive at a barrier before those counters are used. The blocks’ shared arrays remain separate.

Local contributions are combined before merging

Threads make their atomic contributions to the block’s shared counters. A following block barrier completes this counting phase before the merge. Only nonzero partial counters need a global atomic merge in this example.

Read both kinds of operation count

Direct global counting makes eight global atomic additions. Local aggregation makes eight shared atomic additions and six global merges for these inputs. That changes where operations occur. Extra local work and synchronisation still matter, so these counts are not a speed measurement.

Every token chooses category zero

Now consider a hot category: all eight tokens choose zero. Pause and predict the number of nonzero block partials that must merge globally. Each of the two blocks still has its own shared workspace.

Two completed partials reach the global counter

Each block contributes one nonzero category-zero partial, so the model needs two global merges. The final count is eight. Shared aggregation combines local contributions; atomic operations protect updates; barriers protect the phase boundaries. Those are separate responsibilities.

References atomic functions · 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 · atomic functions (new tab)

    atomicAdd updates one location indivisibly at its supported scope; it does not make a block arrive at a barrier.

    Does atomicAdd to a counter also make all threads arrive at a block barrier?

    Compare your answer

    No. The counter update is indivisible at its supported scope. Barriers still order shared initialisation, completed updates and consumers.

  • 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.

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.