Roadmap/Phase 04
PHASE 04 OF 06

Inference Optimization

Make a model answer faster and cheaper without changing what it says.

0%
12 topics30 lessons99 h
In plain English

By now you know how a model computes an answer and how a serving engine feeds it requests. This phase is about shaving time and memory off that process. Think of a restaurant kitchen that already works correctly but slowly. You can use smaller plates (lower-precision numbers), reorganize the counter so the cook stops walking to the fridge (FlashAttention and kernel fusion), have an apprentice guess the next few dishes so the head chef only checks them (speculative decoding), and put a stopwatch on every station to see where the real wait is (Nsight profiling). Each trick is small on its own; together they are the difference between a toy demo and a product.

What you can do afterwards

You can take a model running in vLLM or plain PyTorch, measure where time and memory go with Nsight, and apply quantization, FlashAttention, CUDA Graphs, speculative decoding and KV cache tuning with a before/after number for each change and an explanation of why it helped or did not.

Milestones

  1. M1Numbers and precision
  2. M2Faster kernels and memory
  3. M3Algorithmic speedups
  4. M4Measure and tune

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 INT8/INT4 quantizer for GPT-2 with a correctness gate

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

Quantize GPT-2 small and medium to INT8 (per-channel) and INT4 (group-wise, round-to-nearest and GPTQ-lite), load the quantized weights into your Phase-1 engine or transformers, and put every configuration through a numerics gate you also build: KL and top-k agreement against fp32 goldens plus perplexity on a fixed text slice. It proves the phase because you can show, with your own numbers, exactly how much accuracy each byte saved costs and the gate that would stop a bad quantization from shipping.

Scope

  • A quant package with absmax INT8 per-channel, INT4 group-128 with zero points and nibble packing, and a GPTQ-lite pass using a Hessian from 128 calibration sequences.
  • A loader that swaps quantized weights into the model at load time (dequantize to fp32 for the matmul) and verifies every weight tensor was handled.
  • Golden generation from transformers GPT-2 fp32 on 20 prompts and a gate with per-tier thresholds for KL, top-1 agreement, top-10 overlap and greedy divergence position.
  • Perplexity evaluation on a fixed 2,048-token WikiText-2 slice, held out from the calibration data.
  • A bench that reports weight bytes, compression ratio and batch-1 decode tokens per second for fp32, INT8 and both INT4 variants.
  • One CLI command that runs everything and writes results.csv plus a README table.

Out of scope

  • Real low-bit matmul kernels; dequantizing to fp32 before the matmul is fine on CPU.
  • Activation quantization beyond an optional W8A8 demonstration.
  • Models other than gpt2 and gpt2-medium.

What to measure

Weight compression
How · packed bytes including scales and zero points versus fp32 weight bytes, from the loader's accounting
Target · at least 3.8x for INT8 and at least 7x for INT4 group-128
Perplexity delta
How · your perplexity on the held-out slice minus the fp32 figure, fp32 cross-checked against transformers within 0.01
Target · INT8 at most 0.2; INT4 group-128 GPTQ-lite at most 1.5 and lower than round-to-nearest INT4
Gate metrics
How · mean KL over the full vocab and top-1 agreement against fp32 goldens on 20 prompts
Target · INT8 KL below 0.01 and top-1 at least 0.97; INT4 values reported with the tier they pass
Decode speed
How · batch-1 tokens per second for 128 tokens after a 32-token prompt, median of 5
Target · report; explain the direction of the change versus fp32 on CPU
Gate sensitivity
How · inject one seeded bug (for example quantizing along the wrong axis) and run the gate
Target · exit code 1 on every injected bug

Pay attention to

  • GPT-2's Conv1D stores weights transposed relative to nn.Linear; per-channel must mean per output channel after accounting for that.
  • Asymmetric INT4 needs the zero point clamped into the code range; off-by-one here silently clips the largest weights.
  • Hessian damping and the order of column updates decide whether GPTQ-lite helps or hurts; print the per-layer reconstruction error.
  • Calibration text must not overlap the perplexity slice; reviewers check for this leak.
  • Compare logits before tokens; a greedy match on short prompts hides large distribution shifts.
  • Say whether the embedding and the tied unembedding were quantized, and show both choices if you tried them.

Acceptance (all must pass)

  • ☐pytest passes, including the gate-sensitivity test with at least one injected bug.
  • ☐One command produces results.csv with a row per configuration and the README table is generated from it.
  • ☐INT8 meets the compression, perplexity and gate targets; INT4 GPTQ-lite beats INT4 round-to-nearest on perplexity.
  • ☐The fp32 perplexity matches transformers within 0.01, proving the evaluator.
  • ☐The README explains in one paragraph which configuration you would ship and why.
