Forward Deployed EngineeringAI InfrastructureGPU Programming

Explain how the CUDA execution model maps to hardware, grids, blocks, warps, SMs.

Question 33 of 73 · Updated

On this page

Interview-ready answer#

CUDA exposes a hierarchy of threads, thread blocks and grids, and NVIDIA hardware executes those threads using warps on streaming multiprocessors (SMs).

A kernel launch creates a grid of blocks. Each block contains a programmer-selected number of threads, and ordinary thread blocks are assigned to SMs as resources become available. A block's threads execute on the same SM for its resident execution; multiple blocks may reside on an SM simultaneously if its register, shared-memory, thread, warp and block limits permit.

Within a block, threads are grouped into warps of 32 consecutive linear thread indices on NVIDIA CUDA hardware. Warp schedulers issue instructions for eligible warps using SIMT (single instruction, multiple threads). Threads retain individual registers and logical execution state, so they can follow different branches, but divergent paths within a warp may require additional instruction execution with subsets of lanes active.

The grid determines the total work, the block provides a local cooperation and synchronization scope, the warp is a hardware execution grouping, and the SM provides the execution pipelines, warp schedulers, register resources and shared memory. Good CUDA performance requires enough useful parallelism to hide latency, efficient memory access and appropriate resource usage—not simply maximizing the number of threads or occupancy.

1. Software hierarchy and hardware mapping#

ConceptMeaningMain responsibility
KernelDevice function launched for parallel executionDefines work performed by each logical thread
GridCollection of blocks for one kernel launchRepresents the total parallel workload
Thread blockGroup of cooperating threads with a shared block indexProvides block-level cooperation and shared memory
ThreadLogical execution instance with its own indices and registersExecutes the kernel's per-thread work
WarpHardware execution group of 32 CUDA threadsInstruction issue and active-lane execution
Streaming multiprocessor (SM)GPU execution and resource-management unitHosts resident blocks and schedules their warps

The grid and block dimensions are part of the programming model. The warp and SM explain how the hardware executes that model. A block is not a physical SM, and a thread is not permanently assigned to an individual CUDA core for the entire kernel.

Loading diagram…

This is a conceptual mapping, not a guarantee of actual block placement. The runtime and hardware determine which SM receives each block. Several blocks may execute on the same SM, blocks may execute in waves, and programmers must not assume that block 0 starts before block 1. Ordinary independent blocks must remain correct regardless of their scheduling order.

Newer architecture-specific facilities such as thread-block clusters and cooperative launches support additional coordination under their documented constraints. They do not make arbitrary global synchronization safe in an ordinary kernel.

2. Kernel launches and thread indexing#

A typical launch uses CUDA C++ syntax:

CPP
kernel<<<grid_size, block_size>>>(arguments);

For a one-dimensional launch with 256 threads per block:

  • threadIdx.x ranges from 0 to 255 inside each block.
  • blockIdx.x identifies the block in the grid.
  • blockDim.x is 256.
  • gridDim.x is the number of blocks.

The global thread index is:

LaTeX

For an array of 1,000 elements, choose 256 threads per block and ceil(1,000 / 256) = 4 blocks. The launch creates 1,024 logical threads. The final 24 threads must not read or write outside the array.

Block indexGlobal indices launchedValid element indices
00–2550–255
1256–511256–511
2512–767512–767
3768–1,023768–999

For multidimensional blocks, linear thread order is x + blockDim.x × (y + blockDim.y × z), with x varying fastest. Warps are formed from successive linear thread indices, not from an arbitrary selection of threads. For row-major matrices, a useful starting point is to map neighboring x threads to neighboring columns, subject to the actual layout and algorithm.

3. CUDA kernel example: vector addition#

This illustrative CUDA C++ program allocates device buffers, copies inputs, launches a bounds-checked kernel, checks launch and execution errors, and validates the result on the host.

CUDA
#include <cuda_runtime.h> #include <cstdio> #include <cstdlib> #include <vector> #define CHECK(call) do { \ cudaError_t err = (call); \ if (err != cudaSuccess) { \ std::fprintf(stderr, "%s\n", cudaGetErrorString(err)); \ std::exit(EXIT_FAILURE); \ } \ } while (0) __global__ void add(const float* a, const float* b, float* c, size_t n) { size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; if (i < n) { c[i] = a[i] + b[i]; } } int main() { const size_t n = 1000; const size_t bytes = n * sizeof(float); std::vector<float> a(n, 2.0f), b(n, 3.0f), c(n); float *da = nullptr, *db = nullptr, *dc = nullptr; CHECK(cudaMalloc(&da, bytes)); CHECK(cudaMalloc(&db, bytes)); CHECK(cudaMalloc(&dc, bytes)); CHECK(cudaMemcpy(da, a.data(), bytes, cudaMemcpyHostToDevice)); CHECK(cudaMemcpy(db, b.data(), bytes, cudaMemcpyHostToDevice)); const unsigned threads = 256; const unsigned blocks = (n + threads - 1) / threads; add<<<blocks, threads>>>(da, db, dc, n); CHECK(cudaGetLastError()); CHECK(cudaDeviceSynchronize()); CHECK(cudaMemcpy(c.data(), dc, bytes, cudaMemcpyDeviceToHost)); for (float value : c) { if (value != 5.0f) { std::fprintf(stderr, "validation failed\n"); return EXIT_FAILURE; } } CHECK(cudaFree(da)); CHECK(cudaFree(db)); CHECK(cudaFree(dc)); return EXIT_SUCCESS; }

