Roadmap/Phase 02
PHASE 02 OF 06

GPU Architecture and CUDA

Learn how a GPU actually runs your tensors so you can tell when it is wasting time.

0%
7 topics17 lessons45 h
In plain English

A CPU is a handful of very clever workers; a GPU is a stadium full of simple workers who all do the same step at the same moment. Running a language model is mostly multiplying enormous grids of numbers, which is exactly the kind of job the stadium is good at, as long as the work is handed out and the numbers are delivered in the right order. This phase teaches you how the stadium is organised, where the numbers live while they wait to be used, and how to write and measure small programs (kernels) that run on it. You will do this on free cloud GPUs from your Mac.

What you can do afterwards

You can write, launch and time a CUDA kernel, explain its performance with a roofline sketch, recognise a memory-bound versus compute-bound kernel from a profiler trace, and read a tiled matrix multiplication kernel line by line.

Milestones

  1. M1How a GPU executes work
  2. M2Where the bytes live
  3. M3Writing and measuring kernels

Capstone projects

Three sizes. The small one is part of finishing this phase (it carries 15% of the phase bar); medium and large are tracked but optional. Each lists what to build, what to leave out, what to measure, and what reviewers will look at.

Small

Build your own fused attention kernel in CUDA

Colab T4 · free~8 h
one evening to a weekend · required for phase completion

Write one CUDA kernel that computes causal scaled dot-product attention for GPT-2 shapes (12 heads, head_dim 64, sequences up to 1024) without ever materialising the S x S score matrix. Tile over keys, keep a running max and sum in registers (online softmax), accumulate the output in fp32, bind it with load_inline, and prove it matches torch F.scaled_dot_product_attention while timing it. It proves the phase because thread mapping, shared-memory tiling, warp reductions, coalesced loads and roofline reasoning all have to be right in a single kernel you can explain line by line.

Scope

  • A naive three-kernel attention (QK^T GEMM, row softmax, PV GEMM) in CUDA first, kept as the correctness and speed baseline.
  • The fused kernel, one block per (batch, head, 64-query tile), K and V tiles of 64 keys staged in shared memory, online softmax with rescaling, causal masking that skips fully masked tiles.
  • A load_inline binding with shape, dtype and contiguity checks and a Python wrapper fused_attention(q, k, v, causal=True).
  • pytest comparing against SDPA for batch 1-8, 12 heads, seq 128, 512 and 1024, head_dim 64, with fp32 and fp16 inputs.
  • bench.py timing your kernel against the naive version and SDPA (default and math backends) with torch.cuda.Event, plus peak memory via torch.cuda.max_memory_allocated.
  • One ncu Speed of Light row for your kernel at seq 1024, or event-derived FLOP/s and GB/s if ncu is blocked on Colab.

Out of scope

  • The backward pass or anything training-related.
  • A tensor-core (WMMA) path; fp32 FMA is the target, tensor cores are a stretch.
  • Variable-length batches or paged KV (Phase 3).

What to measure

Numerical agreement with SDPA
How · max abs diff over 20 random inputs per shape, SDPA forced to the math backend for the reference
Target · below 1e-4 with fp32 inputs, below 1e-2 with fp16 inputs
Speed versus SDPA at batch 4, 12 heads, seq 1024
How · median of 50 iterations after 10 warm-ups with torch.cuda.Event
Target · within 3x of SDPA's default backend on a T4 and at least 1.5x faster than your naive three-kernel version
Extra memory during the call
How · max_memory_allocated minus the bytes of q, k, v and the output
Target · under 1 MB at seq 1024, while the naive version allocates batch x heads x 1024 x 1024 x 4 bytes (192 MB at batch 4)
Achieved FLOP/s
How · 2 x B x H x S x S x D (causal, counting QK^T and PV, halved for the mask) divided by time
Target · report; T4 note: FP32 FMA peak is 8.1 TFLOPS and Colab T4s sustain about 5-6 TFLOPS under the 70 W cap, a first fused kernel typically lands at 1-2 TFLOPS
Scaling with sequence length
How · time at seq 128, 256, 512 and 1024, log-log slope
Target · slope between 1.7 and 2.2, and the speed-up over the naive version grows with S