Deliverable · A repository with the quant package, loader, gate, perplexity evaluator, bench, tests, results.csv and a README with the table and recommendation.
Stretch · Add AWQ-lite scaling and show where it beats GPTQ-lite on this model. · Run the INT4 configuration through your Phase-3 server and measure the memory and throughput change.
Medium

Build your own optimized decode path

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

Take the decode step of a small model (GPT-2 small, or Qwen2.5-0.5B in fp16) on a Colab T4 and rebuild it as fused Triton kernels reading an fp8 KV cache, captured into CUDA Graphs per batch bucket, with nsys traces before and after and a numerics gate that proves the output did not drift. It proves the phase because every kernel-level trick is applied to one real model with a measured inter-token latency gain and a correctness number next to it.

Scope

  • An eager fp16 baseline decode step with a static, preallocated KV cache and device-side position state.
  • Triton kernels for residual-add plus normalisation, the gated or GELU MLP activation, and RoPE-plus-KV-write where the model needs it, each unit-tested against the PyTorch ops.
  • A Triton decode attention kernel that reads keys and values stored as fp8 e4m3 with per-head scales (stored as uint8 and decoded in-kernel if the T4 cannot cast natively).
  • CUDA Graph capture per batch bucket (1, 4, 16, 32) with padding, and a routing function with tests.
  • nsys traces of the eager and optimised paths analysed with your p4 trace analyzer for kernel count, idle fraction and launch latency.
  • A numerics gate against transformers fp16 goldens, and an ITL benchmark at batch 1, 8 and 32 with cuda events.

Out of scope

  • Prefill optimisation; prompts are processed with the stock model.
  • A serving layer, scheduler or HTTP API.
  • Multi-GPU or any model that does not fit the T4 in fp16.

What to measure

Inter-token latency at batch 1
How · median over 200 decode steps with cuda events after 20 warmup steps, eager transformers versus your path
Target · at least 2x faster
Kernel launches per decode step
How · your nsys analyzer on both traces
Target · at least 3x fewer in the optimised path
GPU idle fraction per decode step
How · idle gaps inside the per-step NVTX range from your analyzer
Target · below 15 percent in the optimised path; eager figure reported
KV bytes per token
How · cache accounting from your cache class
Target · at most 55 percent of the fp16 figure
Numerics gate
How · mean KL and top-1 agreement against fp16 transformers goldens on 20 prompts over 64 decode steps
Target · KL below 0.01 and top-1 at least 0.97
Model-bandwidth utilisation at batch 32
How · weight bytes plus KV bytes read per step divided by measured step time, over the T4's 320 GB/s
Target · report

Pay attention to

  • Everything a captured graph reads must be a tensor updated in place; a rebound Python int or a fresh tensor is the classic silent bug, so keep a test that reproduces it.
  • fp8 scales must be computed at write time per head and the kernel must apply them before the dot product; forgetting the scale on V alone still yields plausible text.
  • The T4 has no fp8 tensor cores; fp8 here saves bandwidth, not compute, and your write-up must say so.
  • Warm up before capture and before timing; the first replay and the first Triton compile are not representative.
  • Measure with cuda events and synchronise; time.time() around an async launch measures nothing.
  • Colab sessions die; keep traces, CSVs and goldens on Drive and make every stage re-runnable from a clean session.

Acceptance (all must pass)

  • ☐All Triton kernels pass unit tests against PyTorch ops at atol 1e-3 in fp16.
  • ☐Batches of 3, 9 and 20 route to the right buckets and produce the same tokens as eager for every real row.
  • ☐The numerics gate passes at the stated thresholds and the ITL, kernel-count and idle-fraction targets are met or explained.
  • ☐Two .nsys-rep files and your analyzer's reports are committed with the commands that produced them.
  • ☐The README has a before-and-after table and a one-paragraph explanation of where the remaining time goes.
Deliverable · A repository with the kernels, cache, graph runner, gate, benchmark, nsys traces, analyzer output and a README with the before-and-after numbers.
No GPU? · Develop and unit-test every kernel on your Mac with TRITON_INTERPRET=1 and run the gate on CPU; do graph capture, nsys and timing in one planned Colab session with everything else already green.
Stretch · Add speculative decoding from your p4 build on top of the optimised path and report the combined speedup. · Compare against torch.compile(mode="reduce-overhead") and vLLM on the same T4 and model.
Large

