Phase 02/How a GPU executes work/CUDA thread hierarchy
PHASE 02 · How a GPU executes work

CUDA thread hierarchy

0%
6 h5 subtopics2 lessons · 2 required
In plain English

Imagine organising a national census. You cannot tell each of a million counters what to do individually, so you organise them into teams, give each team a numbered district, and give each person a numbered seat in the team. Every counter then works out which houses to visit from just two numbers, their team number and their seat number. CUDA does the same with threads. You write one small program, launch it once, and tell the GPU "run this with so many teams of so many threads". Each thread computes its own position from its team (block) and seat (thread) index and handles its own slice of the data. Underneath, the hardware actually marches threads in groups of 32 called warps, and those 32 must agree on what instruction to run next or they slow each other down.

Why it matters

Every CUDA, Triton and FlashAttention kernel you will later read is organised around blocks and warps. Choosing block sizes, understanding why a branch inside a warp is expensive, and mapping thread indices to tensor coordinates are daily tasks for an inference kernel engineer.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Cohere, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Compute a global thread index from blockIdx, blockDim and threadIdx in 1D and 2D.
  • Explain what a warp is and why warp divergence costs time.
  • Choose a grid and block size for a given problem size and justify the choice.
  • Describe which resources are shared within a block and which are per-thread.

Key concepts

Thread
One instance of the kernel function with its own registers and index.
Thread block
A group of up to 1024 threads that run on the same SM and can share memory and synchronise.
Grid
The full set of blocks launched by one kernel call; blocks are independent and scheduled in any order.
Warp
32 consecutive threads of a block that the hardware executes together in SIMT fashion.
Warp divergence
When threads in one warp take different branches, the warp executes both paths serially with some threads masked off.
Grid-stride loop
A pattern where each thread handles several elements spaced gridDim.x * blockDim.x apart, decoupling grid size from data size.

Subtopics

  1. 1. Threads, blocks and grids

    The three-level hierarchy, the built-in variables threadIdx, blockIdx, blockDim, gridDim, and 1D/2D/3D indexing.

  2. 2. Mapping indices to data

    Deriving idx = blockIdx.x * blockDim.x + threadIdx.x; row-major 2D indexing; guarding against out-of-range threads.

  3. 3. Warps and SIMT execution

    Why 32, how a warp scheduler issues instructions, what happens on a divergent branch, and why bounds checks on the last block are cheap.

  4. 4. Block scheduling and occupancy

    How blocks are assigned to SMs, limits on resident blocks and warps, and how register and shared memory use reduce occupancy.

  5. 5. Choosing launch configurations

    Multiples of 32, typical 128-256 threads per block, grid-stride loops, and when to use 2D blocks.

Resources

documentation
tutorial

Hands-on lessons

L1

Simulate the thread hierarchy in NumPy

CPU · your Macscript60 minrequired

Goal · A pure-Python "fake CUDA" that runs a kernel function over a grid of blocks and threads, including warp grouping and a divergence counter.

  1. 1Write launch(kernel, grid_dim, block_dim, *args) that loops over every (blockIdx, threadIdx) pair and calls kernel with those indices.
  2. 2Implement a vector-add kernel using idx = blockIdx * blockDim + threadIdx with a bounds guard; verify against numpy.
  3. 3Group the threads of each block into warps of 32 and record, per warp, whether all threads took the same branch in an if statement.
  4. 4Write a kernel with if idx % 2 == 0 and another with if idx < n/2; count divergent warps for each and explain the difference.
  5. 5Implement a 2D launch and a matrix transpose kernel; verify against numpy .T.
  6. 6Add a grid-stride loop variant and show it gives the same result with gridDim smaller than n / blockDim.
Deliverable
fake_cuda.py with the launcher, three kernels and printed divergence statistics.
Check
Vector add and transpose match numpy exactly; the idx % 2 kernel reports 100 percent divergent warps and the idx < n/2 kernel reports at most one divergent warp.
L2

Launch real kernels with numba.cuda and measure divergence

Colab T4 · freenotebook75 minrequired

