CUDA C++ LabGPU architecture

Investigate stable token routing

Combine counts, starts and ranks to place every token once, then design a performance measurement.

Before you run

A routing stage sends tokens to destinations, such as experts in a model. First count each category to determine its range in the output. Within the range, give each token a rank that preserves its original order.

Definitions

Stable grouping
Members of the same category keep their relative input order.
Category start
The exclusive prefix of the category counts.

Read the starter excerpts

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

int rank = prefix[category][t] - 1;
for (int i = 0; i < category; ++i) start += histogram[i];

positions[start + rank] = t;

route first completes shared-memory scans of the four category masks. In this final body excerpt, subtracting one from the token’s inclusive category prefix gives its stable rank. start sums earlier category counts; start plus rank gives a unique destination. All threads finish the scan barriers before reading prefix, and count precedes route in the same stream.

CUDA C++ · launch inside main()

count<<<1, 8>>>(input, histogram);
route<<<1, 8>>>(input, histogram, positions);

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 the eight Slot lines in Console. Each slot gives the ID of the token routed there.

Change the source

In the CUDA source editor, above count, change hot from false to true. With hot = true, every token selects category 0. Predict which token appears in Slot 1, then click Compile and run again. Inspect all Slot lines in Console: are tokens with the same destination still ordered by their original IDs?

Read the starter’s execution diagram

Follow the starter’s execution
  1. Count categoriesBuild counts before routing starts.
  2. Find start and rankCombine the category region and local order.
  3. Write token IDGive each token a unique stable slot.

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

Hardware context

Device-memory phase results connect counting to placement. Atomics can count safely, but the order of atomic arrivals alone does not preserve token order. The explicit earlier-token rank supplies stability.

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 unitsThis lessonMemory instructions and addresses.
L1 cacheRecently used data.
Shared memory · banksPer-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.

Explore the model: stable destination ranks

Predict and run

Try it

Select Mixed categories and click Run model. Use Next step until token 4 is placed in the grouped output. Select All tokens in category 0, predict token 4’s new output index, then rerun. Check the order of token IDs inside each category’s output range.

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

// Host categories: 0, 1, 0, 2, 1, 0, 3, 0.
// Earlier stages compute counts, starts and stable ranks.
// Scatter kernel (each thread i owns token i):
int bin = category[i];
int destination = start[bin] + rank[i];
grouped[destination] = i;

The rank is the number of earlier input tokens in the same category. A global atomic increment alone can allocate unique ranks but does not guarantee input order.

Optionally enter a prediction, then click Run model.

Apply what you saw

Design separate GPU measurements for a count-only pipeline and a stable-grouping pipeline. Which application needs only category totals, and which needs token IDs in stable order? What would you validate and report for each output contract?

Compare your explanation

Check category totals for both. For grouping, also check unique destinations and the order within each category. For a native measurement, time every required stage on identical mixed and skewed inputs and report the GPU, launch sizes and input sizes. Counting and grouping produce different outputs, so their time ratio is not a speedup between interchangeable implementations.

Connect category counts to stable token addresses 2 min 1 sec · Video walkthrough, captions and transcript

Use fullscreen to inspect the code and diagram labels.

Read the transcript

Counts describe sizes, not token order

The eight tokens choose four categories. The counts tell us the size of each output region. They do not by themselves say where each token ID belongs within its category.

Completed counts choose each region’s start

The count kernel finishes before the route kernel begins in the same stream. Device-memory counts therefore supply the region sizes before placement. Exclusive category starts identify where each category’s output region begins.

A prefix rank identifies earlier matching tokens

Token five belongs to category zero. Two earlier tokens have that category, so its within-category rank is two. The route kernel’s completed shared prefix stages supply this rank before the scatter write.

Start plus rank forms a unique destination

A category’s start plus the token’s earlier-match rank gives the destination. Token five therefore writes output position two. The SM performs this address calculation; GPU memory holds the category regions and their stored token IDs.

Token seven executes its write first

Token seven also belongs to category zero. Suppose its write is inspected before the other category-zero writes. Pause and predict whether it should take position zero or retain the destination determined by its earlier-match rank.

Its stable rank still chooses position three

Token seven has three earlier matching tokens, so it retains position three even if its write happens first. Atomic arrival tickets can make updates unique without preserving input order. Stable grouping needs the explicit prefix rank used here.

The grouped IDs preserve order within each category

The completed grouping places zero, two, five and seven in the first region, followed by one and four, then three, then six. Choose the required output contract first: counts need safe additions; stable token grouping also needs ordered ranks and distinct destinations.

References atomic functions · streams

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