Roadmap/Phase 01
PHASE 01 OF 06

LLM Fundamentals

Understand exactly what a GPU is computing when a model answers you.

0%
7 topics14 lessons44 h
In plain English

A large language model is an enormous autocomplete. You give it text, it turns each piece of a word into a list of numbers, pushes those numbers through the same fixed recipe a few dozen times, and ends with a score for every possible next piece of text. Think of a factory line where every station does the same kind of work on every item, but with different settings. This phase teaches you the stations, what each one costs in time and memory, and why generating the first word of an answer is a completely different job from generating the hundredth. Everything you do later in inference engineering is a trick applied to one of these stations.

What you can do afterwards

You can trace a prompt through a decoder-only transformer by hand, name every tensor that is created and its shape, implement attention and a KV cache from scratch, and explain with measured numbers from your own laptop why prefill is compute-bound while decode is memory-bound.

Milestones

  1. M1Tensors and tokens
  2. M2Inside the transformer block
  3. M3How generation actually runs

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 GPT-2 inference engine (no HuggingFace)

CPU · your Mac~8 h
one evening to a weekend · required for phase completion

Load the real GPT-2 small weights into a decoder you wrote yourself (embeddings, RoPE-free learned positions, attention, MLP, layer norm, tied unembedding), add a KV cache and greedy/top-k sampling, and prove it matches the Hugging Face output. This is the whole of Phase 1 in one file you understand completely.

Scope

  • A single model.py with the decoder block, under 400 lines, no transformers import except to download weights once.
  • A weight loader that maps the HF state_dict names onto your modules (and checks every tensor was consumed).
  • A tokenizer wrapper using the GPT-2 BPE vocab files (you may use tiktoken for the BPE itself).
  • A generate() with a KV cache, greedy and top-k, temperature, and a stop token.
  • A bench.py that times prefill and per-token decode for prompts of 16, 128 and 512 tokens.

Out of scope

  • Training or fine-tuning.
  • Any GPU code; this is CPU fp32.

What to measure

Logit agreement with Hugging Face GPT-2
How · torch.allclose on logits for 5 prompts, atol 1e-3
Target · all pass
Parameter accounting
How · sum(p.numel()) versus config formula
Target · 124,439,808 exactly, zero unconsumed HF tensors
Prefill vs decode time
How · wall-clock with torch.set_num_threads fixed, 5 repeats, median
Target · prefill grows roughly linearly with prompt length; decode per-token is flat within 20 percent across 16/128/512
Tokens per second at batch 1
How · 128 greedy tokens after a 32-token prompt
Target · report the number; typical Apple M-series CPU lands 10-40 tok/s

Pay attention to

  • Pre-norm order and the residual stream; most "almost right" outputs come from applying layer norm in the wrong place.
  • GPT-2 uses Conv1D-named linear layers with transposed weights; the loader must transpose.
  • Causal mask must be applied before softmax in fp32; check with a prompt whose later tokens would otherwise leak.
  • Position ids for the one-token decode step must equal the current cache length, not zero.
  • Do not compare argmax tokens only; compare logits, then tokens.

Acceptance (all must pass)

  • ☐pytest passes the logit-agreement test on 5 prompts.
  • ☐Greedy generation of 64 tokens is identical to HF generate(do_sample=False) for 3 prompts.
  • ☐KV-cached decode produces identical tokens to the uncached path and is at least 2x faster at 128 tokens.
  • ☐README contains the bench table and a one-paragraph explanation of why decode is memory-bound even on CPU.
Deliverable · A repository with model.py, loader, tokenizer wrapper, generate, bench.py, tests, and a README with the numbers.
Stretch · Swap learned positions for RoPE and load TinyLlama instead. · Add speculative sampling with GPT-2 small drafting for GPT-2 medium.
Medium

Build your own inference profiler for transformers

CPU · your Mac~16 h
a weekend or two · composes several builds

Instrument your Phase-1 engine (or HF GPT-2) to produce a per-layer, per-operator breakdown of time, FLOPs and bytes moved for prefill and decode, then use it to predict and verify where time goes as prompt length, batch size and model size change. The output is a tool, a report and a set of predictions you tested.

Scope

  • Forward hooks (or manual timers) that record time per module per step, separated into prefill and decode.
  • An analytic FLOP and byte model per operator from shapes alone (matmul 2mnk, attention scores, KV reads).
  • A CLI that prints a table and writes a CSV plus a stacked-bar plot per phase.
  • Experiments sweeping prompt length (16-2048), batch (1-16) and model (gpt2, gpt2-medium).
  • A written comparison of predicted versus measured ratios and an arithmetic-intensity estimate per phase.