Goal · Run vector add on a T4 with several block sizes and measure the slowdown caused by intra-warp divergence.

  1. 1On a Colab T4, write a numba @cuda.jit vector-add kernel using cuda.grid(1) and a bounds check.
  2. 2Launch with block sizes 32, 64, 128, 256, 512, 1024 for n = 1e7; time each with cuda.synchronize() and plot.
  3. 3Write a kernel where even and odd threads do different arithmetic (divergent) and one where even and odd warps differ (non-divergent); time both.
  4. 4Print cuda.get_current_device() attributes such as MULTIPROCESSOR_COUNT, MAX_THREADS_PER_BLOCK and WARP_SIZE.
  5. 5Convert one kernel to a grid-stride loop and show the runtime is unchanged with a grid of only 2 x SM_count blocks.
Deliverable
Notebook with the block-size plot and the divergent versus non-divergent timing table.
Check
Block size 32 is measurably slower than 128-256; the divergent kernel is slower than the warp-aligned kernel by a clear margin (typically 1.3x or more).
Fallback
Run the same code on Kaggle, or fall back to lesson l1 and reason about the expected result.

Build your own

Build your own thread-index visualiser and vector ops

CUDA C++Colab T4 · free~5 h

Real CUDA kernels on a Colab T4 that dump their own indices into an image, then vector add, SAXPY, dot and transpose with bounds guards and grid-stride loops, verified against numpy.

The real thing: github.com/NVIDIA/cuda-samples/tree/master/cpp/0_Introduction/vectorAdd ↗

How you know a stage passes

Each stage is a .cu file compiled with `nvcc -arch=sm_75 -O3` on a Colab T4 and run by `bash run.sh sN`, which executes the binary, writes its outputs as .npy or CSV, and then calls tests/check.py to compare against numpy and assert the timing relationships. A stage is done when run.sh exits 0. On a CPU-only day the same kernels can be dry-run through fake_cuda.py from lesson l1 to check the index logic.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01every thread writes down who it is
    A kernel where each thread records blockIdx, threadIdx, warp id, lane id and global index into a device array that the host copies back and dumps as CSV.
    test · For grid 4 and block 96 the CSV has 384 rows, the global indices are a permutation of 0..383, and lane equals threadIdx.x % 32 on every row.
  2. 02render the grid
    A Python script turns the CSV into an image where each pixel is a thread coloured by block and shaded by warp, for 1D and 2D launches.
    test · A 2D launch with grid (4,4) and block (16,16) renders a 64x64 image containing 16 distinct block colours and 8 warp stripes per block; check.py asserts the colour counts.
  3. 03vector add with a bounds guard
    An add kernel that handles n not divisible by the block size without writing past the end of the array.
    test · n = 1,000,003 with 256 threads per block gives max abs error 0 against numpy and the 64 canary floats placed after the output buffer are unchanged.
  4. 04grid-stride loop with a fixed grid
    The same kernel processes any n with gridDim fixed at 2 x SM count (80 blocks on a T4) by looping with stride gridDim.x * blockDim.x.
    test · Outputs are identical to s3 for n in 1, 1000, 1e7 and 1e8; with CUDA events the 80-block grid-stride launch is within 10 percent of the one-thread-per-element launch at n = 1e8.
  5. 05SAXPY, dot product and 2D transpose
    SAXPY, a dot product (per-block shared-memory tree then one atomicAdd per block) and a 4096 x 4096 transpose using 2D blocks of 16 x 16 with 2D index arithmetic.
    test · SAXPY and transpose match numpy exactly; dot is within 1e-4 relative error of a float64 numpy dot over 1e7 elements.
  6. 06measure warp divergence
    Two kernels doing the same arithmetic, one branching on thread parity (divergent inside each warp) and one on warp parity (uniform per warp), timed with CUDA events and written to a table.
    test · The intra-warp divergent kernel is at least 1.3x slower than the warp-uniform kernel at n = 1e7 and the table is in the README.

Knowledge check

QHow many warps are in a block of 200 threads, and how many threads in the last warp do real work?

7 warps (224 threads allocated); the last warp has 8 active threads and 24 idle lanes.

QWrite the global index for a 1D launch.

idx = blockIdx.x * blockDim.x + threadIdx.x, followed by if (idx < n) to guard the tail.

QWhy is the bounds check on the last block nearly free even though it is a branch?

Only the final warp can diverge on it; all other warps take the same path, so no serialisation occurs.

QCan two thread blocks communicate during a kernel?

Not directly; blocks are scheduled independently and may run on different SMs. Communication happens through global memory, usually across kernel launches.

Completion

  • All 5 subtopics marked done
  • All 2 required lessons done
  • All five subtopics marked completed.
  • fake_cuda.py and the numba notebook both saved with checks passing.
  • Can state the index formula and the warp size from memory.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →