CUDA C++ LabGPU architecture

Process more inputs than the launch has threads

Give each input one owner with a grid-stride loop, including tails and empty inputs.

The elementwise operation still multiplies each input by 2.5. Now the input can be longer than the launch: a small reusable grid should cover every element.

PyTorch

import torch
x = torch.arange(70, dtype=torch.float32)
x = (x.remainder(13) - 6.0) * 0.25
y = x * 2.5
print(y)

remainder(13) repeats a pattern with negative, zero and positive FP32 values. The output has the same length and order. PyTorch chooses a launch internally; the CUDA exercise deliberately fixes two blocks of 32 threads.

Download the complete PyTorch example

Definitions

Grid-stride loop
A loop in which each thread advances by the total thread count in the grid.
Tail
The valid elements left after the last complete group.

How does one thread visit several elements?

The host supplies n as an element count. For two blocks of 32 threads, thread index t visits t, t + 64, t + 128, … while the index stays below n. Adjacent lanes still address adjacent elements on each iteration. Each thread starts at a different index and advances by 64, so their visits do not overlap. With the starter’s 70 inputs, thread 0 visits indices 0 and 64; thread 6 visits index 6 and stops before index 70.

The complete starter supports 0–4096 elements and 1, 2 or 4 blocks of 32 threads. The host returns before allocating or launching when n is zero. That avoids a zero-block launch. The bound checks protect the final partial iteration, not just the first visit.

Execution relationships · order, not measured duration
  1. StartblockIdx.x × blockDim.x + threadIdx.x.
  2. VisitRead input[i], multiply, write output[i].
  3. AdvanceAdd blockDim.x × gridDim.x; repeat only while i < n.

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 scale(const float* input, float* output, int n) {
    int first = blockIdx.x * blockDim.x + threadIdx.x;
    int stride = blockDim.x * gridDim.x;
    for (int i = first; i < n; i += stride) {
        output[i] = input[i] * 2.5f;
    }
}

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 the starter. Compare 70 Checked values with 64 launched threads in Console: why can outputs outnumber threads? Above scale in the CUDA source editor, change count to 129 and predict whether all values will still be covered. Run again to check. For nonempty inputs, Console reports Checked values, launched threads and mismatches; mismatches should be 0. For count = 0, inspect Empty input: no allocation or launch. Next change count to 0, 31 and 33, running after each edit, then try count = 129 with blocks = 1. Use the optional visit model to inspect individual thread indices; the program prints verification totals.

Download this CUDA starter

Explore grid-stride visits

Trace each thread’s visits

Set Input elements to 70 and Blocks to 2. Predict thread 0’s visit count, then click Run model. In Thread visits, inspect the input/output indices for thread 0. Change Blocks from 2 to 1 and predict again: does thread 0 visit more indices?

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

Enter a visit-count prediction, then click Run model.

Hardware context

A fixed grid can reuse resident threads on SMs without assigning one thread for every input element. Lane-adjacent accesses remain grouped. The model calculates index coverage; it does not predict block order or execution time.

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

Apply what you found

For n = 129, does changing from two blocks to one change the mathematical output? What changes for thread 0?

Compare your explanation

The output is unchanged. With 64 launched threads, thread 0 visits 0, 64 and 128. With 32 it visits 0, 32, 64, 96 and 128. The host skips the launch entirely for n = 0.

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

References thread hierarchy · coalesced global-memory access

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

  • CUDA · coalesced global-memory access (new tab)

    Active lanes’ addresses determine the aligned regions requested. Sector counts do not measure device-memory traffic or time.

    If adjacent active lanes read adjacent FP32 values, can a sector count alone establish how many device-memory reads occur?

    Compare your answer

    No. It counts aligned address regions in the stated model. Cache hits and the actual memory-system behaviour determine traffic beyond those requests.

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.