Pay attention to

  • Online softmax rescaling. When the running max changes, both the running sum and the accumulated output must be multiplied by exp(m_old - m_new); forgetting the output rescale passes short tests and fails at seq 1024.
  • Causal masking must skip whole key tiles above the diagonal and apply -inf inside the diagonal tile; compare against SDPA with is_causal=True, not a hand-built mask of zeros, and check that the first 128 outputs are identical whether S is 128 or 1024.
  • Scale by 1/sqrt(d) before the exp and keep max and sum in fp32; an fp16 running sum overflows on long rows.
  • __syncthreads placement between loading the next K/V tile and reading it; double buffering without a barrier races and only shows up as sporadic mismatches.
  • Timing hygiene. Synchronise, warm up, exclude the load_inline compile, and report the median, not the mean.

Acceptance (all must pass)

  • ☐pytest passes the agreement test for every listed shape in fp32 and fp16.
  • ☐The causality check passes (first 128 query outputs identical at S = 128 and S = 1024).
  • ☐README has a bench table with your kernel, the naive version, SDPA default and SDPA math at four sequence lengths.
  • ☐The memory measurement confirms no S x S intermediate.
  • ☐README contains a roofline sketch placing the kernel at seq 1024 on the T4 and states whether it is compute- or memory-bound with the ncu or event numbers that justify it.
Deliverable · A repository with attention.cu, the Python binding, tests, bench.py, and a README with the bench table, the roofline sketch and a ten-line explanation of online softmax.
Stretch · WMMA fp16 QK^T and PV with fp32 accumulation and the resulting speed-up. · Support head_dim 128 and grouped-query attention (fewer K/V heads than Q heads).
Medium

Build your own CUDA kernel library for a transformer block

Colab T4 · free~16 h
a weekend or two · composes several builds

Assemble the kernels from this phase's builds (SGEMM, softmax, layernorm, GELU, fused attention) plus the glue they need (bias add, residual add, head reshapes) into one PyTorch C++ extension, then write a MyGPT2Block module that runs a complete GPT-2 small layer, attention and MLP, using only your kernels, and verify it against the Hugging Face GPT2Block with the same weights. It proves the phase because every kernel must agree with PyTorch at the layer level and be fast enough that the whole layer is not embarrassingly slower than eager mode.

Scope

  • Kernels, your fp32 2D-blocked SGEMM with a fused bias epilogue and an optional fused GELU epilogue, layernorm, fused residual add plus layernorm, row softmax, causal fused attention (from the small capstone or a three-kernel version), and GELU.
  • A C++ extension built with torch.utils.cpp_extension.load (not inline) that exposes each kernel with input checks.
  • MyGPT2Block, an nn.Module that loads a transformers GPT2Block state_dict (transposing the Conv1D weights) and forwards with only your ops, plus a per-op flag to swap any single kernel back to torch for bisecting.
  • pytest with per-kernel tests against torch and a layer test against HF for batch 1-8 and seq 128-1024, including one odd shape (B = 3, S = 100).
  • bench.py with per-kernel microbenchmarks (microseconds, GB/s or GFLOP/s, percent of torch) and whole-layer time against HF eager in fp32, plus a torch.profiler trace of your layer.
  • A fusion study comparing separate (GEMM, bias, GELU) against the fused epilogue and separate (add, layernorm) against the fused kernel.

Out of scope

  • Backward pass or training.
  • fp16 tensor-core paths (stretch).
  • Multiple layers, KV cache and generation (the large capstone).

What to measure

