CUDA C++ LabGPU architecture

One thread, one element

Change a CUDA multiplier and follow each input to its output.

Before you run

The starter supplies five input values. Each thread reads one input and writes the multiplied value to the same index in the output array.

Definition

FP32
A floating-point value stored in four bytes.

Read the starter excerpts

Read-only CUDA C++ · runKernel · starter kernel

__global__ void runKernel(
    const float* input, float* output, int n
) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) {
        output[i] = input[i] * 2.0f;
    }
}

runKernel uses i to select the same position in input and output. The caller passes n as an element count and supplies separate GPU arrays. Every launched thread runs this body; the index chooses its data.

blockIdx.x is the block number, blockDim.x is the number of threads per block, and threadIdx.x is the thread’s index within its block. The expression for i combines them into an array index. The condition i < n allows only valid indices to read and write the arrays. Lesson 3 explores launches with extra threads.

CUDA C++ · launch inside main()

runKernel<<<blocks, threadsPerBlock>>>(
      d_x, d_y, n);

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 Output: [2, 4, 6, 8, 10] in Console. These are the five input values multiplied by two.

Change the source

In runKernel in the CUDA source editor, change input[i] * 2.0f to input[i] * 3.0f. Predict the third value (index 2) in Console’s Output array and click Compile and run again. Which output values change? Do they keep their positions?

Read the starter’s execution diagram

Follow the starter’s execution
  1. Read input[i]Choose an element using the thread index.
  2. MultiplyApply the multiplier in runKernel.
  3. Write output[i]Keep the same destination index.

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

Hardware context

The SM executes the threads in the assigned block. Threads are logical executions with their own values; they do not each own a physical arithmetic unit.

Computer / system · host and GPU device

CPU side · CUDA host

CPUmain() and CUDA calls.
System RAMCPU memory for arrays.

GPU device

GPU compute chip

SM · streaming multiprocessorThis lesson
Assigned blocks → threads
Logical groups using this SM’s resources
Other SMs

Can run other blocks.

Blocks may be assigned to different SMs.

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 is not a dedicated physical processor.

Explore the model: thread outputs

Trace the model inputs and outputs

Try it

The model starts with Multiplier 2.0. Click Run model and find Thread index 2 in Modelled values. Set Multiplier to 3.0, predict the Output at that index and click Run model again. Which inputs or indices change?

These controls change only this model and its displayed source excerpt. They do not edit or run the CUDA program above.

CUDA C++ · runKernel

__global__ void runKernel(
    const float* input, float* output, int n
) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) {
        output[i] = input[i] * 2.0f;
    }
}

In runKernel, the index i selects both the input and the output. The f on 2.0f makes the multiplier an FP32 value.

Input [1.0, 2.0, 3.0, 4.0, 5.0]

Run to see the result.

Read the complete model program

CUDA C++ · complete program

// CUDA C++ Lab · hello.cu
#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(1);
  }
}
#define CUDA_CHECK(call) check(call)

__global__ void runKernel(
    const float* input, float* output, int n
) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) {
        output[i] = input[i] * 2.0f;
    }
}

int main() {
  const float x[] = {
    1.0f, 2.0f, 3.0f, 4.0f, 5.0f
  };
  const int n = sizeof(x) / sizeof(x[0]);
  float y[n];
  float *d_x, *d_y;

  CUDA_CHECK(cudaMalloc(&d_x, sizeof(x)));
  CUDA_CHECK(cudaMalloc(&d_y, sizeof(y)));

  CUDA_CHECK(cudaMemcpy(
      d_x, x, sizeof(x),
      cudaMemcpyHostToDevice));

  const int threadsPerBlock = 5;
  const int blocks =
      (n + threadsPerBlock - 1) / threadsPerBlock;
  runKernel<<<blocks, threadsPerBlock>>>(
      d_x, d_y, n);
  CUDA_CHECK(cudaGetLastError());
  CUDA_CHECK(cudaDeviceSynchronize());

  CUDA_CHECK(cudaMemcpy(
      y, d_y, sizeof(y),
      cudaMemcpyDeviceToHost));

  std::printf("Output: [");
  for (int i = 0; i < n; ++i) {
    std::printf("%s%g", i ? ", " : "", static_cast<double>(y[i]));
  }
  std::printf("]\n");
  CUDA_CHECK(cudaFree(d_x));
  CUDA_CHECK(cudaFree(d_y));
}

Apply what you saw

If you change the multiplier to 0.5, do the threads pick different inputs?

Compare your explanation

No. The thread indices stay the same. The result at index 2 changes to 1.5 because its input is still 3.0.

Follow one element through an SM 2 min 8 sec · Video walkthrough, captions and transcript

Use fullscreen to inspect the code and diagram labels.

Read the transcript

Follow one input to its output

The starter doubles five input values. Follow input[2] to output[2]. How does the thread choose that position?

The inputs are already in GPU memory

The supplied setup already copies the inputs into GPU memory. Leave that setup unchanged for this experiment.

Find the selected thread’s index

We follow block zero’s local thread two. Zero times four, plus two, gives array index two.

One index selects both positions

The same index selects input[2] and output[2].

The SM executes the thread

An SM, or streaming multiprocessor, is execution hardware on the GPU chip. It runs the selected thread’s instructions.

Read input[2] from GPU memory

The thread reads 3.0 from input[2] in GPU memory. That value becomes working state for its instructions on the SM.

Shared hardware performs the multiply

The SM’s arithmetic hardware multiplies 3.0 by 2.0, producing 6.0. Threads keep their own working values while sharing this hardware.

Write the matching output position

The thread writes 6.0 to output[2] in GPU memory. Its index fixes the destination even if other threads finish first.

The CPU prints the copied results

main copies the GPU results into CPU memory and prints Output.

Try a different multiplier

Return to the lesson. Find runKernel in the CUDA source editor. Change its multiplier from 2.0f to 4.0f. Pause. Predict the third Output value and the hardware doing the multiply. Click Compile and run. Return to this recording to compare your result.

Compare your result

With 4.0f, input[2] still supplies 3.0 and output[2] becomes 12.0. The same index chooses the destination; the SM still performs the multiply.

Index, execution and storage

The index selects data. The SM performs arithmetic. GPU memory holds the arrays. Lesson three explores the launch size.

References thread hierarchy · kernel launches

The browser exercises need no installed CUDA documentation version. For local execution, use the documentation matching your toolkit. External references need internet access.

  • 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 · kernel launches (new tab)

    The launch gives blocks and threads per block. Kernel arguments supply data and array bounds.

    For nine values and four threads per block, what launch covers the input, and what must the kernel still check?

    Compare your answer

    Three blocks cover twelve thread indices. Pass n = 9 separately and guard array accesses with i < n; the launch does not allocate storage.

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.