Module 13 · Lesson 9 of 98

The kernel, the grid, and the thread index

Read a one-dimensional CUDA launch, compute each thread’s array index, and guard accesses when the grid contains more threads than elements.

  • Beginner to advanced
  • 7 min read
  • 11 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM for the written practice, plus familiarity with C-style arrays and zero-based indexing. Running the CUDA excerpts requires a CUDA-capable NVIDIA GPU and a CUDA development environment.

Your place in the module
By the end you can 4 objectives
  • Identify the kernel, block count, thread count per block, and function arguments in a CUDA launch.
  • Distinguish threadIdx, blockIdx, blockDim, and gridDim in a one-dimensional grid.
  • Calculate a thread’s flattened index from its block and local thread coordinates.
  • Calculate a covering grid and guard array accesses against excess threads.
Video coming soonThe kernel, the grid, and the thread index
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Memory bandwidth and when a discrete GPU wins
  • A shared memory controller services DRAM traffic from the CPU, accelerators, and other SoC devices.
  • Required DRAM bandwidth equals bytes transferred per inference multiplied by inferences per second.
  • Dedicated VRAM can reduce contention with host traffic, but transfers and queueing still count toward response time.
01

One kernel launch creates a grid

3 min read

You have finished the survey of embedded GPUs and know which unit runs your code. Now you write that code, and this lesson answers how one kernel launches on thousands of threads that each know their own index.

Suppose an embedded application has two arrays of sensor samples and needs to add corresponding values. The sum at element 0 uses the two inputs at element 0. The sum at element 1 uses the two inputs at element 1. Each sum can be computed independently when the output is a separate array. NVIDIA’s CUDA C++ Programming Guide uses vector addition to demonstrate this mapping. A single function describes the addition for one element, and a single launch supplies enough threads for the whole array.

A In the CUDA C++ excerpt below, __global__ declares VecAdd as a kernel. It has a void return type. Each thread writes its result through out, and the caller supplies the array length as n. The three pointers refer to arrays accessible to the GPU, each with room for at least n elements.

cpp
#include <cstddef>

__global__ void VecAdd(const float* a, const float* b, float* out,
                       std::size_t n)
{
    const std::size_t i =
        static_cast<std::size_t>(blockIdx.x) * blockDim.x + threadIdx.x;

    if (i < n) {
        out[i] = a[i] + b[i];
    }
}

Here is the launch statement as it would appear in host code after the pointers, length, and launch counts have been prepared. The two excerpts show the kernel and its launch syntax.

cpp
VecAdd<<<numBlocks, threadsPerBlock>>>(a, b, out, n);

The two expressions inside <<< >>> set the execution configuration. For this one-dimensional launch, numBlocks gives the number of blocks in the grid and threadsPerBlock gives the number of threads in each block. The expressions inside ( ) supply the function arguments. Every thread in this launch receives the same pointer and length argument values. CUDA supplies the coordinates each thread reads inside the function.

A For example, a configuration of 16 blocks with 256 threads in each block creates 4,096 logical threads. There is one VecAdd definition and one launch statement. Each logical thread executes the function with its own local variables, including i. The count describes the work the launch creates. The indexing calculation gives the same answer regardless of when a particular thread executes.

One vector addition launchVecAdd launchOne grid16 blocksnumBlocks256 threads per blockthreadsPerBlockVecAdd launchOne grid16 blocksnumBlocks256 threads per blockthreadsPerBlock
The launch creates one grid, which contains blocks of equal size.

For vector addition, the programmer chooses the rule that one thread with index i handles element i. CUDA provides block and thread coordinates. The multiplication and addition in the kernel turn those coordinates into an array index. The next section works through that calculation using a launch small enough to inspect by hand.

02

From two coordinates to one array index

3 min read

Inside the kernel, CUDA exposes four built-in variables that describe the current thread and its launch. This lesson uses the .x component of each because the launch is one-dimensional. Coordinates start at zero. Counts tell you how many coordinate values are available.

Built-in Meaning in this launch Value or range for 3 blocks of 4 threads
threadIdx.x This thread’s position within its block 0 through 3 in every block
blockIdx.x This block’s position within the grid 0 through 2
blockDim.x Number of threads in each block 4 for every thread
gridDim.x Number of blocks in the grid 3 for every thread

Consider the thread at local position 2. Each block has a thread with that position, so threadIdx.x alone would select element 2 in all three blocks. The block coordinate tells you how many blocks precede the current one in index order. Multiply that coordinate by the size of a block to count the thread positions in those preceding blocks. Then add the thread’s local position. The flattened index is i = blockIdx.x * blockDim.x + threadIdx.x.

