From the free course 2.1.Intro to CUDA C++ on Lykke
The SIMT Execution Model and Thread Hierarchy
Key concepts: SIMT Execution Model · Thread Blocks and Grids · threadIdx, blockIdx, blockDim, gridDim · Thread Indexing
Explains the Single Instruction, Multiple Threads (SIMT) model and how threads are organized into grids and blocks for parallel execution.
The SIMT Execution Model and Thread Hierarchy
The transition from traditional sequential CPU programming to high-performance GPU computing necessitates a fundamental shift in how we conceptualize execution. At the heart of NVIDIA’s CUDA platform lies the SIMT (Single Instruction, Multiple Threads) execution model and a structured Thread Hierarchy. These concepts are not merely abstractions; they represent the bridge between software intent and hardware reality, allowing a single program to scale across GPUs with vastly different core counts.
[AI_INFOGRAPHIC: A multi-layered diagram showing the CUDA Hierarchy. At the top, a 'Grid' containing multiple 'Blocks'. One 'Block' is expanded to show a 3D array of 'Threads'. A side panel maps 'Blocks' to 'Streaming Multiprocessors (SMs)' and 'Threads' to 'CUDA Cores', highlighting the Warp as the fundamental scheduling unit.]
The SIMT Execution Model
The SIMT (Single Instruction, Multiple Threads) model is the architectural foundation of the GPU. While it shares DNA with the classic Flynn’s Taxonomy category of SIMD (Single Instruction, Multiple Data), it introduces critical flexibility that distinguishes modern GPUs from vector processors of the past.
What it is
In a SIMT model, the processor executes the same instruction across multiple threads in parallel. However, unlike SIMD—where a single instruction operates on a fixed-width vector register—SIMT allows each thread to have its own instruction address counter and register state. This means that while threads are scheduled to execute the same instruction simultaneously, they can technically follow different control flow paths.
Definition: SIMT (Single Instruction, Multiple Threads) A parallel execution model where a single instruction is issued to a group of threads (a Warp). Each thread has its own register state and can perform independent branching, though performance is maximized when threads in a warp follow the same execution path.
Why it Matters: The Abstraction of Parallelism
SIMT solves the "vector width" problem. In traditional SIMD programming (like Intel SSE/AVX), the programmer must explicitly manage the width of the vector (e.g., 4 floats or 8 floats). If the hardware changes, the code often needs a rewrite. In SIMT, the programmer writes code for a single thread. The hardware then bundles these threads into groups of 32, known as Warps, and executes them. This allows the same CUDA kernel to run on a budget laptop GPU or a massive H100 data center GPU without modification.
SIMT vs. SIMD vs. SPMD
To understand SIMT, it is helpful to compare it to other common parallel paradigms:
| Feature | SIMD (Vector) | SPMD (MPI/Multi-core) | SIMT (CUDA) |
|---|---|---|---|
| Unit of Programming | Vector of N elements | Independent Process | Single Thread |
| Instruction Stream | Single | Multiple | Single (issued to Warps) |
| Branching | Masked/Predicated | Fully Independent | Hardware-managed Divergence |
| Hardware Mapping | Vector Registers | CPU Cores | Streaming Multiprocessors |
The Thread Hierarchy: Grids, Blocks, and Threads
To manage the massive parallelism of the SIMT model, CUDA organizes threads into a three-tier hierarchy. This structure allows developers to map their problem domain (e.g., pixels in an image, cells in a fluid simulation) directly onto the hardware.
1. The Thread
The smallest unit of execution. A thread executes the kernel function and has its own private Registers and Local Memory.
2. The Block (Thread Block)
A collection of threads that execute on the same Streaming Multiprocessor (SM). Threads within the same block can communicate with each other through Shared Memory and can synchronize their execution using barriers (__syncthreads()).
- Limitation: A block is limited in size (typically 1,024 threads) because all threads in a block must reside on a single SM and share its limited resources.
3. The Grid
The highest level of the hierarchy. A grid is composed of multiple thread blocks. When a kernel is launched, it creates a single grid.
- Scalability: Blocks within a grid are required to be independent. They can be executed in any order, in parallel or in series. This "independence" is what allows CUDA programs to scale; a GPU with more SMs will simply run more blocks in parallel.
Hierarchy Parameters and Limits
| Level | Maximum Dimensions | Typical Max Capacity | Resource Sharing |
|---|---|---|---|
| Thread | N/A | 1 | Registers, Local Memory |
| Block | 3D (x, y, z) | 1,024 Threads | Shared Memory, L1 Cache |
| Grid | 3D (x, y, z) | $2^{31}-1$ (x), 65535 (y, z) | Global Memory, L2 Cache |
Built-in Variables and Indexing
In a CUDA kernel, every thread is identical in terms of code. To make threads perform different tasks (e.g., processing different elements of an array), we use Built-in Variables to calculate a thread's unique identity.
The Four Fundamental Variables
gridDim: The dimensions of the grid (number of blocks in x, y, and z).blockIdx: The index of the current block within the grid.blockDim: The dimensions of the block (number of threads in x, y, and z).threadIdx: The index of the current thread within its block.
Mathematical Indexing Formulas
To map a thread to a 1D data array, we must calculate a global index. This is the most common operation in CUDA programming.
1. Linear (1D) Indexing: If you have a 1D grid of 1D blocks: $$GlobalIndex = blockIdx.x \times blockDim.x + threadIdx.x$$
2. 2D Indexing (e.g., Image Processing): When processing a matrix or image, we often use 2D blocks and 2D grids. To find the row ($y$) and column ($x$): $$x = blockIdx.x \times blockDim.x + threadIdx.x$$ $$y = blockIdx.y \times blockDim.y + threadIdx.y$$ $$GlobalIndex = y \times Width + x$$
[AI_DEMO: An interactive visualization where users can adjust 'Block Size' and 'Grid Size' sliders. As values change, a grid of cells updates. Clicking a cell highlights the specific values for threadIdx, blockIdx, and the resulting GlobalIndex calculation.]
Implementation: A Practical Example
The following code demonstrates a standard vector addition kernel. It highlights the use of the triple-chevron syntax (<<< >>>) for the Execution Configuration, which defines the thread hierarchy.
#include <cuda_runtime.h>
#include <iostream>
// Kernel definition: __global__ indicates this runs on the device
__global__ void vectorAdd(const float* A, const float* B, float* C, int numElements) {
// Calculate the global unique thread ID
int i = blockIdx.x * blockDim.x + threadIdx.x;
// Boundary check: ensure we don't access memory out of bounds
// if the number of threads is not a perfect multiple of block size
if (i < numElements) {
C[i] = A[i] + B[i];
}
}
int main() {
int N = 50000;
size_t size = N * sizeof(float);
// Using Unified Memory (Managed) for simplicity
float *A, *B, *C;
cudaMallocManaged(&A, size);
cudaMallocManaged(&B, size);
cudaMallocManaged(&C, size);
// Initialize data...
// Execution Configuration
// We want enough threads to cover N elements.
int threadsPerBlock = 256;
int blocksPerGrid = (N + threadsPerBlock - 1) / threadsPerBlock;
// Launch the kernel
// <<< blocksPerGrid, threadsPerBlock >>>
vectorAdd<<<blocksPerGrid, threadsPerBlock>>>(A, B, C, N);
// Wait for GPU to finish before accessing results on host
cudaDeviceSynchronize();
// Free memory...
cudaFree(A); cudaFree(B); cudaFree(C);
return 0;
}
Analysis of the Execution Configuration
In the example above, blocksPerGrid is calculated as (N + threadsPerBlock - 1) / threadsPerBlock. This is a standard idiom in CUDA to perform an integer ceiling division. It ensures that if $N$ is not a multiple of threadsPerBlock, we launch one extra block to cover the remaining elements, preventing data from being ignored.
Hardware Mapping: The Warp and the SM
While the programmer thinks in terms of Blocks and Grids, the hardware thinks in terms of Streaming Multiprocessors (SMs) and Warps.
The Warp: The Unit of Execution
A Warp is a group of 32 threads within a block. The SM schedules and executes threads at the warp level. All 32 threads in a warp start at the same program address.
Warp Divergence
If a kernel contains an if-else statement and some threads in a warp take the if path while others take the else path, the warp is said to diverge.
- The SM executes the
ifpath while disabling the threads that take theelsepath. - The SM then executes the
elsepath while disabling the threads that took theifpath. - The paths are eventually reconverged.
- Performance Impact: Divergence can significantly reduce throughput because the hardware is essentially executing both paths serially for that specific warp.
Block Scheduling
When a grid is launched, the CUDA runtime enumerates the blocks and distributes them among the available SMs.
- If an SM has enough registers and shared memory, it can host multiple blocks simultaneously.
- As soon as one block finishes, a new block from the grid is scheduled onto that SM.
- This is why Block Independence is vital: since you don't know which block will run first or which SM it will run on, blocks cannot safely wait for each other to produce data.
Advanced Considerations: Memory and Compilation
The SIMT model is inextricably linked to the GPU's memory hierarchy and the compilation toolchain.
Memory Spaces and the Hierarchy
The thread hierarchy maps directly to the memory hierarchy, which is crucial for optimizing data movement.
| Memory Space | Scope | Lifetime | Latency |
|---|---|---|---|
| Register | Thread | Thread | Lowest (Instant) |
| Local Memory | Thread | Thread | High (DRAM-backed) |
| Shared Memory | Block | Block | Low (On-chip) |
| Global Memory | Grid + Host | Application | Very High (DRAM) |
The Role of NVCC
The nvcc compiler is responsible for splitting the CUDA source code into host code (running on the CPU) and device code (the kernels).
- PTX (Parallel Thread Execution): nvcc first compiles device code into PTX, an intermediate virtual assembly language.
- Cubin: The PTX is then compiled (either at compile-time or JIT at runtime) into a binary specific to the GPU architecture (e.g., sm_80 for Ampere).
- Virtual vs. Real Architectures: Developers can target a virtual architecture (for compatibility) and a real architecture (for optimization) simultaneously using the
-archand-codeflags.
Common Pitfalls and Best Practices
- Integer Overflow in Indexing: When working with very large datasets (e.g., 4K video frames or large 3D volumes), calculating
blockIdx.x * blockDim.xcan exceed the limit of a 32-bitint. Always usesize_torlong longfor global index calculations in high-scale applications. - Hardcoding Block Sizes: While
threadsPerBlock = 256is a safe default, different kernels have different register requirements. Hardcoding can lead to poor Occupancy (the ratio of active warps to maximum supported warps). UsecudaOccupancyMaxPotentialBlockSizeto let the runtime decide the optimal size. - Ignoring Boundary Conditions: If your grid size is not a perfect multiple of your block size, the last block will contain "extra" threads. Without an
if (index < N)check, these threads will access memory outside the allocated array, leading to undefined behavior or crashes. - Assuming Block Execution Order: Never write code that assumes Block 0 will finish before Block 1. If you need global synchronization, you must end the kernel and launch a second one, or use expensive global atomics (not recommended for general flow control).
[AI_FLASHCARDS:
- SIMT: Single Instruction Multiple Threads; the execution model of CUDA.
- Warp: A group of 32 threads; the fundamental unit of hardware scheduling.
- __syncthreads():** A barrier synchronization primitive for threads within a single block.
- blockDim: A built-in variable defining the number of threads per block.
- Warp Divergence: Performance loss occurring when threads in a warp follow different execution paths.
- SM (Streaming Multiprocessor): The hardware unit that executes thread blocks.
- Grid: The complete set of thread blocks launched for a single kernel. ]
[AI_QUIZ:
- If a kernel is launched with
<<<dim3(10, 10), dim3(16, 16)>>>, how many total threads are in the grid?- A) 256
- B) 100
- C) 25,600 (Correct: 1010 blocks * 1616 threads/block)
- D) 1,600
- Which memory space allows threads in different blocks to communicate?
- A) Shared Memory
- B) Registers
- C) Global Memory (Correct)
- D) Local Memory
- Why does SIMT improve scalability compared to SIMD?
- A) It uses less power.
- B) It abstracts the vector width, allowing the same code to run on different hardware configurations. (Correct)
- C) It prevents all types of branching.
- D) It removes the need for a compiler.
- What happens if 16 threads in a warp take Branch A and 16 threads take Branch B?
- A) They run in parallel on two different SMs.
- B) The SM executes Branch A, then Branch B, effectively doubling execution time for that warp. (Correct)
- C) The kernel crashes.
- D) The GPU automatically merges the branches into a single instruction. ]
[AI_STUDY_GUIDE: Key Concepts to Master:
- The Mapping Equation: Be able to derive the global index for 1D, 2D, and 3D thread layouts.
- Resource Constraints: Understand how registers and shared memory usage per thread/block limit the number of active blocks on an SM.
- The Warp Unit: Remember that hardware always operates in groups of 32, regardless of your
blockDim. - Synchronization: Know the difference between
__syncthreads()(block-level) and host-sidecudaDeviceSynchronize()(grid-level). - Compilation Workflow: Understand how
nvcchandles the separation of host and device code and the role of PTX. Practice Problem: Write a kernel that performs a 2D image transpose. Calculate thexandycoordinates usingthreadIdxandblockIdx, then swap them to write to the output buffer. Ensure you handle non-square images correctly. ]
Source Materials
Study 2.1.Intro to CUDA C++ on Lykke
This course page is free to open: signed out, you can read its first two sections, and signing in, on any plan, opens the rest. The free Lykke Chrome extension syncs your own Canvas courses, so ChatGPT, Claude and Muse can answer from your classes and deadlines. It only reads Canvas.
Add the free extensionSign in to open every sectionAll sections of 2.1.Intro to CUDA C++ · Browse more course pages