Lecture 20: GPU

Section 1: Data-Level Parallelism and the GPU/SIMT Architecture

We have now seen all three major classes of hardware parallelism:

  1. Instruction-Level Parallelism (ILP): Execute independent instructions from one instruction stream in parallel (pipelining, superscalar, VLIW).
  2. Thread-Level Parallelism (TLP): Execute independent instruction streams in parallel (multithreading, multi-core).
  3. Data-Level Parallelism (DLP): Execute multiple operations of the same type on different data elements in parallel (vector/SIMD execution).

Compare them across three engineering criteria:

Today’s resurgence of DLP is driven by applications—graphics, machine vision, speech recognition, and machine learning—whose core workloads are massive, trivially data-parallel numerical computations.

From Graphics Pipelines to GP-GPUs

Original GPUs (mid-to-late 1990s) were fixed-function 3D rendering devices packed with high-performance floating-point units that users could configure, not program. Between 2001 and 2005, GPUs added programmable vertex and pixel shaders (using languages like Cg and DirectX), exposing massive parallelism (millions of vertices or pixels per frame) through a heavily constrained graphics model. Clever programmers realized they could disguise general-purpose matrix math as textures and shaders—painful to code, but remarkably fast.

In 2006–2007, NVIDIA introduced the GeForce 8800 and CUDA (Compute Unified Device Architecture, followed by vendor-neutral OpenCL), turning the GPU into a General-Purpose GPU (GP-GPU): an attached processor model where a Host CPU dispatches data-parallel computational kernels to the GP-GPU for execution.

GPGPUs in a Nutshell: SPMD Meets SIMD + Multithreading

A student seeing GPUs for the first time often thinks a GPU is a multi-core CPU with thousands of independent out-of-order cores. That misconception misses the entire hardware secret of a GPU! Look at the two-level abstraction:

(As a weaving metaphor: the warp consists of the parallel threads running lengthwise in lockstep, while the weft represents the sequence of instructions stepping across them.)

Worked Example: DAXPY in C vs. CUDA

Consider the classic vector operation DAXPY (y[i] = a \cdot x[i] + y[i]):

In sequential C:

void daxpy(int n, double a, double *x, double *y) {
    for (int i = 0; i < n; i++)
        y[i] = a * x[i] + y[i];
}

In CUDA, we split execution between the host CPU and the device GPU:

// Piece run on host processor
__host__
int nblocks = (n + 255) / 256;       // 256 CUDA threads per block
daxpy<<<nblocks, 256>>>(n, 2.0, x, y);

// Piece run on GP-GPU (executed by EVERY microthread)
__device__
void daxpy(int n, double a, double *x, double *y) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) y[i] = a * x[i] + y[i];
}

Let’s trace what happens for, say, n = 1000:

  1. The host computes \text{nblocks} = (1000 + 255) / 256 = 4 thread blocks, each containing blockDim = 256 threads (threadId 0..255), forming a 1D (or 2D) Grid of 4 \times 256 = 1024 threads.
  2. Each thread computes its global element index i = \text{blockIdx.x} \times 256 + \text{threadIdx.x} (for example, Block 3 Thread 200 gets i = 3 \times 256 + 200 = 968).
  3. For the last block (blockIdx = 3), indices i = 1000..1023 fail the conditional if (i < n), safely turning off the 24 unused threads!

Hardware Execution Model and Implications of SIMT

How does hardware execute that CUDA Grid?

Notice two subtle inefficiencies created by this SIMT (Single Instruction, Multiple Thread) illusion of independent scalar threads:

  1. Scatter-Gather Memory & Coalescing: Because every μthread issues its own scalar load/store (ld x, (z)), every GPU memory instruction is logically a scatter-gather! To avoid crippling DRAM bandwidth, the GPU adds dynamic memory coalescing hardware that inspects the addresses of all 32 μthreads in a warp and merges contiguous (unit-stride) accesses into wide vector cache-line transfers.
  2. Redundant Stripmining: Because there is no scalar control processor running the loop bounds, every single μthread must redundantly compute i = blockIdx.x * blockDim.x + threadId.x and evaluate if (i < n) (“am I active?”).