With four threads per block, block 0 starts at index 0, block 1 starts at index 4, and block 2 starts at index 8. Local position 2 in those blocks maps to indices 2, 6, and 10 respectively. At the boundary between blocks 0 and 1, the last local position in block 0 gives 0 * 4 + 3 = 3. The first local position in block 1 gives 1 * 4 + 0 = 4. That same calculation works at every block boundary.

Three blocks of four threadsLocal position0123Block 00123Block 14567Block 2891011Block start plus local position gives the array index.
Each row is a block. Each column is a local thread position. The cells show the resulting array indices.

In general, a block with coordinate b owns the consecutive index range from b * blockDim.x through (b + 1) * blockDim.x - 1. Each following block starts exactly one index after the previous block ends. This gives every thread a unique flattened index and covers every integer from zero through gridDim.x * blockDim.x - 1. The range describes index ownership. For example, thread 5 can compute its sum without waiting for thread 4 to compute its own.

blockDim.x supplies the stride from one block’s starting index to the next. gridDim.x supplies the total number of blocks and helps calculate the total thread count. In the example, using the grid size as a stride would give block 1 a starting index of 3. Block 0 already ends at 3, so two threads would claim that element. In the excerpt, i uses std::size_t, an unsigned size type, and the cast converts the block coordinate before multiplication. This makes the arithmetic use the wider size type on a 64-bit target, where large launches can require it.

03

Cover the array and guard the final block

2 min read

The array length determines how many useful indices the launch needs. If n is 10 and each block contains 4 threads, two blocks give indices 0 through 7 and leave elements 8 and 9 without a thread. Three blocks give indices 0 through 11. A one-dimensional launch gives every block the configured size, so the third block also has four threads. The kernel must check which of those threads have a valid element.

For a positive n and a positive threadsPerBlock, choose the smallest block count whose capacity covers n. This is the mathematical ceiling of n / threadsPerBlock. You can calculate it with integer division and remainder. The quotient counts full blocks, and a nonzero remainder calls for one more. In the host excerpt below, assume the computed count and block size are valid for the device.

cpp
if (n > 0) {
    const std::size_t numBlocks =
        n / threadsPerBlock + (n % threadsPerBlock != 0);
    VecAdd<<<numBlocks, threadsPerBlock>>>(a, b, out, n);
}

For 10 elements and 4 threads per block, the quotient is 2 and the remainder is 2, so the expression gives 3 blocks. For 12 elements with the same block size, the quotient is 3 and the remainder is 0, so the expression still gives 3 blocks. When n is zero, the host skips the launch because an empty array needs no threads.

In the kernel, i < n admits exactly the valid array indices, from 0 through n - 1 for a nonempty array. With 10 elements, threads 8 and 9 in the last block perform their additions. Threads 10 and 11 reach the same test, skip both input reads and the output write, and finish. Put the test before any of the three accesses. The comparison i <= n would admit index 10, which is already one position past the last element.

Bounds check before array accessComputeindexi < n?Read bothinputsStore thesumExit from step 2: i >= nSkip array accessComputeindexi < n?Exit from step 2: i >= nSkip array accessRead bothinputsStore thesum
Every launched thread computes an index. Only indices below the array length reach the loads and store.

For a larger example, take 4,100 elements and 256 threads per block. Sixteen blocks cover 4,096 elements, so the host launches seventeen blocks. The last block begins at index 4,096. Its first four threads process the remaining four elements, and the others skip the addition. The same formula and test work even when the last block has just one useful thread. A larger data set changes the launch count and the boundary value, while the function body stays the same.

When reading a launch, first calculate how many index positions it creates. Then compare that count with the number of elements and trace the last valid index through the kernel. In 2D and 3D grids with dim3, the next lesson uses the same coordinate idea to assign threads to data with rows, columns, and planes.

Key takeaways

  • A host launch of a __global__ kernel specifies the number of blocks and the number of threads per block.
  • In a one-dimensional launch, threadIdx.x repeats in each block and blockIdx.x identifies the block.
  • Multiplying the block index by the block size and adding the local thread index gives a unique index across the grid.
  • A rounded-up launch can include threads beyond the array length, so the kernel checks i < n before accessing the arrays.
Reflect
  1. Explain to a colleague, in two sentences: identify the kernel, block count, thread count per block, and function arguments in a CUDA launch.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close