CUDA C++ LabGPU architecture

Build and verify a stable softmax

Implement a row-wise kernel, check additional shapes and propose a bottleneck to test on a GPU.

Softmax turns each row of attention scores into non-negative weights that sum to one. Build a row-wise CUDA implementation and use independent references to decide whether it is ready to measure.

PyTorch

import torch
logits = torch.tensor([
    [-2.0, 0.0, 1.0],
    [1000.0, 1002.0, 1003.0],
])
y = torch.softmax(logits, dim=1)
print(y)

dim=1 normalises across the columns of each row. Adding a large constant to a row should not change its mathematical weights. torch.softmax supplies an independent framework baseline; it does not promise our one-block-per-row algorithm.

Download the complete PyTorch example

Definitions

Logit
An input score before softmax turns the row into weights.
Stable softmax
Compute exp(x − row maximum) and divide by their row sum, avoiding overflow for large positive logits.
Row reduction
Combine all columns of one row into a maximum or sum.

Establish the calculation first

For [0.0, 1.0], subtract the maximum 1.0 to obtain [−1.0, 0.0]. The exponential weights are approximately [0.367879, 1.0]; divide by their sum 1.367879 to obtain [0.268941, 0.731059]. Applying the same rule to [1000.0, 1001.0] gives the same result without evaluating exp(1001.0).

Use one block of 32 threads per row. Each thread visits columns t, t + 32, … . First reduce per-thread maxima in shared memory, then accumulate shifted exponentials and reduce their sum. Finally revisit columns to write normalised weights. Each thread starts its maximum at -3.402823466e38f, the lowest finite FP32 value, and its sum at 0.0. Threads with no columns keep those initial values, so they do not change the block maximum or sum. Every lane still reaches each block barrier. Protect shared scratch before reuse.

Your implementation contract

Implement rowSoftmax(input, output, cols) for a row-major FP32 matrix. The host supplies a positive column count and launches one 32-thread block for each row. This browser exercise accepts finite logits, 1–128 rows, a positive column count and at most 8192 elements; it does not define empty rows, infinities or NaNs. Production kernels need an explicit policy for those cases. The 128-row limit keeps the 32-thread blocks within this browser simulator’s 4096-thread launch budget; it is not a CUDA hardware limit.

The starter writes zero for every output. Its complete CPU reference compares those outputs and reports mismatches. You will replace the body of rowSoftmax in the CUDA source editor after running the unchanged starter. Keep allocation, copying, the serial CPU reference, full-output comparisons and row-sum checks. A row sum alone cannot detect a permutation.

The 32-thread launch is part of this reference contract. Changing it requires changing the shared reductions and identities too. Faster alternatives are an investigation, not a requirement to copy a production implementation.

Execution relationships · order, not measured duration
  1. Row maximumCombine per-thread maxima with collective barriers.
  2. Shifted sumAccumulate exp(x − max) and combine all columns.
  3. NormaliseWrite each column once; compare all outputs independently.

Implement and verify the kernel

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 rowSoftmax(const float* input, float* output, int cols) {
    int t = threadIdx.x, row = blockIdx.x;
    // Implement the row maximum, shifted exponential sum and normalisation.
    // All threads must participate in the shared reductions.
    // The untouched scaffold writes zero and deliberately fails verification.
    for (int col = t; col < cols; col += 32)
        output[row * cols + col] = 0.0f;
}
// END SOFTMAX KERNEL

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. Console reports Mismatch at index and a nonzero mismatch count because rowSoftmax writes zero. The compiler and simulator can run this intentionally incomplete program. Replace the body of rowSoftmax with the three passes described above. Click Compile and run again and find mismatches: 0, the counts of checked values and row sums, and the output values in Row 0. Then change rows, columns and shift above rowSoftmax for the cases in Test new shapes and inputs below. Which shapes require a thread to visit more than one column?

Download this CUDA starter

Test new shapes and inputs

  1. Start with 1 row × 1 column and 2 × 7. Check every value.
  2. Use 3 × 31, 3 × 33 and 5 × 65 to exercise inactive lanes and repeated visits.
  3. Above rowSoftmax, change shift from 1000.0f to 0.0f and rerun. For equal logits, replace the input[i] assignment in main() with input[i] = shift; and rerun. Explain shift invariance and the uniform-row result.
  4. Before looking at the reference solution, write down your ownership, barrier and tail reasoning. Use the supplied CPU checks for every shape. For another independent comparison, follow Check an additional softmax row below and paste Row 0 from the same explicit logits. Verify those results before measuring a larger native shape.
Check an additional softmax row

Check a row from your implementation

Choose a Reference row. Run your implementation on those displayed logits, then paste its output values and click Check my row. Compare Your value with Stable reference for each Column. This checker uses a different dataset from the editor’s default generated inputs.

To test the first Reference row using the CUDA editor, set rows = 1 and columns = 3 above rowSoftmax. Before the input loop in main(), add const float test[] = {-2.0f, 0.0f, 1.0f}; and replace the input[i] assignment with input[i] = test[i];. Click Compile and run, then copy the values after Row 0 in Console into this checker. For another Reference row, replace test[] with that row’s logits and set columns to the number of entries.

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

Paste output values for the selected Reference row, then click Check my row.

Hardware context

Thread working maxima and sums use registers; a block’s shared scratch exchanges partial reductions. The output and input live in device memory. One block owns a row, so no cross-block barrier is needed for that row.

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

Your kernel passes a 32-column row but fails at 33 columns. What should your explanation and evidence cover?

Compare your explanation

