Lecture 7 · GPU Architecture and CUDA Programming

Parallel Computing · Lecture 07。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: Stanford CS149 Fall 2025, Lecture 7 (Oct 14), slide deck 07_gpuarch (74 slides). Context for Programming Assignment 3. Sources: the public Fall 2025 slides; the 2023 lecture video; NVIDIA’s CUDA C++ Programming Guide; Apple’s Metal documentation. The author’s machine has no NVIDIA GPU, so the CUDA kernels run on a SIMT simulator written for these notes, and the same kernels run on the author’s Apple M4 Pro GPU through Metal. All numbers below come from those runs (macOS 27, Swift 6.3). Code: code/lecture07/. Reading time: ~80 minutes for the prose; ~15 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Explain how GPUs grew from fixed-function graphics hardware into throughput processors (吞吐量处理器), and why a shader, “a pure function over a stream of inputs”, invited data-parallel computing.
  2. Write a CUDA kernel and launch it over a grid (网格) of thread blocks (线程块): compute global indices from blockIdx, blockDim and threadIdx; round the grid up and guard against out-of-bounds threads.
  3. Use CUDA’s memory model: host (主机) vs. device (设备) memory and cudaMemcpy; per-block shared memory (共享内存); per-thread local memory; __syncthreads() and atomics (原子操作).
  4. Explain how a GPU implements these abstractions: a compiled kernel records its resource needs; a block scheduler places whole blocks on SMs (流式多处理器); threads run in warps (线程束) of 32 in SIMT (单指令多线程) fashion; warps are interleaved to hide latency.
  5. Reason about cost: coalesced (合并) vs. scattered loads, shared-memory bank conflicts (存储体冲突), divergence (分支发散), and occupancy (占用率).
  6. Explain why a block’s threads must all be resident at once, why blocks must not wait for each other, and what the “persistent threads” style trades away.

0.2 Prerequisites and scope

  • Prerequisites: Lecture 2 (SIMD, masks and divergence, hardware multi-threading, “how many threads hide a latency”), Lecture 3 (ISPC gangs and tasks, bandwidth-bound kernels), Lecture 5 (pools of workers pulling tasks), Lecture 6 (locality, arithmetic intensity).
  • Scope: the CUDA programming model and how NVIDIA GPUs implement it, using the V100 as the running example. Tensor cores and the newest features (TMA, thread-block clusters) are Lectures 10–11. Programming Assignment 3 asks you to write CUDA programs (a scan, then a circle renderer); these notes teach the ideas and do not solve the assignment.

0.3 Section → code map

SectionIdeaDemo in code/lecture07/
§3.2–§3.3the thread hierarchy; rounding up and guarding01_cuda_basics.py
§3.51D convolution, global vs. shared memory02_convolution.py, convolve.cu
§4warps: coalescing, bank conflicts, divergence04_memory_and_divergence.py
§5–§6block scheduling, occupancy, block independence, persistent threads03_block_scheduling.py
§7the same kernels on a real GPU05_metal_convolution.swift

Run them all with cd code/lecture07 && make run (~5 seconds). The simulator is simt.py; its docstring explains how to write kernels for it.

0.4 Notation

  • CUDA’s names are used throughout: CUDA thread, thread block, grid, warp, SM. Metal’s names for the same things appear only in §7 (threadgroup = block, SIMD-group = warp, threadgroup memory = shared memory).
  • “Sector” = 32 bytes, the unit in which NVIDIA GPUs move data between caches and DRAM; a 128-byte cache line holds 4 sectors.

1. Why GPUs became parallel computers

1.1 What GPUs were built for: real-time 3D rendering

Slides 5–12. The input to rendering (渲染) is a description of a scene: surfaces made of triangles (each triangle three vertices), materials, lights and a camera. The output is an image. The workload, in one slide (10):

  • for each triangle, determine where it lies on screen, given the camera;
  • for every output pixel covered by the triangle, compute the colour of the surface at that pixel.

The colour computation is the expensive and varied part: real materials and lights are enormously diverse (slides 11–12). So GPUs made it programmable. A shader (slide 13, in the GLSL language) is a small function run once per pixel (“fragment”) covered by a triangle. It reads per-pixel inputs (a texture coordinate, a surface normal) and read-only globals (a texture, a light direction), and returns that pixel’s colour. The key property, in the slide’s words: a shader is a pure function invoked on a stream of inputs. No shader invocation depends on another, so all of them can run in parallel.

Hence the architecture (slide 15): many SIMD, multi-threaded cores, the design Lecture 2 built step by step, plus high-bandwidth memory (~1 TB/s on high-end GPUs today) to feed them.

1.2 GPGPU: abusing a graphics pipeline

Around 2001–2003 people noticed (slide 16) that GPUs were very fast at running the same computation over large collections of data, and getting faster every year, since more transistors meant more parallelism. That sounds like the data-parallel supercomputers of the 1990s.