Build your own speculative decoding system

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

Turn speculative decoding into a production feature of the continuous-batching server you built in Phase 3: pluggable drafters (a small same-family model, n-gram prompt lookup and a tree-structured draft), a verifier that is exact for greedy and provably lossless for sampling, KV rollback for draft and target, per-request adaptive gamma, metrics, and an end-to-end benchmark on a T4 with Qwen2.5-0.5B drafting for Qwen2.5-1.5B. It is portfolio-grade because it combines an algorithm, systems integration and honest measurement of where the speedup disappears as batch size grows.

Scope

  • A Drafter interface with three implementations, small-model, n-gram prompt lookup and top-2 tree of depth 3 with a tree attention mask, selectable per request.
  • A verifier with exact greedy acceptance and rejection-sampling acceptance at arbitrary temperature and top-p, including the bonus token.
  • KV cache rollback for both draft and target integrated with the Phase-3 paged cache, so accepted lengths differ per sequence in a batch.
  • Batched speculative decoding inside the continuous-batching scheduler with per-request gamma adapted from a running acceptance estimate, and automatic fallback to plain decoding when the predicted speedup drops below 1.1.
  • A metrics endpoint exposing acceptance rate, accepted tokens per round, draft and verify time, and gamma per request.
  • A benchmark with your p4 latency/throughput explorer on three workloads (summarisation, code, open-ended chat) at concurrency 1, 4, 16 and 32, plus a statistical losslessness test and a greedy-equivalence test.

Out of scope

  • Training EAGLE or Medusa heads; drafters use existing models or the prompt.
  • Multi-GPU serving.
  • Any model family whose draft and target tokenizers differ.

What to measure

End-to-end speedup at concurrency 1
How · output tokens per second with speculation on versus off, same prompts, median of 5 runs per workload
Target · at least 1.5x on the summarisation workload; all three workloads reported
Acceptance rate and accepted tokens per round
How · from the metrics endpoint over the benchmark
Target · between 0.6 and 0.9 for the small-model drafter on summarisation; reported per drafter and workload
Losslessness
How · total-variation distance between 5,000 speculative and 5,000 plain samples of the next token on a fixed prompt at temperature 1.0
Target · below 0.05
Speedup versus concurrency
How · tokens per second ratio at concurrency 1, 4, 16 and 32
Target · report the concurrency where it falls below 1.1 and show adaptive gamma keeps throughput at concurrency 32 at least 0.9x of plain decoding
Greedy equivalence
How · 256 greedy tokens for 20 prompts, speculative versus plain, for every drafter
Target · 100 percent identical

Pay attention to

  • Draft and target must share a tokenizer and special tokens exactly; a one-token vocabulary mismatch corrupts acceptance silently.
  • The bonus token after a fully accepted draft and the residual distribution on rejection are where most implementations lose exactness; test both paths separately.
  • Rolling back the paged cache means freeing or truncating blocks per sequence; a leaked block shows up as capacity loss only after thousands of requests, so track block counts in tests.
  • Tree drafts need per-node position ids and a mask that lets each node see only its ancestors; verify the mask with a hand-written 3-node case.
  • Speculation under sampling cannot be checked by token equality; compare distributions, and use greedy equivalence for the mechanics.
  • Report speedup against a baseline running in the same server with speculation disabled, not against transformers.

Acceptance (all must pass)

  • ☐Greedy equivalence holds for all drafters and the TVD test passes.
  • ☐The Phase-3 server's existing test suite still passes with speculation enabled and disabled.
  • ☐Speedup, acceptance, concurrency crossover and metrics are reported for all three workloads with the commands to reproduce.
  • ☐Adaptive gamma demonstrably switches speculation off under load, shown in a plot of gamma and speedup against concurrency.
  • ☐No KV block leaks over a 1,000-request soak run, asserted by block accounting.
  • ☐A 5-minute demo video or notebook walks through a request, the metrics and the benchmark plots.
Deliverable · A public repository with the drafters, verifier, scheduler integration, metrics, benchmark results, plots, tests and a write-up suitable for a blog post or interview walkthrough.
No GPU? · Run the whole system on your Mac CPU with gpt2 drafting for gpt2-medium (or the n-gram drafter alone on Qwen2.5-0.5B), 64-token generations and concurrency 1 to 8; every test and plot is the same at smaller scale, and the T4 run is one session when available.
Stretch · Add a trained lightweight draft head (Medusa-style) on top of the target's hidden states and compare acceptance with the small-model drafter. · Combine with your p4-cap-medium optimised decode path and report the stacked speedup.