✎ Check Your Understanding

  1. If a GPU kernel launches with 128 threads per block (blockDim.x = 128) on an array of n = 300 elements, how many thread blocks are in the Grid, and how many threads in the final block will be deactivated by if (i < n)? Answer: \lceil 300 / 128 \rceil = \mathbf{3} thread blocks (384 total threads). The final block handles indices 256..383, so 383 - 299 = \mathbf{84} threads will be turned off by if (i < n).

  2. Why do GPUs require dynamic memory coalescing hardware whereas traditional vector processors (like the Cray-1) did not? Answer: A traditional vector processor has explicit unit-stride and strided vector load/store instructions in its ISA. In SIMT, every μthread executes its own scalar load/store instruction, so hardware must inspect all threads in a warp at runtime and coalesce contiguous scalar addresses into a single wide memory access.


Section 2: GPU Warp Scheduling, Memory Hierarchy, Branch Divergence, and Real Cores

Inside a single SM, one warp of 32 μthreads acts as a single hardware thread. A single CUDA thread block can contain up to 1,024 threads (32 warps), and on a B300 one SM can hold up to 2,048 resident threads (64 warps) from up to 32 blocks at once. Because an SM has zero out-of-order speculation to hide DRAM latency, the SIMT multithreaded instruction scheduler switches vertically among ready warps every cycle (warp 8 inst 11 \to warp 1 inst 42 \to warp 3 inst 95 \to warp 8 inst 12…), keeping the SIMD lanes 100% busy while waiting warps stall on DRAM loads or long-latency math!

GPU Memory Hierarchy and SIMT Efficiency Rules

The GPU exposes a three-tier memory hierarchy matching the CUDA execution hierarchy:

  1. Per-thread private local memory (register spill/private stack per μthread).
  2. Per-block shared memory (fast on-chip scratchpad memory shared among all threads within one Thread block, enabling fast cooperation without going to off-chip DRAM).
  3. Per-application global memory (large off-chip DRAM visible across all thread blocks and grids).

To get high performance out of SIMT hardware, the programmer cannot treat μthreads as truly independent—they must keep μthreads aligned in a SIMD fashion:

Handling Conditionals and Branch Divergence (PTX Assembly Walkthrough)

What happens when threads inside the same warp disagree on an if-else branch?

DAXPY in PTX (Parallel Thread Execution, NVIDIA’s virtual ISA), parameter loads trimmed:

mov.u32            %r3, %ctaid.x;          // blockIdx.x
mov.u32            %r4, %ntid.x;           // blockDim.x
mov.u32            %r5, %tid.x;            // threadIdx.x
mad.lo.s32         %r1, %r3, %r4, %r5;     // i = blockIdx.x * blockDim.x + threadIdx.x
setp.ge.s32        %p1, %r1, %r2;          // i >= n ?
@%p1 bra           $L__BB0_2;              // inactive threads skip the body
cvta.to.global.u64 %rd3, %rd1;
cvta.to.global.u64 %rd4, %rd2;
mul.wide.s32       %rd5, %r1, 8;           // byte offset = i * 8
add.s64            %rd6, %rd3, %rd5;
ld.global.f64      %fd2, [%rd6];           // x[i]
add.s64            %rd7, %rd4, %rd5;
ld.global.f64      %fd3, [%rd7];           // y[i]
fma.rn.f64         %fd4, %fd1, %fd2, %fd3; // a * x[i] + y[i], one fused multiply-add
st.global.f64      [%rd7], %fd4;           // y[i] = ...
$L__BB0_2:
ret;

The redundant stripmining from Section 1 is visible here: every thread computes i with mad.lo and tests i < n itself.

Now a divergent if-else:

if (X[i] != 0)
    X[i] = X[i] - Y[i];
else
    X[i] = Z[i];

Its PTX is ordinary branching; nothing in it mentions masks or reconvergence:

