CUDA C++ LabGPU architecture

Check every GPU result

Compare every output with a CPU reference, then diagnose a safe indexing error.

AI kernels must produce the right values before their speed is useful. This matrix product gives each row and column different data, so an indexing error changes the answer.

PyTorch

import torch
a = torch.tensor([[1.0, 2.0], [3.0, 5.0]])
b = torch.tensor([[2.0, 0.0], [1.0, 4.0]])
y = a @ b
print(y)

a and b contain FP32 values; @ computes a matrix product. The expected output is [[4.0, 8.0], [11.0, 20.0]]. PyTorch chooses its implementation. Our CUDA exercise below uses a simpler elementwise operation so you can isolate the checking workflow.

Download the complete PyTorch example

Definitions

CPU reference
An independent, straightforward calculation used to check the GPU result.
Tolerance
The allowed numerical difference between a result and its reference.
NaN
A floating-point “not a number” value; here it marks output that was never written.

What counts as a passing result?

Compare every element, its shape and its order. Reject non-finite values before checking abs(actual − expected) ≤ atol + rtol × abs(expected). This lesson uses absolute tolerance 1e-5 and relative tolerance 1e-4 for FP32. Here atol names the absolute tolerance and rtol the relative tolerance. These are example choices: choose tolerances from the operation, input scale and numerical requirements. For a reference value of 20.0, that bound is 0.00201: an absolute error of 0.001 passes, while 0.003 fails. Reject non-finite values even if another element passes. Integer offsets should match exactly.

All-one matrices can hide a transpose mistake. Distinct rows and columns expose it. Include negative values, zeros, lengths around block boundaries and empty input. Fill output with NaN before execution so unwritten locations fail visibly.

Execution relationships · order, not measured duration
  1. InitialiseDifferent input values; output filled with NaN.
  2. ExecuteCheck launch errors, then complete the device-to-host copy.
  3. VerifyCompare all 33 values against an independent CPU loop.

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 transform(const float* input, float* output, int n) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) {
        int source = correctIndex ? i : (i + 1) % n;
        output[i] = input[source] * 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. In Console, find Checked 33 values and mismatches: 0. In the CUDA source editor, change correctIndex from true to false above transform. Predict the first mismatching index, then click Compile and run. In Console, inspect Mismatch at index, actual, reference and mismatches. Restore correctIndex to true and run again: this tests the numerical comparison, not a compilation error.

Download this CUDA starter

Use Compute Sanitizer (requires a GPU)

Diagnose native execution errors

After repairing the safe indexing error, use Compute Sanitizer on a native CUDA build. memcheck detects invalid/misaligned accesses; racecheck targets shared-memory hazards; synccheck checks synchronisation misuse. These tools complement numerical comparison and do not prove the algorithm correct.

Shell · native CUDA debugging

nvcc -O2 -lineinfo verify-every-output.cu -o verify
compute-sanitizer --tool memcheck ./verify
compute-sanitizer --tool racecheck ./verify
compute-sanitizer --tool synccheck ./verify

Use a small reproducible failing input, read the first diagnostic and recheck the repaired program. These tools require a supported NVIDIA GPU and are not run by the browser.

Explore verification cases

Test a candidate result

The page calculates the candidate for your selected Matrix inputs and Candidate result. Click Run model and inspect Candidate, CPU reference and Check. Select Right matrix transposed by mistake under Candidate result. Run with All ones, then with Nonuniform rows and columns under Matrix inputs: which dataset exposes the error?

Matrix A: [1.0, 2.0, 3.0, 5.0]; Matrix B: [2.0, 0.0, 1.0, 4.0]. Each list stores two rows of two values.

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

Choose Matrix inputs and Candidate result, then click Run model.

Hardware context

The CPU creates the independent reference and compares copied results. An immediate cudaGetLastError checks a launch; asynchronous execution errors can appear at the blocking copy or a synchronisation call. The example checks both calls.

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

CPUThis lessonmain() 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 · 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

The all-one transpose case passes. What additional test would make that check useful?

Compare your explanation

Use nonuniform rows and columns, compute a separate CPU reference and compare every element. Passing a convenient input establishes only that input; a sanitizer also cannot prove the mathematical answer.

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

References Compute Sanitizer · explicit memory management

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.

  • Compute Sanitizer (new tab)

    Check memory errors separately from numerical correctness.

    Can memcheck prove that a safely indexed transpose is the intended matrix product?

    Compare your answer

    No. It can detect memory access violations; independent full-output comparison checks the mathematical result.

  • CUDA · explicit memory management (new tab)

    An FP32 value occupies four bytes. Allocation reserves storage; a separate copy supplies its contents.

    Seven FP32 values need how many bytes? Does allocating those bytes also copy the CPU inputs?

    Compare your answer

    Seven four-byte values need 28 bytes. Allocation reserves storage; a separate copy or other initialisation supplies its contents.

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.