A developer with a compatible NVIDIA GPU, CUDA toolkit and driver can save this as add.cu, compile using nvcc add.cu -o add, and execute the resulting program. Check the target GPU architecture and compiler options for the actual deployment. The synchronization in this example is intentional for validation; production code often uses stream ordering, events and appropriately placed synchronization to avoid needless serialization.

Verification status: the CUDA kernel is illustrative and manually reviewed. The local environment has neither nvcc nor an exposed NVIDIA CUDA device/toolchain, so it was not compiled, GPU-executed, sanitized or benchmarked. The CPU-side index model below was executed independently.

4. Grid-stride loops#

A launch does not need to create exactly one thread for every data element. A grid-stride loop lets each thread process several elements spaced by the total thread count in the grid.

CUDA
__global__ void add_stride(const float* a, const float* b, float* c, size_t n) { size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; size_t stride = size_t(gridDim.x) * blockDim.x; for (; i < n; i += stride) { c[i] = a[i] + b[i]; } }

For two blocks of four threads, the stride is eight. Thread with global index 0 handles 0, 8, 16 and so on; thread 1 handles 1, 9, 17 and so on. This toy configuration is useful for explaining the arithmetic, not a recommended launch configuration.

Each valid element is assigned to exactly one global thread index modulo the stride. Adjacent threads still access adjacent elements in each iteration. The grid can be sized according to available parallelism and measured performance while the loop covers the entire dataset. Ensure dimensions and indexing types safely represent the actual problem size; empty input should be handled without launching a zero-block grid.

CPU-tested indexing reference#

PYTHON
def grid_stride_indices(n, blocks, threads): if n < 0 or blocks <= 0 or threads <= 0: raise ValueError('invalid launch dimensions') stride = blocks * threads return [list(range(b*threads+t, n, stride)) for b in range(blocks) for t in range(threads)]

This function models the assignment of indices for nonnegative integer n and positive integer blocks and threads. It intentionally materializes the assignments for education and testing, so it uses O(n + blocks × threads) memory and time under the usual arithmetic model. It is not a GPU simulator or a production CUDA implementation.

Example: grid_stride_indices(10, 2, 3) returns [[0, 6], [1, 7], [2, 8], [3, 9], [4], [5]].

5. Warps and SIMT#

SIMT gives programmers the abstraction of independent scalar threads while the GPU executes groups of threads together. A warp contains 32 logical lanes on NVIDIA CUDA hardware. A 256-thread block contains eight warps. A 100-thread block consumes four warps; the final warp has only four valid block threads.

A warp scheduler selects an eligible warp and issues instructions to the applicable execution pipelines. The actual issue rate, number of schedulers and execution width vary by GPU architecture and instruction type. A warp instruction need not finish in one clock cycle, and a warp does not require 32 dedicated cores reserved for its lifetime.

When a warp waits for a memory operation or instruction dependency, the SM may issue instructions from another eligible warp. Maintaining multiple resident warps helps hide latency. This is different from a CPU operating system performing an expensive context switch for each thread: resident GPU warp state is managed by hardware.

Divergence#

Consider a branch that tests whether a thread index is even. Neighboring lanes may take different paths.

Loading diagram…

The diagram is conceptual. Compilers may predicate short branches instead of generating separate control-flow paths, and independent thread scheduling on Volta-class and later architectures permits finer-grained thread progress than simplistic lockstep explanations suggest. Do not rely on implicit warp synchronization for inter-thread data exchange. Use the documented synchronization and mask-aware warp primitives where required.

Divergence within a warp can reduce utilization when only some lanes perform useful work. Different warps taking different branches do not create this same intra-warp divergence penalty. Optimize based on profiling; removing a branch can add unnecessary computation or memory traffic.

6. SM residency and occupancy#

An SM has finite resources, including maximum resident threads, warps and blocks, registers and shared memory. A block becomes resident only when sufficient resources are available. The number of simultaneously resident blocks is constrained by the most restrictive resource.

Theoretical occupancy is the ratio of resident active warps to the architecture's maximum supported resident warps on an SM.

Consider a hypothetical SM with the following simplified limits:

ResourceHypothetical value
Maximum resident threads2,048
Maximum resident warps64
Maximum resident blocks16
Registers65,536 32-bit registers
Shared memory available65,536 bytes
Threads per block256
Registers per thread64
Shared memory per block16,384 bytes

Each block uses eight warps and nominally 16,384 registers. The simplified limits on resident blocks are:

  • Threads: floor(2,048 / 256) = 8.
  • Warps: floor(64 / 8) = 8.
  • Block count: 16.
  • Registers: floor(65,536 / 16,384) = 4.
  • Shared memory: floor(65,536 / 16,384) = 4.

The minimum is four resident blocks, or 32 resident warps. Simplified theoretical occupancy is 32 / 64 = 50%.

These are fictional hardware parameters, not specifications for a particular NVIDIA GPU. Real allocation granularity, per-block resource maxima, reserved shared memory, scheduler partitions and architecture-specific rules can reduce the feasible occupancy. Check actual kernel resource usage, device properties, CUDA occupancy APIs and profiler measurements rather than using a simple division as a launch guarantee.

CPU-tested resource upper-bound model#

PYTHON
def occupancy_upper_bound(threads, max_threads, max_warps, max_blocks, registers_per_thread, register_file, shared_per_block, shared_capacity, warp_size=32): if min(threads, max_threads, max_warps, max_blocks, warp_size) <= 0: raise ValueError('invalid execution limits') if min(registers_per_thread, register_file, shared_per_block, shared_capacity) < 0: raise ValueError('negative resource count') warps = (threads + warp_size - 1) // warp_size limits = [max_threads // threads, max_warps // warps, max_blocks] if registers_per_thread: limits.append(register_file // (threads * registers_per_thread)) if shared_per_block: limits.append(shared_capacity // shared_per_block) resident = min(limits) return resident, resident * warps / max_warps

The model assumes integer resource quantities, a positive warp size and simple additive allocation without architecture-specific rounding. The result is a resource-based upper bound, not an exact CUDA occupancy calculator. A zero result means that the modeled resources cannot accommodate even one block.

PYTHON
assert occupancy_upper_bound( 256, 2048, 64, 16, 64, 65536, 16384, 65536 ) == (4, 0.5)

Local verification: Python 3.13.5 executed both exact CPU-side helpers. All 4,253 checks passed: 4,128 indexing cases covering sizes 0–128, block counts 1, 2, 3 and 7, and eight thread counts including warp boundaries; 120 resource-model cases checked against independent enumeration of feasible block counts; and five invalid-input checks. Indexing tests checked complete, unique coverage and per-thread assignment using an independent modulo-based reference. The worked occupancy example also returned four blocks and 0.5. This validates the simplified arithmetic only, not GPU execution, real allocation rules or performance.

Occupancy is not utilization#

High occupancy is often helpful for hiding latency, but maximum occupancy is not always optimal. Forcing lower register usage may introduce spills to local memory. Reducing shared memory may remove an effective data-reuse optimization. Larger blocks may reduce scheduling flexibility. A kernel with moderate occupancy can outperform one with higher occupancy if it performs more useful work per instruction or memory transaction.

Profile achieved occupancy, eligible warps, stall reasons, instruction throughput, memory throughput and end-to-end duration. Tune launch dimensions and resource use together. Do not select 1,024 threads per block merely because many devices support that maximum.

7. Memory hierarchy#

Memory or resourceScope and locationImportant consideration
RegistersPrivate logical thread state on the SMLimited; pressure can reduce occupancy or cause spills
Local memoryPrivate per-thread address space backed by device memory when usedNot synonymous with fast on-chip storage
Shared memoryOn-chip SM resource exposed to cooperating threads in a blockFast reuse; limited capacity and possible bank conflicts
L1 cacheSM-local caching facilitiesArchitecture-dependent configuration and behavior
L2 cacheShared device-level cacheReuse across SMs and traffic reduction
Global memoryDevice memory accessible by kernels according to allocation and permissionsHigh capacity; access latency and bandwidth matter
Constant memoryRead-only device-side access to constant dataEffective when warp lanes read common addresses
Host memoryCPU-side system memoryTransfers or mapped access involve topology-dependent costs

This hierarchy is conceptual. CUDA supports different allocation and memory-management mechanisms, and hardware implementations vary. Unified memory can simplify programming but does not eliminate page migration, bandwidth or synchronization costs. Measure transfers, faults and data placement in the real workload.

Coalescing#

When neighboring warp lanes access neighboring, appropriately aligned addresses, the hardware can combine accesses into relatively efficient memory transactions. For a warp reading 32 consecutive float values, the requested payload is 128 bytes. Actual transactions depend on alignment, access size, cache behavior and GPU architecture; do not assume that every such access is one physical memory transaction.