Layer output agreement with HF GPT2Block
How · max abs diff on hidden states for 10 random inputs in fp32
Target · below 1e-3 (expect around 1e-4; GEMM accumulation order dominates)
SGEMM efficiency on the layer shapes
How · GFLOP/s versus torch.matmul fp32 (cuBLAS) for 768x768, 768x2304, 768x3072 and 3072x768 weights with M = 4096 rows
Target · at least 60 percent of cuBLAS on every shape; T4 note: cuBLAS SGEMM reaches about 4-5 of the 8.1 TFLOPS peak on a Colab T4, so expect 2.5-3.5 TFLOPS
Memory-bound kernel bandwidth
How · bytes read plus written divided by time for layernorm, GELU and residual add at 4096 x 768 and softmax at 12 x 1024 x 1024
Target · at least 60 percent of your measured copy bandwidth; T4 note: Colab T4s copy at about 220-250 GB/s against the 320 GB/s spec
Whole-layer time versus HF eager
How · median of 50 forward passes at batch 8, seq 512, fp32, with torch.cuda.Event
Target · within 1.5x of HF eager, with a per-kernel breakdown reported
Fusion savings
How · separate versus fused timings for both pairs, and kernel launches per layer counted from the profiler trace for yours and HF
Target · fused at least 1.2x faster in each pair; launch counts reported
Launch-bound check at small batch
How · layer time at batch 1, seq 16 versus batch 8, seq 512, and median gap versus median kernel duration from the trace
Target · report, with a one-line verdict on whether batch 1 is launch-bound

Pay attention to

  • GPT-2 Conv1D stores weights as [in, out]; your GEMM must transpose on load or support a transposed-B flag, and only a non-square shape test will catch a mistake.
  • The attention projection output is [B, S, 2304] laid out as q, k, v blocks that are then split into heads; a wrong head split still passes allclose on single-head tests.
  • HF adds a large negative value for the causal mask rather than -inf; after exp the difference is at the 1e-7 level and is acceptable, but a mask applied after softmax is not.
  • GEMM tiles assume M, N and K are multiples of 128; B x S = 300 is not, so pad or write bounds-checked edge tiles and test the odd shape.
  • LayerNorm eps is 1e-5 for GPT-2; read it from the config rather than assuming.
  • Reviewers look for bisect-ability; the swap-one-op-to-torch flag is what makes a layer-level mismatch debuggable in minutes.

Acceptance (all must pass)

  • ☐All per-kernel tests and the layer test pass for batch 1 and 8, seq 128, 512 and 1024, and the odd shape B = 3, S = 100.
  • ☐bench.md has the per-kernel table with percent of torch and the whole-layer comparison.
  • ☐The torch.profiler trace of your layer shows only your kernels and copies in the hot path, no fallback aten compute kernels.
  • ☐The fusion study reports both pairs with measured speed-ups and launch counts.
  • ☐A clean clone builds and passes `python -m pytest` on a Colab T4 in under 10 minutes including compilation.
Deliverable · A repository with csrc/ kernels, the extension, mygpt2block.py, tests, bench.py and bench.md, and a README with the tables and the fusion study.
Stretch · A WMMA fp16 GEMM with fp32 accumulation and an fp16 layer path, compared with HF in fp16. · CUDA graph capture of the layer forward to remove the launch gaps found in the trace.
Large

Build your own GPU inference engine for GPT-2

Colab T4 · free~40 h
1-3 weeks · portfolio piece

Turn the kernel library into an engine. Load GPT-2 small weights onto the device once, run the full 12-layer forward (embeddings, blocks, final layernorm, tied unembedding) with your kernels, keep a preallocated on-device KV cache, write a decode-step attention kernel that reads it, and generate text greedily from a Python driver that does nothing but launch kernels. Compare tokens per second and bytes per token against PyTorch eager HF generate on the same T4. It is portfolio-grade because it shows you can take a model from weights to streaming tokens on a GPU with code you wrote and can account for every microsecond of a decode step.

Scope

  • A weight loader from the HF safetensors file to device tensors in your own layout (pre-transposed, fp32 with optional fp16 storage) that asserts every HF tensor was consumed.
  • A prefill path running the full sequence through the medium-capstone block kernels and writing K and V into the cache.
  • A KV cache preallocated as [layers, 2, B, heads, max_seq, head_dim] on the device, a cache-append kernel, and a decode attention kernel where one block per (sequence, head) attends one query to the cached keys, split across the sequence when it is long.
  • A decode path for a batched single-token step, with a dedicated GEMV-style kernel for M = 1..16 that streams each weight matrix once, coalesced.
  • On-device greedy and top-k sampling (an argmax reduction over 50257 logits), a stop token, and tiktoken for BPE.
  • bench.py reporting prefill time versus prompt length, decode tok/s at batch 1, 4 and 16, bytes moved per token, and the same for HF eager generate with use_cache=True in fp32 and fp16.
  • A profiler study, an nsys trace of 32 decode steps before and after capturing the step as a CUDA graph, with launches per step, gap histogram and busy fraction.