Check that each thread revisits columns with stride 32, that both reductions include every visited column and neutral contributions from inactive lanes, and that output normalisation visits the same columns. Compare every value with the CPU reference and retain the failing shape; a row sum of one is insufficient.

Explain and extend your result

Record the tested shapes, maximum absolute/relative error policy, row-sum checks, failing cases and fixes. Explain which lane owns column 64, why every barrier is collective, and what limits your implementation. For a native performance investigation, report GPU/toolkit, warm-up, timing boundary and repeated samples; use the measurement lesson to organise the experiment. State one bottleneck hypothesis and the profiler evidence that could reject it.

Reference solution · compare after your own attempt

This readable reference prioritises correctness and supports the same positive shapes. It makes no performance claim. Opening it does not replace your editor draft.

CUDA C++ · complete reference and CPU verifier

// Copyright © 2026 Christopher Snow.
#include <cuda_runtime.h>
#include <cstdio>
#include <cstdlib>

void check(cudaError_t status) {
    if (status != cudaSuccess) {
        std::fprintf(stderr, "%s\n", cudaGetErrorString(status));
        std::exit(EXIT_FAILURE);
    }
}

bool closeEnough(float actual, float expected) {
    if ((actual - actual) != 0.0f) return false;
    float error = actual - expected;
    if (error < 0.0f) error = -error;
    float scale = expected < 0.0f ? -expected : expected;
    return error <= 0.00001f + 0.0001f * scale;
}

#include <cmath>
constexpr int rows = 3;
constexpr int columns = 33;
constexpr float shift = 1000.0f;
static_assert(rows > 0 && rows <= 128 && columns > 0 && rows * columns <= 8192,
    "Browser exercise: 1-128 rows, positive columns, at most 8192 elements.");

// BEGIN SOFTMAX KERNEL
__global__ void rowSoftmax(const float* input, float* output, int cols) {
    __shared__ float scratch[32];
    int t = threadIdx.x, row = blockIdx.x;
    float maximum = -3.402823466e38f;
    for (int col = t; col < cols; col += 32) {
        float value = input[row * cols + col];
        if (value > maximum) maximum = value;
    }
    scratch[t] = maximum;
    __syncthreads();
    for (int distance = 16; distance > 0; distance /= 2) {
        if (t < distance && scratch[t + distance] > scratch[t])
            scratch[t] = scratch[t + distance];
        __syncthreads();
    }
    maximum = scratch[0];
    __syncthreads(); // Finish maximum reads before reusing scratch.
    float total = 0.0f;
    for (int col = t; col < cols; col += 32)
        total += expf(input[row * cols + col] - maximum);
    scratch[t] = total;
    __syncthreads();
    for (int distance = 16; distance > 0; distance /= 2) {
        if (t < distance) scratch[t] += scratch[t + distance];
        __syncthreads();
    }
    float denominator = scratch[0];
    for (int col = t; col < cols; col += 32)
        output[row * cols + col] = expf(input[row * cols + col] - maximum) / denominator;
}
// END SOFTMAX KERNEL

int main() {
    constexpr int count = rows * columns;
    float input[count], actual[count], expected[count];
    volatile float zero = 0.0f;
    for (int i = 0; i < count; ++i) {
        input[i] = shift + static_cast<float>((i * 7 + i / columns) % 17 - 8) * 0.25f;
        actual[i] = zero / zero;
    }
    // Independent serial CPU reference; all inputs are finite FP32 values.
    for (int row = 0; row < rows; ++row) {
        float maximum = input[row * columns], total = 0.0f;
        for (int col = 1; col < columns; ++col)
            if (input[row * columns + col] > maximum) maximum = input[row * columns + col];
        for (int col = 0; col < columns; ++col) {
            expected[row * columns + col] = expf(input[row * columns + col] - maximum);
            total += expected[row * columns + col];
        }
        for (int col = 0; col < columns; ++col) expected[row * columns + col] /= total;
    }
    float *x, *y;
    check(cudaMalloc(&x, sizeof(input))); check(cudaMalloc(&y, sizeof(actual)));
    check(cudaMemcpy(x, input, sizeof(input), cudaMemcpyHostToDevice));
    check(cudaMemcpy(y, actual, sizeof(actual), cudaMemcpyHostToDevice));
    rowSoftmax<<<rows, 32>>>(x, y, columns);
    check(cudaGetLastError());
    check(cudaMemcpy(actual, y, sizeof(actual), cudaMemcpyDeviceToHost));
    int errors = 0;
    for (int i = 0; i < count; ++i) {
        if (!closeEnough(actual[i], expected[i])) {
            if (!errors) std::printf("Mismatch at index %d: actual %g, reference %g\n", i, actual[i], expected[i]);
            ++errors;
        }
    }
    for (int row = 0; row < rows; ++row) {
        float sum = 0.0f;
        for (int col = 0; col < columns; ++col) sum += actual[row * columns + col];
        if (!closeEnough(sum, 1.0f)) ++errors;
    }
    std::printf("Checked %d softmax values and %d row sums; mismatches: %d\n", count, rows, errors);
    std::printf("Row 0: ");
    for (int col = 0; col < columns; ++col) std::printf("%s%g", col ? ", " : "", actual[col]);
    std::printf("\n");
    check(cudaFree(x)); check(cudaFree(y));
    return errors ? EXIT_FAILURE : 0;
}

Download the reference solution

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

References PyTorch · softmax · synchronisation functions

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.

  • PyTorch · softmax (new tab)

    Check the dimension and dtype contract.

    For a rows × columns matrix, which dimension normalises each row?

    Compare your answer

    dim=1 combines the columns within each row. Changing the dimension changes the operation.

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