ld.global.f64  %fd1, [%rd1];               // X[i]
setp.eq.f64    %p2, %fd1, 0d0000000000000000;
@%p2 bra       $L__BB1_3;                  // X[i] == 0 -> else path
ld.global.f64  %fd3, [%rd12];              // then: Y[i]
sub.f64        %fd4, %fd1, %fd3;
st.global.f64  [%rd1], %fd4;
bra.uni        $L__BB1_4;
$L__BB1_3:
ld.global.f64  %fd2, [%rd9];               // else: Z[i]
st.global.f64  [%rd1], %fd2;
$L__BB1_4:
ret;

Reconvergence is added when the driver/assembler lowers PTX to SASS. For a version of this kernel that does shared work after the if-else (so the threads must rejoin), the B300 SASS brackets the divergent region with a barrier pair:

/*00c0*/  BSSY.RECONVERGENT B1, 0x1b70 ;      // open barrier B1; rejoin point is 0x1b70
/*00d0*/  DSETP.NEU.AND P0, PT, R24, RZ, PT ;  // per-thread predicate: X[i] != 0
/*00e0*/  @P0 BRA 0xe40 ;                      // threads with P0 jump to the other path
          ...                                  // the two paths (with nested B0/B2 barriers for their loops)
/*1b60*/  BSYNC.RECONVERGENT B1 ;              // wait here until every thread that entered B1 arrives
/*1bc0*/  STG.E.64 desc[UR6][R6.64], R24 ;     // shared code: X[i] = x, all threads together

BSSY opens a convergence barrier (B1) and names the rejoin address (0x1b70); the paths run in between; BSYNC B1, placed immediately before that address, is where the region’s threads meet before the shared store runs for the whole warp. Nested regions use more barrier registers: the loops inside each path above open and close their own B0 and B2 barriers.

A Real GPU: NVIDIA Blackwell B300

Resource B300 value
Compute capability 10.3 (sm_103)
Streaming Multiprocessors (SMs) 148
Registers per SM 65,536 × 32-bit (256 KB)
Max resident threads per SM 2,048 (64 warps), from up to 32 blocks
Max threads per block 1,024 (32 warps)
Shared memory per SM 228 KiB (233,472 B); up to 227 KiB for one block
L2 cache 126.5 MiB (132,644,864 B)
HBM about 268 GiB (275,040 MiB), 7,680-bit memory interface
Max SM clock 2,032 MHz
Board power limit 1,100 W

65,536 registers per SM is far larger than any CPU’s physical register file, because the SM keeps up to 64 warps resident and switches among them every cycle with zero save/restore. Every resident thread owns its registers for its whole lifetime, so the register file, not the ALUs, often limits how many warps fit: a kernel using 64 registers per thread fits 65{,}536 / 64 = 1{,}024 threads (32 warps) per SM, half the 2,048-thread maximum.

Tensor Cores and Tensor Memory

Dense matrix math on a B300 runs on tensor cores, driven by the tcgen05 family of PTX instructions:

Many GPUs in One Node

A B300 node holds 8 GPUs connected all-to-all by NVLink, each with 18 NVLink links into a switched fabric, so every pair of GPUs talks over NVLink directly. The host CPU still launches kernels and moves data, but the GPU-to-GPU traffic of a large model (tensor-parallel all-reduces, expert-parallel all-to-alls) travels over NVLink without touching the CPU.

[Editor Note: removed blank transition slide, NVIDIA stock-price screenshot, and acknowledgements slide.]

✎ Check Your Understanding

  1. A B300 SM has 65,536 32-bit registers and holds at most 2,048 threads. If a kernel uses 128 registers per thread, how many warps can be resident on one SM, and why does the SM need such a large register file at all? Answer: 65{,}536 / 128 = 512 threads, i.e. 16 warps (a quarter of the 64-warp maximum). The register file is large because vertical multithreading keeps every resident warp’s state on chip, so the scheduler can switch warps every cycle with zero save/restore.

  2. In the divergent if-else example, if 31 threads in a 32-thread warp take the THEN path and 1 thread takes the ELSE path, how many paths does the warp execute, and where do the threads rejoin in the B300 SASS? Answer: Both paths, one after the other, each with only its own threads active, so lane efficiency drops roughly in half for the region. The threads rejoin at the BSYNC.RECONVERGENT B1 that closes the barrier opened by BSSY.RECONVERGENT B1, just before the shared code after the if-else.