For a row-major matrix, mapping neighboring x threads to neighboring columns is often a good starting point. A large stride between neighboring lanes may spread the requested addresses across more memory sectors and reduce effective bandwidth. A single thread walking consecutive addresses does not automatically imply coalesced access across the warp.

Shared memory and synchronization#

Threads in a block can cooperate by staging data in shared memory. In a tiled matrix operation, for example, multiple threads can reuse a loaded tile instead of repeatedly fetching the same values from global memory. Shared-memory bank conflicts and extra barriers can reduce the benefit.

Use __syncthreads() when all participating block threads need a block-wide barrier and the documented visibility guarantees. Do not place a block-wide barrier on a branch taken by only some block threads. For a partial tile, guard loads and stores as needed but structure the barrier so required participants reach it consistently. Use __syncwarp with correct masks and participation requirements for appropriate warp-scoped coordination.

Ordinary blocks do not share a general block-level barrier across an entire grid. A separate kernel launch in the same stream can provide an ordered phase boundary; specialized cooperative grid synchronization requires supported launch conditions.

8. Why this matters in production AI systems#

For LLM serving, CUDA execution details affect how kernels perform matrix multiplications, attention, normalization, sampling and KV-cache operations. Tensor cores are specialized execution units for supported matrix operations and data types, not a synonym for SMs or CUDA threads.

A workload can be limited by arithmetic throughput, memory bandwidth, memory capacity, launch overhead or communication. A large model may fit in memory but serve poorly at the required concurrency. Conversely, a memory-intensive kernel may not benefit from simply increasing arithmetic parallelism.

For an FDE investigating an inference performance issue:

  1. Establish model, precision, context length, output length, batch mix, GPU topology and latency requirements.
  2. Measure end-to-end throughput, time to first token, inter-token latency, queueing and memory pressure.
  3. Use a system profiler to identify transfers, CPU gaps, launches and synchronization.
  4. Use kernel profiling to examine memory transactions, eligible warps, divergence, register pressure and stalls for the actual bottleneck.
  5. Compare optimized library kernels and serving configurations before implementing a custom kernel.
  6. Validate numerical correctness and the customer-visible workload after changes.

For a multi-GPU deployment, include communication topology, collective operations and parallelism strategy. A single-SM occupancy model cannot predict distributed model throughput. Benchmark representative traffic instead of extrapolating directly from theoretical GPU core counts or advertised peak FLOPS.

9. Common interview mistakes#

  • Confusing a thread block with an SM or assuming one block per SM.
  • Assuming CUDA threads map permanently one-to-one to physical CUDA cores.
  • Assuming all blocks in a grid run simultaneously or in index order.
  • Treating a warp as a programmer-defined block size.
  • Forgetting the bounds check when a launch rounds up the work size.
  • Relying on implicit warp lockstep for synchronization.
  • Placing a block-wide barrier inside nonuniform control flow.
  • Assuming maximum occupancy means maximum performance.
  • Confusing per-thread local memory with fast on-chip memory.
  • Claiming coalescing guarantees one memory transaction on every architecture.

Likely interviewer follow-ups#

How many warps are in a 256-thread block? Eight on NVIDIA hardware with warp size 32.

Can multiple blocks execute on the same SM? Yes, if the SM has enough resources to keep them resident. The actual block scheduling and resource allocation depend on the device and kernel.

Why use block sizes that are multiples of 32? It avoids a partially populated final warp within a block, although register use, shared memory, problem shape and profiling may justify other sizes.

What happens when a warp stalls? The scheduler may select another eligible resident warp. This helps hide latency when enough independent useful work exists.

What if branches diverge? Different active subsets may execute different paths, reducing useful lane utilization. Exact scheduling and predication depend on the compiler and hardware.

Can threads in different blocks synchronize using __syncthreads()? No. It is a block-scoped barrier. Use appropriate kernel boundaries or documented specialized cooperative mechanisms.

Does 100% occupancy guarantee the fastest kernel? No. Occupancy describes resident warp capacity, not useful instruction throughput, memory efficiency or end-to-end latency.

How do you know your kernel is correct and fast? Compare results with a trusted reference, test boundary sizes and synchronization, use CUDA error checking and Compute Sanitizer where available, and measure performance on the target GPU under representative conditions.

Interview takeaway#

The programmer specifies a grid of blocks and logical threads. The GPU assigns ordinary blocks to SMs, groups threads into warps, and schedules eligible warps on execution pipelines. Performance depends on useful parallelism, memory access patterns, synchronization, resource constraints and workload-specific measurements—not on a simplistic one-thread-to-one-core mapping.

Related questions

Explore other topics:AI AgentsAI System DesignLarge Language Models