Out of scope

  • Training, and other model families (TinyLlama is a stretch).
  • Continuous batching and request scheduling (Phase 3).
  • Quantisation below fp16.

What to measure

Logit agreement with HF GPT-2
How · max abs diff on logits for 5 prompts in fp32, and greedy 64-token outputs for 3 prompts
Target · max abs diff below 1e-3 on all 5; tokens identical on all 3
Decode tokens per second at batch 1
How · 128 greedy tokens after a 32-token prompt, median of 5 runs with torch.cuda.Event after warm-up
Target · at least match HF eager fp32 (typically 25-45 tok/s on a Colab T4, which is launch-bound) and at least 2x after CUDA graphs; T4 note: the bandwidth ceiling is 320 GB/s divided by 497 MB of fp32 weights, about 640 tok/s (about 1,280 in fp16), so anything under 10 percent of that is launch-bound rather than bandwidth-bound
Decode throughput scaling with batch
How · aggregate tok/s at batch 1, 4 and 16 with equal-length prompts
Target · aggregate tok/s at batch 16 at least 8x batch 1, because the same weight bytes serve every sequence
Prefill throughput
How · tokens per second for a 512-token prompt at batch 1 in fp32
Target · at least 50 percent of HF eager fp32 prefill; this tracks your SGEMM's percent of cuBLAS, so report both
KV cache size and correctness
How · cache bytes after 132 tokens for one fp32 sequence, and token equality between the cached decode and a full recompute
Target · exactly 2 x 12 x 768 x 4 x 132 = 9,732,096 bytes per sequence; tokens identical for 128 steps
Launches per decode step and GPU busy fraction
How · nsys trace over 32 decode steps, before and after CUDA graph capture
Target · report launches per step (HF eager is in the hundreds, yours should be under 100 before graphs and 1 graph launch after) and busy fraction above 80 percent after graphs

Pay attention to

  • Position ids for the decode step equal the current cache length; the learned position embedding must be looked up with them, not with 0, or quality degrades silently.
  • The decode attention kernel must read only the first len cached keys per sequence and never stale entries from a previous request; run two prompts back to back and check the second is unaffected.
  • Batched decode with different prompt lengths needs per-sequence lengths and padding; a single shared length silently attends to padding and the outputs look plausible.
  • GEMM at M = 1 is a GEMV; a 128 x 128 tile kernel runs at under 1 percent of peak there, so the decode path needs its own kernel where each block owns a slab of output columns and reads the weight row-contiguously.
  • CUDA graph capture needs static shapes and addresses; preallocate every buffer, index the cache with a device-side length tensor, and never allocate inside the captured region.
  • Argmax over 50257 logits is a reduction; reuse the reduction build rather than copying logits to the host every step, which alone can halve tok/s.

Acceptance (all must pass)

  • ☐pytest passes the logit agreement and greedy-token equality tests, and generated text is coherent for 5 prompts.
  • ☐Nothing from transformers runs at generation time (it may be imported once to download weights); torch is used only for allocation, launching your extension and the baselines.
  • ☐bench.md contains all six measurements with reproduction commands and the T4 ceiling calculation.
  • ☐nsys traces before and after CUDA graphs are included with launches per step and busy fraction annotated.
  • ☐A fresh Colab T4 builds and runs the engine end to end with one command in under 15 minutes.
Deliverable · A public repository with the engine, kernels, tests, bench.md with tables and plots, nsys screenshots, and a write-up suitable as a blog post explaining where every microsecond of a decode step goes.
Stretch · fp16 weights with your WMMA GEMM for prefill and an fp16 GEMV for decode, measured against the 1,280 tok/s fp16 ceiling. · Load TinyLlama-1.1B (RoPE, grouped-query attention, SwiGLU, RMSNorm) through the same engine. · Speculative decoding with your engine drafting for HF gpt2-medium.