Pack surviving tokens in order
Use selection flags and exclusive offsets to explain each surviving token’s write destination.
Before you run
The starter supplies category IDs 0, 1, 0, 2, 1, 0, 3, 0 for token IDs 0–7. The selection rule keeps tokens whose category equals keepCategory. A kept token has flag 1; a dropped token has flag 0. Exclusive prefixes count earlier kept tokens. Each surviving thread uses its prefix as an output offset.
Definitions
- Compaction
- Pack selected inputs into consecutive positions.
- Scatter
- Write each item to its computed destination.
Read the starter excerpts
Read-only CUDA C++ · scatter · starter kernel
__global__ void scatter(const int* flags, const int* offsets, int* output) {
int t = threadIdx.x;
if (flags[t]) output[offsets[t]] = t;
}flag marks selected categories. scanFlags forms exclusive offsets using staged shared-memory scans and collective barriers. scatter writes original token IDs at those unique offsets. All three kernels are ordered in one stream; main verifies the complete stable result.
A CUDA stream is an ordered queue of operations. These three launches use the same default stream: scanFlags reads the completed flags from flag, and scatter reads the completed offsets from scanFlags. Lesson 20 explores dependencies between different streams.
CUDA C++ · launch inside main()
flag<<<1, 8>>>(input, flags);
scanFlags<<<1, 8>>>(flags, offsets);
scatter<<<1, 8>>>(flags, offsets, 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 the Kept token lines in Console. The starter writes the tokens from category 0 in input order.
Change the source
In the CUDA source editor, above flag, change keepCategory from 0 to 1. Predict the token IDs that survive, then run again. Read the Kept token lines in Console and check that IDs remain in their original input order.
Read the starter’s execution diagram
- Flag tokensRecord whether each token survives.
- Scan flagsForm exclusive offsets with shared stages.
- Scatter IDsWrite each selected token once.
Conceptual dependencies in this example; placement and timing are not specified.
Hardware context
Flags produced in device memory must be ready before scatter consumes them. Unique offsets give selected threads distinct destinations. Stable output order follows the offsets, not the order in which warps happen to run.
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: stable write offsets
Predict and run
Try it
Select Keep category 0 and predict the output offset of the last kept token. Click Run model and inspect the reverse write order. Select Keep categories 1–3 and predict again before rerunning. For Keep no tokens, enter −1 because no thread writes an 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
// First kernel, one thread per input token.
flags[i] = category[i] == 0;
// An exclusive scan of flags produces offset.
// After the scan, in the scatter kernel:
if (flags[i]) packed[offset[i]] = i;The category IDs are 0, 1, 0, 2, 1, 0, 3, 0. The packed array has capacity for all eight inputs. Its used prefix contains original token positions. The model visits writes in reverse order to expose stability.
Apply what you saw
Could a dropped token and a kept token have the same exclusive offset? Why is the scatter still safe?
Compare your explanation
Yes. A dropped token does not increase the prefix and never writes. Each kept token increases the running count once, so its write offset is unique.
See why output order can survive unordered writes 1 min 39 sec · Video walkthrough, captions and transcript
Use fullscreen to inspect the code and diagram labels.
Read the transcript
Keep selected tokens in input order
For category zero, the selected input token IDs are zero, two, five and seven. Their threads need unique output positions even if the GPU does not execute those threads in input order.
Completed phases communicate through device memory
The flag kernel writes selection flags. The scan kernel uses completed flags to produce offsets, and scatter uses completed offsets. The launches use one ordered stream. A block barrier is not the mechanism that orders these separate kernel phases.
An offset supplies a destination
Token five has two earlier selected tokens, so its exclusive offset is two. Its scatter writes token ID five into output position two. The address comes from the completed prefix, not from arrival order.
Let token seven write first
Pause and predict the destination if token seven’s write is inspected before token zero’s. Does writing first give token seven output position zero?
Its offset still sends it to position three
Token seven writes position three because three selected tokens precede it in the input. The model inspects writes in reverse order and still produces token IDs zero, two, five and seven in the completed output.
Ordering data and ordering execution are different
Stream dependencies make flags and offsets ready before scatter. Prefix offsets determine the stable destination of each survivor. The SMs may execute independent writes in different orders; the completed output’s order follows the address calculation.
References streams · thread hierarchy
The browser exercises need no installed CUDA documentation version. For local execution, use the documentation matching your toolkit. External references need internet access.
- 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.
- CUDA · thread hierarchy (new tab)
For a one-dimensional launch, i = blockIdx.x * blockDim.x + threadIdx.x.
Block 2 contains four threads. Which global index belongs to its local thread 1?
Compare your answer
The one-dimensional expression gives 2 × 4 + 1 = 9. Whether index 9 accesses data depends on the element count and bounds guard.
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.