Lab 03 — Transformer Performance Bug Hunt
Phase: 07 — Profiling & Performance Engineering | Difficulty: ⭐⭐⭐⭐⭐ | Time: 3–4 hours
Diagnose and fix 5 common Transformer performance anti-patterns seen in production code.
What you build
Identify and fix these anti-patterns in a buggy transformer implementation:
- Incorrect attention mask causing O(T²) work even for padding tokens
- Missing
.contiguous()before reshape causing unnecessary copies - CPU-GPU sync via
.item()inside the forward loop - Redundant recomputation of
sqrt(d_k)on every call - Inefficient KV projection using separate linear layers instead of one
Key concepts
| Concept | What to understand |
|---|---|
| Memory contiguity | Non-contiguous tensors require copy before CUDA kernels |
.item() sync | Blocks GPU pipeline — never call in inference loop |
| Flash-attention mask | Causal mask should be precomputed and registered as buffer |
| GEMM batching | One [d, 3*d_k] projection is faster than three [d, d_k] projections |
Files
| File | Purpose |
|---|---|
lab.py | Buggy transformer implementation with TODO: fix markers |
solution.py | Fixed implementation with explanations |
test_lab.py | pytest suite checking correctness and performance |
requirements.txt | Dependencies |
Run
pip install -r requirements.txt
python lab.py
pytest test_lab.py -v