The hack (slide 17): to run a function on every element of a 512 × 512 array, set the output image size to 512 × 512 and draw two triangles that exactly cover the screen. The “fragment shader” then runs once per pixel, i.e. once per array element. That is a map over a 2D collection. Researchers built fluid simulations, ray tracers and sparse solvers this way: GPGPU, general-purpose computing on GPUs (slide 18).

Brook (2004, Stanford, slide 19) abstracted the GPU as a data-parallel stream processor. You wrote kernel void scale(float amount, float a<>, out float b<>) { b = amount * a; } and called it on streams; the compiler translated the program into graphics commands and shaders. Its lead author, Ian Buck, went on to lead CUDA at NVIDIA.

1.3 Compute mode

Before 2007 the only interface to a GPU was the graphics pipeline (slide 22): give the GPU shader binaries, pipeline parameters and a buffer of vertices, then send “draw”. The hardware could only run graphics pipeline computations.

NVIDIA’s Tesla architecture (2007) added a non-graphics compute mode interface (slide 23):

  • the application can allocate buffers in GPU memory and copy data to and from them;
  • the application provides a single kernel program binary;
  • the application tells the GPU to run the kernel in an SPMD fashion: launch(myKernel, N), “run N instances of this kernel”.

This is a far simpler operation than drawPrimitives(). CUDA (slide 24) is the C-like language introduced with it. Its design goal was a low abstraction distance: CUDA’s abstractions closely match the capabilities and performance characteristics of the hardware. That is why understanding the implementation (§4–§6) is part of programming CUDA well.


2. Questions to keep in mind

Slide 25 asks you to keep these open while reading:

  • Is CUDA a data-parallel model? Shared address space? Message passing?
  • Can you draw analogies to ISPC instances and tasks? To pthreads?

And slide 26’s warning: a CUDA thread presents an abstraction like a pthread, a logical thread of control with its own program counter and variables, but its implementation is very different. A CUDA thread is not an OS thread, has no stack of its own in the usual sense, and costs almost nothing to create. §4 explains what it really is.


3. CUDA programming abstractions

3.1 The plan of a CUDA program

A CUDA program has two parts (slides 28–31):

  • host code: ordinary C++ running serially on the CPU;
  • device code: kernel functions, marked __global__, which run on the GPU in SPMD fashion. Helper functions callable from kernels are marked __device__ (slide 29). The separation is static: the programmer decides which code runs where.

A launch kernel<<<numBlocks, threadsPerBlock>>>(args) is a bulk launch of many CUDA threads, and the call does not complete until all of them have terminated. (Strictly, the launch is asynchronous on the CPU side; the next CUDA call that needs the results waits for it.)

3.2 A hierarchy of threads

Slides 27–28: threads are grouped into thread blocks, and the blocks form a grid. Both can be 1D, 2D or 3D (dim3), which is convenient for naturally 2D or 3D problems:

const int Nx = 12, Ny = 6;
dim3 threadsPerBlock(4, 3);
dim3 numBlocks(Nx / threadsPerBlock.x, Ny / threadsPerBlock.y);   // (3, 2)
matrixAdd<<<numBlocks, threadsPerBlock>>>(A, B, C);               // 72 CUDA threads

__global__ void matrixAdd(float A[Ny][Nx], float B[Ny][Nx], float C[Ny][Nx]) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    int j = blockIdx.y * blockDim.y + threadIdx.y;
    C[j][i] = A[j][i] + B[j][i];
}

Each thread computes its overall position from its block’s position in the grid (blockIdx), the block size (blockDim) and its own position in the block (threadIdx). 01_cuda_basics, Part A runs exactly this on the simulator: 6 blocks of 12 threads, 72 threads, and C = A + B.

3.3 The number of threads is explicit

Slide 30 points out a difference from graphics shading: a kernel launch is not map(kernel, collection). The program states the number of threads, and nothing forces it to match the data. If Nx = 11 and Ny = 5 are not multiples of the block size, you round the grid up and guard every access:

dim3 numBlocks((Nx + threadsPerBlock.x - 1) / threadsPerBlock.x,
               (Ny + threadsPerBlock.y - 1) / threadsPerBlock.y);
...
if (i < Nx && j < Ny)          // guard against out-of-bounds array access
    C[j][i] = A[j][i] + B[j][i];

Demo 01, Part B: 72 threads for 55 elements; the guard idles the extra 17. Without the guard, the simulator stops at A[55] is out of bounds. A real GPU does not check: the access silently reads or corrupts other data, or crashes the kernel. NVIDIA’s compute-sanitizer finds such bugs.

3.4 The memory model

Slides 32–34. The host and the device have distinct address spaces. Data moves between them with explicit copies:

float* A = new float[N];                     // host memory
float* deviceA;
cudaMalloc(&deviceA, bytes);                 // device ("global") memory
cudaMemcpy(deviceA, A, bytes, cudaMemcpyHostToDevice);
// deviceA[i] is INVALID on the host: deviceA does not point into the host's address space

Slide 33 asks what cudaMemcpy reminds you of: message passing (Lecture 6), with explicit copies between private address spaces.

Inside the device, a kernel sees three kinds of address space (slide 34):

memoryvisible tolifetimeimplementation
per-thread local (private)one threadthe threadregisters (spills to device memory)
per-block sharedthe threads of one blockthe blockfast on-chip SRAM in the SM
device globalall threads (and copies from the host)the programDRAM (HBM), cached in L2/L1

The different address spaces reflect different regions of locality in the program. Slide 34’s question: how would you schedule threads if you knew in advance that certain threads access the same variables? Put them on the same core, close to the same fast memory. That is exactly what a thread block is.

3.5 Example: 1D convolution, two versions

Slide 35: output[i] = (input[i] + input[i+1] + input[i+2]) / 3.f.

Version 1 (slide 36): one thread per output element; each thread loads its three inputs from global memory.

#define THREADS_PER_BLK 128
__global__ void convolve(int N, float* input, float* output) {
    int index = blockIdx.x * blockDim.x + threadIdx.x;   // thread-local variable
    float result = 0.0f;                                 // thread-local variable
    for (int i = 0; i < 3; i++)
        result += input[index + i];
    output[index] = result / 3.f;
}
convolve<<<N / THREADS_PER_BLK, THREADS_PER_BLK>>>(N, devInput, devOutput);

Each input value is loaded by three different threads. Version 2 (slide 37) loads each once per block:

__shared__ float support[THREADS_PER_BLK + 2];           // per-block allocation
int index = blockIdx.x * blockDim.x + threadIdx.x;
support[threadIdx.x] = input[index];                     // all threads cooperate ...
if (threadIdx.x < 2)
    support[THREADS_PER_BLK + threadIdx.x] = input[index + THREADS_PER_BLK];
__syncthreads();                                         // barrier: all threads in the block
float result = 0.0f;
for (int i = 0; i < 3; i++)
    result += support[threadIdx.x + i];
output[index] = result / 3.f;

All threads of the block cooperatively load its “support” region from global memory into shared memory: 130 load instructions instead of 3 × 128. The barrier ensures nobody reads support before it is complete.

02_convolution runs both on the simulator (16,384 outputs; a small GPU with 4 SMs; global latency 300 cycles):

versionL1 cacheloads per block (thread / warp instr.)sectors loaded from DRAMshared instr.cycles
v1 (global only)none384 / 127,16804,699
v2 (shared memory)none130 / 52,1762,1763,701
v116 KiB per SM384 / 122,56002,900
v216 KiB per SM130 / 52,5602,1763,710

Without a cache, version 1 loads 3.3× the sectors and takes 1.27× the cycles: shared memory is a program-managed cache. With a hardware L1, version 1’s repeated loads hit in the cache, both versions move the same DRAM traffic, and version 1 is now faster, because version 2 still pays its barrier and extra instructions. Keep this in mind for §7, where the real GPU gives the same answer.

3.6 Synchronization

Slide 38 lists CUDA’s synchronization constructs:

  • __syncthreads(): a barrier for all threads of one block. (There is no barrier across blocks inside a kernel; see §6.)
  • Atomic operations, e.g. float atomicAdd(float* addr, float amount), on both global and shared memory.
  • Host/device synchronization: an implicit barrier across all threads when the kernel returns.

3.7 Summary of the abstractions

Slide 39:

  • Execution: a thread hierarchy. A bulk launch of many threads (to be made precise in §5), grouped two levels deep into blocks.
  • A distributed address space: built-in memcpy between host and device, plus three device address spaces (per thread, per block “shared”, per program “global”).
  • Barrier synchronization for the threads of a block, and atomics for additional synchronization on shared and global variables.

Slide 25’s questions can now be answered. Within a block, CUDA is SPMD with a shared address space: threads cooperate through shared memory, barriers and atomics. Across blocks it is in the spirit of the data-parallel model: blocks are independent and may run in any order (§5). Between host and device it looks like message passing: separate address spaces and explicit copies.


4. How CUDA threads really run: warps and SIMT

4.1 Not a million pthreads

Slide 40: version 2 launches over a million CUDA threads in over 8K blocks. Does that create a million stacks and 8K copies of support? Compare pthread_create, which allocates a stack and a control block so the OS can schedule the thread. If CUDA threads worked that way, the launch alone would take seconds. The rest of the lecture explains why they do not.

4.2 Inside an SM: the NVIDIA V100

