CUDA C++ LabGPU architecture

More threads than elements

Change the block size and see which threads skip the guarded array reads and writes.

Before you run

The starter uses the same five input values and runKernel as lesson 2. Change the number of threads per block while keeping the input array unchanged.

Definitions

Block
A group of threads launched together.
Bounds check
A condition that prevents a thread from accessing an array beyond its valid indices.

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;
    }
}

blockIdx.x identifies a block, blockDim.x its size, and threadIdx.x the local thread index. Their combination gives i. The caller passes n separately; i < n protects both array accesses when the launch has spare 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. In Console, find the five values in Output. Open Trace CUDA calls and find 2 blocks × 4 threads. The launch requests eight threads for five inputs.

Change the source

In main() in the CUDA source editor, change threadsPerBlock from 4 to 3. Predict the total launched threads and click Compile and run again. Open Trace CUDA calls and compare the blocks × threads line with the starter. Does Console’s Output array change?

Read the starter’s execution diagram

From local thread index to array index
Thread 0Thread 1Thread 2Thread 3
Block 00Write1Write2Write3Write
Block 14Write5Skip6Skip7Skip

Both blocks have local threads 0–3. The start of the second block is 1 × 4, so its first local thread handles array index 4.

Hardware context

A block is assigned to an SM. More launched threads do not create more execution units. A thread beyond n still exists but skips the guarded array operations.

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 indices and bounds

Trace the model inputs and outputs

Try it

The model starts with five inputs and Threads per block set to 4. It calculates the block count. Click Run model, then change Threads per block to 3. Predict which Index i rows will show Skipped under Array access and click Run model again.

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

CUDA C++ · kernel and launch

__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 main(), after copying the input:
const int threadsPerBlock = 4;
const int blocks =
    (n + threadsPerBlock - 1) / threadsPerBlock;
runKernel<<<blocks, threadsPerBlock>>>(
    d_x, d_y, n);

blockIdx.x is the block number. blockDim.x is its size. threadIdx.x is the thread’s index within that block. Multiplying the block number by the block size and adding the local index gives i.

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 = 4;
  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

The input still has five values. Why does one block of eight threads skip the same indices as two blocks of four?

Compare your explanation

Both launches produce indices 0 through 7. The grouping changes, and the condition i < n still allows indices 0 through 4.

Why eight threads can form two warps 1 min 53 sec · Video walkthrough, captions and transcript

Use fullscreen to inspect the code and diagram labels.

Read the transcript

Eight threads, five elements

Five inputs need five array updates. The supplied launch creates two blocks of four threads, so eight threads start. Follow where those threads fit in the GPU, including the three that have no input element.

A block uses shared SM hardware

An SM is a streaming multiprocessor: hardware that executes the threads of assigned blocks. Both blocks are drawn on one SM here as a possible placement. The launch does not assign each thread its own physical processor.

Each block forms its own warp

A warp is a group of up to thirty-two threads from one block whose instructions are issued together. A four-thread block occupies a partially filled warp. Threads from the second block cannot fill the first block’s unused positions.

The guard changes participation

All eight launched threads calculate their indices. Only indices below five execute the guarded array reads and writes. Threads five, six and seven skip those operations. They are different from warp positions that were never launched.

Regroup the same eight threads

Consider changing threadsPerBlock from four to eight. There are still five inputs. Pause and predict the number of blocks and partially filled warps. Should the five output values change?

One block, one partially filled warp

The launch now needs one block of eight threads, so it uses one partially filled warp. Five threads still perform the array operations and three skip them. The grouping changed, not the requested calculation.

Check grouping separately from values

In the CUDA source editor, set threadsPerBlock to eight and click Compile and run. Trace CUDA calls shows one block of eight threads. Console’s five outputs stay the same; the warp diagram explains grouping, not measured execution time.

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.