Unit 9 of 11 · about 3 hours · measure
Token, distribution and task-quality equivalence
Every inference optimization is a correctness claim first. Equivalence at token, distribution and task levels decides whether a speedup ships.
You'll be able to
- Define token, distribution and task-quality equivalence with predeclared tolerances.
- Run a perplexity evaluation with fixed windows, stride and dtype and report the difference.
- Gate one optimization on all three equivalence levels.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Correctness-first debugging gateAI Systems Performance Engineering - Chapters 13, 15 and 16
Chapter 16, Profiling, Debugging, and Tuning Inference Performance: Debugging Correctness Issues
- Perplexity evaluator contractAI Systems Performance Engineering companion code - Chapters 12 to 16
load_tokenswith space-separated integers;parse_argswithtokens,--seq-len,--stride,--dtypeand--fp8-mode;GPTConfigandGPTModelscoring - Exact-match sampler fast pathAI Systems Performance Engineering companion code - Chapters 12 to 16
GreedySamplerBenchmark(defined ingreedy_sampler_common.py) withmaterialize_probabilities=Trueinbaseline_greedy_sampler.pyversusFalseinoptimized_greedy_sampler.py
Focus on
- Token equivalence is exact ID match under a stated sampling policy. Greedy
argmaxon logits equalsargmaxon probabilities, so the sampler fast path must match exactly. - Distribution equivalence is a measured distance: perplexity difference near noise on a fixed token window plus a KL or logprob check where sampling matters. One perplexity number without windows, stride and dtype is not a gate.
- Task equivalence is a product spot-check on a small eval slice. Quantization and speculative paths pass only when all three levels agree within predeclared tolerances.
Common mistakes · 3
- Accepting
equal_nan=Truestyle looseness as correctness. Unexpected NaNs must fail the gate, not pass it quietly. - Widening tolerance until a wrong-mask variant passes. Tolerances are predeclared from precision and use, not fitted to results.
- Testing quality on the data the optimization was tuned on. Fix the eval tokens before measuring the difference.
Try it yourself
Closed-book, before checking anything
argmax of logits equals argmax of softmax of the same logits, so skipping probability materialization is exact. Then state the perplexity formula and which windows, stride and dtype your gate fixes.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Does a small perplexity difference alone prove an optimization is safe?Answer
No. It can hide distribution shifts that sampling exposes and task regressions that perplexity misses. All three levels need tolerances.
2.What does the greedy-sampler fast path save, and why is it exact?Answer
It removes the full-vocabulary softmax and probability buffer from greedy decode. Softmax is monotone, so
argmaxis unchanged; only logits close enough to round to equal probabilities could pick a different index.3.What must a perplexity comparison fix?Answer
Fixed token file, window length, stride, dtype and conversion mode. Changing any of them between runs invalidates the comparison.
Practice
- Companion code ch16: perplexity evaluation gate
Run
perplexity_eval.pywithtokens,--seq-len,--stride,--dtypeand--fp8-modeon a fixed token file before and after one optimization; report perplexity difference with windows and dtype retainedCPU or single-GPU run is enough. No public autograder scores the difference; retain the token file, windows, stride, dtype and both perplexities.
You're done when
One optimization carries a written equivalence report with exact-match, perplexity-difference and task spot-check results against predeclared tolerances.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 12 more in the section
- AI Systems Performance Engineering - Chapters 13, 15 and 16Chris Fregly · primary
Read Chapter 13 on profiling and tuning PyTorch, Chapter 15 on inference parallelism, decoding and routing, and Chapter 16 on profiling and debugging inference. Keep Chapters 17 to 19 for GPU-9 and depth.
- AI Systems Performance Engineering companion code - Chapters 12 to 16Chris Fregly · required
Use compatible examples from
code/ch12throughcode/ch16. Trace whether each optimized path changes a kernel, graph, compiler choice, scheduler or library dispatch, then integrate one bounded custom path into a realistic operator or small endpoint.
Also in this section
- AI Performance Engineering - Inference EnginesWafer · reference
A curated index. Use Section 4 only to find the introducing paper and implementation for the mechanism your measurement points to.
- PagedAttention and vLLMvLLM Authors · required
Study block-based key-value allocation, sharing and scheduling interaction. Trace logical token positions to physical blocks in one engine run and quantify fragmentation and memory-capacity effects.
- SGLangSGLang Authors · support
Read the runtime and RadixAttention design, then inspect the repository path for one kernel or prefix-reuse interaction. Use it as an alternative architecture in the integration defense.
- LeetGPU - Inference Kernel SetAlphaGPU · required
Choose three bottleneck-matched challenges from 74 GPT-2 Block, 83 Fused Residual Add RMS Norm, 84 SwiGLU MLP Block, 87 Speculative Decoding Verification, 93 Llama Transformer Block and 96 INT8 KV Cache Attention. Integrate one result locally rather than stopping at the hosted submission.
- FlashInferFlashInfer Project · support
Use the repository as the serving-kernel baseline and interface reference. Reconstruct workspace planning, layouts, dispatch and stream behavior for one selected operation before comparing your path.
- GPU Microbenchmark and Kernel Suite - IntegrationRoadmap-Final · support
Complete the real tensor or model-operation integration, dispatch and fallback requirements. Report compilation and invocation overhead, workload frequency, correctness or quality and the end-to-end no-benefit regime.
- PyTorch 2.14 ProfilerPyTorch · reference
Read the Overview example plus the API reference for
torch.profiler.profile(activities,schedule,on_trace_ready,record_shapes,with_stack),torch.profiler.record_functionandexport_chrome_trace. Use it for exact profiler and NVTX-range call contracts missing from the book. - Orca (OSDI 2022)USENIX · support
Read Sections 3 to 4 for iteration-level scheduling and selective batching, and Section 6 for the engine microbenchmark and end-to-end latency-throughput method. Use it as the continuous-batching mechanism behind the book summary.
- Sarathi-ServearXiv · support
Read Sections 3 to 4 for chunked-prefill stall-free batching and token-budget selection, and Section 5 for capacity and overhead method. Use it as the chunked-prefill mechanism behind the book summary.
- Fast Inference from Transformers via Speculative DecodingPMLR · support
Read Sections 2 to 3 for the draft-verify-accept loop, the acceptance rule and the walltime-versus-operations analysis. Use it for the verification cost model behind the engine guides.
- vLLM Documentation - Automatic Prefix CachingvLLM Project · reference
Read Automatic Prefix Caching (vLLM v0.31.0) for hash-based block reuse, full-block caching, reverse-order freeing and the multimodal hashing example. Use it for engine behavior the papers do not version.
- Transformer Inference ArithmeticKipply · reference
Read kv cache, capacity, latency calculations, batch sizes and flops counting for per-token KV bytes, weight-capacity arithmetic and memory-bound versus compute-bound latency floors. Use it to derive endpoint bounds before measuring.