Slides 45–53 open up one streaming multiprocessor (SM) of the V100 (2017):

  • An SM has 4 sub-cores. Each has a warp selector, a fetch/decode unit, 16 fp32 multiply-add units, 16 int32 units, 8 fp64 units, load/store units and tensor cores (Lecture 10), plus a 64 KB register file. The whole SM has 256 KB of registers.
  • A warp (slides 46–47): a group of 32 threads of a block, threads 0–31, 32–63, and so on. A block of 256 threads is mapped to 8 warps. Each sub-core can schedule and interleave up to 16 warps, so an SM holds up to 64 warps (2,048 threads). Their registers all live in the register file at once; that is the “execution context storage” of Lecture 2.
  • Instruction execution (slides 48–49): each clock, each sub-core’s warp selector picks one runnable warp and issues its next instruction. That instruction runs for all 32 threads of the warp. With 16 fp32 units, a 32-wide warp instruction takes 2 clocks.
  • SIMT (slides 48, 54): threads in a warp are executed in a SIMD manner if they share the same instruction. NVIDIA calls this single instruction, multiple thread. If the 32 threads do not share the same instruction, they execute divergently, with some lanes masked off. This is like an ISPC gang, with one crucial difference (slide 48’s footnote): the CUDA program is not compiled to SIMD instructions. Each CUDA thread runs a scalar instruction stream, and the hardware checks dynamically whether the threads of a warp are at the same instruction.
  • A warp is not part of CUDA (the programming model). It is an implementation detail, but an important one. (Exceptions: intra-warp built-ins such as shuffle and vote.)

V100 geometry (slide 53): 1.245 GHz, 80 SMs, 80 × 4 × 16 = 5,120 fp32 mul-add ALUs = 12.7 TFLOP/s (counting a mul-add as 2 FLOPs), up to 80 × 64 = 5,120 interleaved warps = 163,840 CUDA threads, 6 MB of L2 cache, and 16 GB of HBM at 900 GB/s (slide 52).

Why so many warps? Lecture 2’s answer: hardware multi-threading hides latency. A warp waiting hundreds of cycles for memory is simply not selected; one of the other 15 on the sub-core runs. Lecture 2’s formula, threads needed ≈ 1 + latency / (work between misses), explains why a GPU wants tens of warps per sub-core.

4.3 What one warp instruction costs

Because 32 threads execute each instruction together, the cost of a memory instruction depends on which addresses the 32 threads choose. 04_memory_and_divergence measures three consequences on the simulator.

Coalescing. The memory system moves data in 32-byte sectors. If the 32 threads of a warp load 32 neighbouring floats, one instruction needs exactly 4 sectors (128 bytes). Stride the accesses and the same instruction needs more:

dst[i] = src[i * stride]examplesectors per warp loadbytes moved per byte used
stride 1float array41
stride 2real parts of complex numbers82
stride 4field x of struct {x, y, z, w}164
stride ≥ 8a column of a matrix328

This is Lecture 6’s “minimum granularity of transfer”, at GPU scale. It makes “array of structs vs. struct of arrays” a performance decision: store each field in its own array, so that thread i reading field x of element i is coalesced.

Shared-memory bank conflicts. Shared memory is divided into 32 banks, each 4 bytes wide; word k lives in bank k mod 32. A warp’s shared access completes in one pass if its 32 addresses fall in 32 different banks, or several threads read the same word (a broadcast). Otherwise it is split into as many passes as the most-used bank has distinct words. Transposing a 32 × 32 tile through shared memory reads a column: 32 words, 32 apart, all in one bank, so 32 passes. Demo 04: 992 extra passes; 1,057 cycles. Padding each row to 33 words shifts every row by one bank: 0 conflicts, 449 cycles.

Divergence. Lecture 2’s masks reappear per warp. With 1,024 threads where half run 20 extra instructions:

which half takes the branchwarp instructionsSIMD utilizationcycles
nobody32100%16
even lanes (or lanes 0–15)67252%336
even warps352100%176

Divergence costs only when threads of the same warp disagree. The same amount of useful work arranged so that each warp is uniform runs at full SIMD utilization. Demo 01, Part C shows the simplest way to waste lanes: slide 27’s 4 × 3 block has only 12 threads, so each warp instruction uses 12 of 32 lanes (38%). Make block sizes multiples of 32.


5. Running a CUDA program on a GPU

5.1 Compilation records resource needs

Slide 41: the same CUDA program should run on a 16-core high-end GPU and on a 6-core mid-range one, unmodified. There is no concept of “number of cores” in a CUDA program; a launch is like a forall over blocks.

Slide 42: the compiled binary contains the program text and its resource requirements. For convolve: 128 threads per block, B bytes of local data per thread, and 130 floats (520 bytes) of shared space per block.

5.2 The block scheduler

