# CS152 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: - **Which is easiest to program?** ILP requires no parallel programming model at all (you write sequential code and hardware/compilers handle it), while DLP is straightforward on regular array math; TLP is hardest because programmers must explicitly synchronize threads and manage races. - **Which is the most flexible?** **TLP**—independent threads can execute completely unrelated programs or irregular control flow. - **Which is the most efficient** (greatest tasks/second/area and lowest energy/task)? **DLP**—fetching and decoding one instruction drives dozens of parallel arithmetic units simultaneously! 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: - **Programming Model — SPMD (Single Program, Multiple Data):** The programmer writes *one* scalar kernel function and launches thousands of independent **threads** (`CUDA threads` or `microthreads`, `μT`). Every thread executes the exact same program code on different array indices (so the application must possess DLP). - **Microarchitecture — SIMD Vector Processor + Vertical Multithreading:** Because every thread in a group runs the *exact same code*, they can **share a single instruction fetch and decode frontend!** A GPU groups threads into lockstep bundles—**warps** (32 CUDA threads in NVIDIA GPUs)—and maps each warp onto a **vector-like core** where **each thread acts as one SIMD lane** (with a single-issue frontend broadcasting one instruction across $W$ lanes, each with its own register file partition). *On top of* this spatial SIMD execution, the GPU uses **vertical multithreading** across multiple warps on each core to hide memory and functional-unit latencies! *(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: ```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**: ```c // Piece run on host processor __host__ int nblocks = (n + 255) / 256; // 256 CUDA threads per block daxpy<<>>(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? - The GPU contains many parallel **Streaming Multiprocessors (SMs)**—**148 on an NVIDIA B300**—each a **multithreaded SIMD processor** whose lanes are the threads of a warp, backed by **GPU Memory** (about 268 GiB of HBM per B300). - There is no separate scalar CPU core inside an SM, but there is a **uniform datapath**: values that are the same for every thread in a warp (block index, kernel parameters, base addresses) live in **uniform registers** (`UR`) and are computed once per warp. In B300 machine code (SASS), `S2UR UR4, SR_CTAID.X` reads `blockIdx.x` into a uniform register, and `LDCU` / `UIADD3` load and add warp-uniform values. - The CPU sends the entire **Grid** over to the GPU, which distributes **thread blocks** across available SMs (each thread block executes on one SM, so the programmer remains unaware of the exact number of SMs). 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**: - Perform **unit-stride loads and stores** across adjacent `threadIdx` values so **memory coalescing** kicks in. - Avoid **branch divergence** so SIMD execution slots perform useful work rather than getting masked off. #### Handling Conditionals and Branch Divergence (PTX Assembly Walkthrough) What happens when threads inside the *same* warp disagree on an `if-else` branch? - **Simple `if-then-else`** compiles directly to **predicated execution**, identical to vector masking. - **Complex control flow** compiles to branches. Hardware tracks which `μthreads` take or don't take the branch: - If **all threads in the warp agree**, execution continues at full SIMD speed. - If **threads diverge**, the warp runs one path with only the threads that took it active, then the other path with the remaining threads, and the threads **reconverge** at a point the compiler marks with a **convergence barrier**. The cost is the same as any SIMD masking scheme: during divergence, total execution time equals `time(THEN) + time(ELSE)`. **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`**: ```c 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: - **`tcgen05.mma`** multiplies matrix tiles. Its operand form is `tcgen05.mma.cta_group.kind [d_tmem], a_desc, b_desc, idesc, ...`: the **A and B operands are named by shared-memory descriptors** (`a_desc`, `b_desc`), and the **accumulator `D` lives in Tensor Memory** (`[d_tmem]`), not in registers. - **Tensor Memory (TMEM)** is a dedicated per-SM accumulator store of **128 lanes × 512 columns × 32 bits = 256 KB**. Kernels allocate it explicitly with `tcgen05.alloc` in power-of-2 chunks of 32 to 512 columns, and move data with `tcgen05.ld` / `tcgen05.cp`. TMEM adds another 256 KB of fast storage per SM, the same size as the register file, and keeps large accumulator tiles out of the registers that warps need for everything else. - **`cta_group::1` or `cta_group::2`**: one MMA can be issued for a single thread block, or for a **pair of blocks on two SMs** cooperating on one larger tile. - **Supported formats on B300 (`sm_103a`)**: `kind::f16`, `kind::tf32`, `kind::f8f6f4`, and the block-scaled microscaling kinds `kind::mxf8f6f4`, `kind::mxf4`, and `kind::mxf4nvf4`. **No `kind::i8` (INT8)**: it exists on the B200 (`sm_100a`) but not on the B300. #### 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`.