Out of scope

  • GPU profiling (Phase 2 and 4 cover Nsight).
  • Optimising anything; this capstone only measures and explains.

What to measure

Attribution coverage
How · sum of per-module times versus end-to-end time
Target · within 10 percent
Prediction error
How · predicted FLOP share of attention vs MLP compared with measured time share
Target · ranking correct for every configuration; shares within 15 points at long prompts
Arithmetic intensity
How · FLOPs / bytes for prefill and for one decode step at batch 1
Target · decode intensity at least 20x lower than prefill at 512-token context
Scaling slopes
How · log-log fit of time vs prompt length for attention scores
Target · slope between 1.7 and 2.3

Pay attention to

  • Warm up and pin thread count; CPU timing noise will otherwise swamp per-layer numbers.
  • Hooks add overhead; measure the overhead with hooks that do nothing and subtract it.
  • Separate the first decode step from steady-state decode; the first step still pays allocation costs.
  • Bytes moved must count weight reads once per step, not once per token in a batch.

Acceptance (all must pass)

  • ☐Tool runs on both models with one command and produces CSV plus plot.
  • ☐Report contains the four measurements with their targets met or a documented explanation.
  • ☐At least two predictions written before measuring, with the outcome recorded honestly.
Deliverable · A CLI profiler package, CSV results for all sweeps, plots, and a 2-page report.
Large

Build your own llama.cpp (CPU-only Llama inference in C++ or Rust)

CPU · your Mac~50 h
1-3 weeks · portfolio piece

Reimplement inference for TinyLlama-1.1B on CPU without PyTorch, in C++ or Rust: GGUF or safetensors loading, bf16-to-fp32 or int8 weight handling, RoPE, grouped-query attention, SwiGLU, RMSNorm, a KV cache, a BPE tokenizer and a streaming CLI. This is a portfolio project in the mould of llama.cpp and llama2.c and exercises every Phase-1 idea at the level a systems team expects.

Scope

  • Weight loader for safetensors (JSON header plus raw tensors) supporting bf16 and fp32.
  • All forward-pass kernels hand-written, including a blocked matmul with threads.
  • SentencePiece/BPE tokenizer compatible with the TinyLlama vocab, verified against the Python tokenizer.
  • KV cache with a maximum context, RoPE applied with the correct positions on decode.
  • Streaming CLI with temperature and top-p, and a --bench flag.
  • Optional int8 per-channel weight quantisation with accuracy comparison.

Out of scope

  • GPU backends.
  • Multi-sequence batching (single sequence is fine).
  • Model formats beyond safetensors (GGUF optional).

What to measure

Numerical agreement with PyTorch
How · logits for 3 prompts versus transformers in fp32, max abs diff
Target · below 1e-2 in fp32 weights; document int8 drift
Tokens per second
How · 128-token generation after a 32-token prompt, median of 5
Target · report; aim for at least 5 tok/s fp32 on an 8-core laptop, higher with int8
Memory
How · peak RSS
Target · within 1.3x of weight bytes plus KV cache for 2048 context
Matmul efficiency
How · achieved GFLOP/s of your blocked matmul versus a naive triple loop and versus numpy
Target · at least 10x over naive; report the gap to numpy and explain it
Tokenizer fidelity
How · round-trip 1,000 random Wikipedia sentences versus the Python tokenizer
Target · 100 percent identical ids

Pay attention to

  • RoPE frequency base and head-dimension pairing; off-by-one in positions silently degrades quality rather than crashing.
  • GQA means K/V heads are fewer than Q heads; map head groups correctly.
  • RMSNorm epsilon and the order of residual adds; compare per-layer activations against PyTorch to localise bugs early.
  • bf16 to fp32 conversion is a bit shift, not a cast through float16.
  • Cache-friendly memory layout for the matmul matters more than SIMD intrinsics at first.

Acceptance (all must pass)

  • ☐Generates coherent text for 5 prompts and matches PyTorch greedy tokens for at least 32 tokens on 3 prompts.
  • ☐All five measurements reported in the README with the commands to reproduce.
  • ☐Per-layer activation diff tool exists and shows max diff per layer.
  • ☐Builds from a clean clone with one command on macOS and Linux.
Deliverable · A public repository with source, tests, benchmark table, and a write-up suitable as a blog post.
Stretch · Add int4 quantisation with group-wise scales and measure perplexity on a small text set. · Add Metal or CUDA matmul for the heaviest kernel.
GPU Architecture and CUDA →Complete this phase to unlock