Slide 43: on a kernel launch, the GPU’s thread block scheduler maps blocks to cores with a dynamic policy that respects the resource requirements. A block is placed on a core only if the core has room for all its threads’ execution contexts and its shared memory. The major CUDA assumption: thread block execution can be carried out in any order; blocks are assumed to have no dependencies on each other.

Slide 44 names the pattern, which we have met several times: a pool of worker “threads” pulling sub-problems from a queue. ISPC’s task implementation, a web server’s thread pool and Lecture 5’s work queues are other examples. The number of workers is a function of the machine (cores × slots), not of the number of tasks.

Slides 55–65 walk through convolve<<<1000, 128>>> on a fictitious two-core GPU. Each core has execution contexts for 384 threads (12 warps) and 1.5 KB of shared memory. 03_block_scheduling, Part A replays it:

cycle     0: block  0 starts on core 0          (contexts 0-127,   support at 0)
cycle     0: block  1 starts on core 1
cycle     0: block  2 starts on core 0          (contexts 128-255, support at 520)
cycle     0: block  3 starts on core 1
              -> block 4 must wait: a third block would need 3 x 520 = 1,560 > 1,536 bytes
cycle   706: block  0 ends  on core 0
cycle   706: block  4 starts on core 0          (reuses block 0's contexts and shared memory)
cycle   707: block  1 ends  on core 1
cycle   707: block  5 starts on core 1

By thread contexts a core could hold three blocks; shared memory limits it to two. When a block finishes, its contexts and shared memory are freed and the next block takes its place.

5.3 Occupancy

On a real GPU, four resources limit how many blocks an SM holds at once: thread contexts, registers, shared memory, and a hardware limit on resident blocks. The fraction of the SM’s warp slots in use is the occupancy. Higher occupancy means more warps for the warp selectors to choose from, so more latency hidden. Demo 03, Part B is an occupancy calculator (per SM: 2,048 threads, 32 blocks, 65,536 registers, and 96 / 164 / 228 KB of shared memory on V100 / A100 / H100):

kernel (threads/block, regs/thread, shared/block)V100A100H100
convolve (128, 16, 520 B)16 blocks, 100% (threads)100%100%
tiny blocks (32, 16, 0)32 blocks, 50% (block limit)50%50%
register-heavy (256, 128, 0)2 blocks, 25% (registers)25%25%
shared-heavy (256, 32, 48 KB)2 blocks, 25% (shared)3, 38%4, 50%

Register and shared-memory usage are therefore performance parameters. A kernel that uses fewer registers per thread, or a smaller shared tile, may run faster because more warps hide latency, even though each thread does the same work. Occupancy is not everything, though: a low-occupancy kernel with lots of independent work per thread (ILP) can still keep the units busy.


6. Advanced scheduling questions

Slide 66: “If you understand the following examples you really understand how CUDA programs run on a GPU.”

6.1 Why must all threads of a block be resident at once?

Slide 67: imagine a block of 256 threads on a core with contexts for only 128. Why not run threads 0–127 to completion, then threads 128–255?

Because CUDA kernels may create dependencies between threads in a block, the simplest being __syncthreads(). Threads 0–127 reach the barrier and wait for threads 128–255, which cannot start until threads 0–127 finish: a deadlock. CUDA’s semantics: the threads in a block are running concurrently; if a thread in a block is runnable, it will eventually be run. Hence the implementation constraint that all of a block’s threads exist, with register state allocated, when the block begins.

Demo 03, Part C: on real CUDA the launch is refused (“a block of 256 threads cannot fit an SM with 128 thread contexts”). On a hypothetical GPU that runs half a block at a time, the simulator detects the deadlock at the first barrier.

6.2 Implementation summary

Slide 68:

  • Thread blocks can be scheduled in any order by the system, which assumes no dependencies between them. They are logically concurrent, a lot like ISPC tasks.
  • CUDA threads in the same block run concurrently (live at the same time). When a block begins executing, all its threads exist and have register state allocated. A block is itself an SPMD program, like an ISPC gang of program instances, whose threads are cooperating workers.
  • A warp has performance characteristics like an ISPC gang, but unlike a gang, the warp does not exist in the programming model.
  • All warps of a block are scheduled onto the same SM, which allows high-bandwidth, low-latency communication through shared memory.
  • When all threads of a block complete, the block’s resources (shared memory, warp contexts) become available for the next block.

6.3 Blocks may share atomics, but not wait for each other

Slide 69: a histogram where every thread does atomicAdd(&counts[A[i]], 1) on counters in global memory. This is valid CUDA. Atomics provide mutual exclusion and nothing more; they do not constrain the order of blocks. Demo 03, Part D runs it with the blocks in forward and in reverse order: correct both times.

Slide 70: block 0 spins while (atomicAdd(&myFlag, 0) == 0) { } until block 1 does atomicAdd(&myFlag, 1). Is this reasonable? Not on a GPU with resources for only one block at a time:

  • if the implementation runs block 1 first, it sets the flag and finishes; block 0 then sees the flag and finishes. Demo 03: 364 cycles.
  • if it runs block 0 first, block 0 spins forever, because block 1 cannot start until block 0 finishes. Demo 03: “HANGS”.

The program is correct only under a scheduling assumption that CUDA does not make. Slide 69’s phrasing is careful: CUDA never claimed blocks were guaranteed to be independent, only that it reserves the right to schedule them in any order. Blocks must not wait for each other. (Newer CUDA features, cooperative launches and thread-block clusters, guarantee co-residency for exactly this reason; Lecture 11.)

6.4 The “persistent threads” style

Slide 71: write code that knows the hardware. Launch exactly as many blocks as fit on the GPU at once (BLOCKS_PER_CHIP = 80 * (32*64/128) on a V100), and have each block loop, grabbing the next chunk of work from a global counter with atomicInc, until all work is done. The programmer implements the block scheduler.

Demo 03, Part E runs both styles on the fictitious GPU. The results are equal, with 4 blocks launched instead of 48. In the simulator the persistent version is slower (16,744 vs. 8,528 cycles). Every chunk now starts with an atomic round trip to global memory and two extra barriers, while the simulator charges nothing for starting a block. On real GPUs block launch has a cost, and persistent kernels can also keep data in shared memory across work items, which is when the style pays. Its price is the one slide 71 implies: the program now depends on knowing how many blocks the hardware holds, exactly what the CUDA abstraction tried to hide.


7. The same kernels on a real GPU (Apple M4 Pro, Metal)

Apple GPUs follow the same design: cores with many resident SIMD-groups of 32 threads, threadgroup memory and caches. Metal plays CUDA’s role. 05_metal_convolution compiles the kernels at run time and times them with the GPU’s own timestamps (best of 10, after 0.3 s of warm-up):

GPU: Apple M4 Pro; max threads per threadgroup 1024, threadgroup memory 32 KiB; SIMD-group width 32
empty kernel: 5.5 us on the GPU, ~100 us from the CPU's commit to completion
saxpy on 16M floats: 0.79 ms = 253 GB/s
filterversionthreadgrouptimeGB/s (minimum traffic)
3 tapsv1: device loads only1280.571 ms235
3 tapsv2: threadgroup memory1280.569 ms236
3 tapsv22560.678 ms198
33 tapsv11280.965 ms139
33 tapsv21280.999 ms134

What the real GPU says:

  • A launch costs ~100 µs end to end, though only ~5 µs of it on the GPU: the rest is the CPU submitting the work and waiting for completion. Small kernels do not pay off; batch work into big launches.
  • saxpy reaches 253 GB/s. It is bandwidth-bound on the same unified memory where the CPU cores reached ~215 GB/s in Lecture 6.
  • With 3 taps, staging in threadgroup memory buys nothing. Both versions run at ~235 GB/s, near saxpy: memory-bound, with the GPU’s caches catching version 1’s reuse. This is the simulator’s “with L1” row of §3.5, now measured.
  • Even with 33 taps the versions are equal (~1.0 ms, ~135 GB/s): both are now limited by the 33 loads each output needs, and on this GPU a threadgroup-memory load costs about as much as a cache-hitting device load. Shared memory pays off when reuse is large and hardware caches handle it badly, for example the 2D tiles of matrix multiply (Lecture 9).
  • Group size matters: version 1 with 32-thread groups takes 0.82 ms vs. 0.56 ms with 128 or more. One SIMD-group per group gives each core too few threads to hide memory latency (occupancy again). Version 2 with 256 instead of 128 threads is slower, because a barrier makes every SIMD-group wait for the slowest one.
  • For scale: the same 3-tap convolution on one CPU core took ~2 ms.

Plan vs reality. The plan expected slide 37’s shared-memory version to win clearly on a real GPU; it does not, on this GPU and for this kernel. The first Metal timings also varied by 2× between runs, until the demo warmed up the GPU (whose clock rises only under sustained load) and kept the best of 10. The slides’ version 2 is the right idea. Modern GPUs with large caches make it unnecessary for this particular, cache-friendly access pattern.


8. Summary of the lecture (slide 72) and what comes later

  • Execution semantics. Partitioning the problem into thread blocks is in the spirit of the data-parallel model: machine-independent, and the system schedules blocks onto any number of cores. The threads of a block do run concurrently, as they must in order to cooperate. Inside a block: SPMD with a shared address space.
  • Memory semantics. A distributed address space between host and device; per-thread, per-block shared and global variables on the device. Loads and stores move data between them, so it is correct to think of them as distinct address spaces.
  • Key implementation details. The threads of a block are scheduled onto the same SM, so that they can communicate quickly through shared memory, and grouped into warps for SIMT execution.

Slides 73–74: this lecture used only the programmable cores. GPUs also contain fixed-function hardware for the graphics pipeline (rasterization, texture filtering), more or less turned off when running CUDA (see CS248A or CS348K). And the hundreds of TFLOP/s in the tensor cores are a topic for Lecture 10.


Summary

  • GPUs became throughput processors because shading is a pure function over huge streams of pixels. GPGPU hacks and Brook led to CUDA (2007): launch(kernel, N) on a compute-mode interface.
  • A CUDA kernel is written for one thread. A launch creates a grid of blocks of threads; each thread finds its element from blockIdx, blockDim and threadIdx. Round the grid up and guard the extra threads.
  • Memory: host vs. device (explicit cudaMemcpy, like message passing), per-block shared memory (fast, on-chip, program-managed), global memory (DRAM, cached), per-thread locals in registers. __syncthreads() synchronizes a block; atomics synchronize anything.
  • Implementation: the compiled kernel records its resource needs; a block scheduler places whole blocks on SMs when all their threads and shared memory fit; a block’s threads run as warps of 32 in SIMT fashion; many warps per SM hide latency. A CUDA thread is cheap because it is a lane of a warp, not an OS thread.
  • Cost model: coalesced loads (4 sectors per warp) vs. strided ones (up to 32); shared-memory bank conflicts (a column of a 32 × 32 tile: 32-way; padding to 33 fixes it); divergence only within a warp; occupancy limited by threads, registers, shared memory and block slots.
  • Rules from the implementation: a block must fit an SM entirely (barriers); blocks may run in any order and must not wait for each other (atomics are fine); persistent threads trade portability for control.
  • On the real Apple GPU, the slides’ shared-memory convolution is no faster than the cached version: caches capture simple reuse, and shared memory earns its keep with 2D tiling.

Common pitfalls

  • Forgetting the bounds guard when the data size is not a multiple of the block size. Real GPUs do not catch the out-of-bounds access.
  • Thinking a CUDA thread is like a pthread. It shares an instruction stream with 31 others; branches that split a warp cost both paths.
  • Calling __syncthreads() inside a branch that not all threads of the block take. That is undefined behaviour and can hang.
  • Making blocks depend on each other (flags, spin-waits across blocks). It may work on one GPU and hang on another, or with a different grid size.
  • Strided or struct-of-fields accesses across a warp. Lay data out so that consecutive threads touch consecutive addresses.
  • Ignoring occupancy. Large register or shared-memory use per thread can silently cap the number of resident warps.
  • Assuming shared memory always wins. Measure: modern GPU caches handle simple, local reuse well.
  • Timing a GPU without warming it up, or timing tiny kernels whose cost is all launch overhead.

Exercises

  1. Indices. A kernel is launched with dim3 grid(4, 3) and dim3 block(16, 8) over a 60 × 20 array (Nx = 60 columns, Ny = 20 rows). How many threads are launched, how many pass the guard, and which (i, j) does the thread with blockIdx = (3, 2), threadIdx = (5, 7) compute?

    AnswerThreads: 4 × 3 × 16 × 8 = 1,536. The grid covers 64 × 24 positions; 60 × 20 = 1,200 pass the guard. The thread computes i = 3 × 16 + 5 = 53 and j = 2 × 8 + 7 = 23. Since j = 23 ≥ Ny = 20, it is guarded off and does nothing.
  2. Shared memory budget. On the fictitious GPU (1.5 KB of shared memory, 384 thread contexts per core), how many blocks per core fit for a convolution with a 5-tap filter (support = TPB + 4 floats) and TPB = 64? For TPB = 128?

    AnswerTPB = 64: (64 + 4) × 4 = 272 bytes; by shared memory 5 blocks (1,360 B), by threads 6, so 5 blocks (320 threads). TPB = 128: 528 bytes, so 2 by shared memory (3 would need 1,584), 3 by threads, so 2 blocks (256 threads).
  3. Coalescing. A warp of 32 threads loads A[threadIdx.x * 2 + 1] (floats, A 128-byte aligned). How many 32-byte sectors does the instruction touch? What if it loads A[(threadIdx.x * 32) % 1024]?

    AnswerThe first touches floats 1, 3, …, 63, spanning 256 bytes = 8 sectors. In the second, thread t reads float 32t: each thread is in a different 128-byte line, so 32 sectors.
  4. Bank conflicts. A warp reads a 32 × 32 float tile in shared memory, stored with rows of 32 floats, at tile[threadIdx.x][k] for a fixed k. How many passes does the access need? With rows of 33 floats? With rows of 34?

    AnswerWord index = 32 × t + k, so all threads are in bank k: 32 passes. With 33: 33t + k mod 32 = t + k mod 32, all different: 1 pass. With 34: 34t + k mod 32 = 2t + k mod 32, which takes only 16 distinct values, two threads per bank: 2 passes.
  5. Latency hiding. A warp issues a global load whose latency is 400 cycles, then 20 independent arithmetic instructions that need the loaded value. Each sub-core issues one warp instruction per cycle. Roughly how many warps per sub-core keep it busy?

    AnswerLecture 2's estimate: one warp does 21 cycles of issue work per ~421-cycle round. To fill the gap, about 1 + 400 / 21 ≈ 20 warps, more than the V100's 16 per sub-core. With 16 warps, utilization is about 16 × 21 / 421 ≈ 80%. More work per load (ILP within a warp, or more instructions per byte) reduces the warps needed.
  6. Block independence. A kernel computes a prefix sum of block totals: block b waits until block b − 1 has published its running total (a flag in global memory), adds its own total and publishes. Under what condition does it always finish? Why might it still work in testing?

    AnswerIt finishes if blocks start in index order and block b − 1 is resident or finished whenever block b waits, e.g. if every block that can be waited on is guaranteed to have started first. CUDA does not promise that. If block b holds the last free slot while b − 1 has not started, b spins forever. It may work in testing because real GPUs usually dispatch blocks in index order and have many slots. Production "decoupled look-back" scans make this safe by assigning each block its logical index dynamically, through an atomic counter taken when the block *starts*, so a waiting block only ever waits for blocks that already started.

PA3, A Simple Renderer in CUDA, starts with warm-ups: saxpy (and a look at its bandwidth and the cost of host↔device copies), then a parallel exclusive scan and “find repeats” built from it (Lecture 8’s topic). The main task is a circle renderer that must be correct, with circles composited in input order, and fast, which requires the thinking of §3.5–§6: decomposition into blocks, shared memory, avoiding atomics and divergence where possible. These notes do not provide solutions; the demos use different kernels.

Further reading

  • The Fall 2025 slides for this lecture and the 2023 lecture video.
  • NVIDIA, CUDA C++ Programming Guide (docs.nvidia.com/cuda): Chapters 2 (programming model) and 5 (performance guidelines: coalescing, bank conflicts, occupancy). Also the CUDA C++ Best Practices Guide.
  • E. Lindholm, J. Nickolls, S. Oberman and J. Montrym, “NVIDIA Tesla: A Unified Graphics and Computing Architecture”, IEEE Micro 28(2), 2008. The architecture that introduced compute mode.
  • I. Buck et al., “Brook for GPUs: Stream Computing on Graphics Hardware”, SIGGRAPH 2004.
  • NVIDIA, Volta V100 architecture whitepaper (2017): the SM of slides 45–53.
  • K. Fatahalian and M. Houston, “A Closer Look at GPUs”, CACM 51(10), 2008. The throughput-processor view of these lectures.
  • Apple, Metal Shading Language Specification and “Performing Calculations on a GPU” (developer.apple.com), for demo 05’s counterpart of CUDA.

Preview of Lecture 8 — Data-parallel thinking

So far parallel programs were described by what each worker does. Lecture 8 describes them as operations on whole sequences: map, reduce, scan (prefix sum), segmented scan, gather/scatter and sort. These primitives have efficient implementations on GPUs and multi-core CPUs, including a scan built from per-warp scans and per-block sums. With them, even irregular problems (sparse matrices, building a grid of particles, histograms) become regular and avoid fine-grained synchronization. The demos build a small data-parallel library and run a hierarchical scan on the Apple GPU.


术语表 (Glossary, English → 中文)

English中文
GPU (graphics processing unit)图形处理器
rendering / vertex / triangle mesh渲染 / 顶点 / 三角形网格
shader / fragment着色器 / 片元
GPGPU (general-purpose GPU computing)通用 GPU 计算
stream programming流式编程
compute mode计算模式
throughput processor吞吐量处理器
CUDA kernelCUDA 核函数
host / device主机(CPU 端)/ 设备(GPU 端)
grid / thread block / CUDA thread网格 / 线程块 / CUDA 线程
bulk launch批量启动
bounds guard越界保护判断
global / shared / local memory全局 / 共享 / 局部内存
__syncthreads() (block barrier)线程块内屏障
atomic operation原子操作
streaming multiprocessor (SM)流式多处理器
sub-core / warp selector子核 / 线程束调度器
warp线程束(32 个线程)
SIMT (single instruction, multiple thread)单指令多线程
register file寄存器堆
coalesced memory access合并访存
sector (32 bytes)扇区(32 字节)
bank / bank conflict存储体 / 存储体冲突
divergence / reconvergence分支发散 / 重新汇合
block scheduler线程块调度器
occupancy占用率
resource requirements (of a kernel)(核函数的)资源需求
persistent threads持久线程
threadgroup / SIMD-group (Metal)线程组 / SIMD 组(Metal 术语)
launch overhead启动开销
warm-up预热
← 返回课程目录