Unit 3 of 13 · about 4 hours · derive
KV bytes per token across MHA, GQA, MQA and MLA, and allocated capacity
KV decides batch before compute matters. Head grouping moves bytes by 4x to 32x, and allocation waste decides what fits.
You'll be able to
- Derive KV bytes per token for MHA, GQA, MQA and MLA from layers, KV heads, head dim and bytes.
- Distinguish logical cache bytes from allocated bytes with pages, waste and reserve, and fit allocated capacity.
- Check the fit against your own worksheet for the same configuration.
Covers
Read
In this order, only the parts listed
0 of 4 done
- KV bytes and attention variantsMachine Learning Engineering Open Book - Inference
Anatomy of Model's Memory Usage, KV Caching: bytes per token as dtype times 2 times layers times hidden times KV heads over attention heads; Llama-3.1-8B bf16 GQA at 0.131 MB per token with bs1x1024 at 134 MB and bs128x1024 at 17.2 GB; MHA 4x, MQA 8x less, MLA via DeepSeek-v3
- Cache tables, GQA cuts and pagingHow to Scale Your Model - Inference
What about memory? with 13B bf16 6.7 GB at 8192 context; Modeling throughput and latency for LLaMA 2-13B with both batch tables; Tricks for Improving Generation Throughput and Latency for GQA ratio cuts, quant and PagedAttention; Worked Problems Questions 1 and 2
The batch tables label GiB but divide decimal gigabytes. Recompute in bytes. In Question 2, dropping to one KV head raises the batch from 7 to about 56.
- GQA multiplier, fragmentation and two-regime budgetLLM Inference: From scratch, one token at a time - Modules 01, 02 and 04
What is stored with
kv_bytes = 2*n_layers*n_kv_heads*head_dim*seq_len*batch*dtype_bytes; The GQA multiplier with the 70B MHA versus GQA-8 versus MQA table; Fragmentation with 97.6% waste and 20.4-38.2% useful; The two-regime memory budget with crossover atbatch*seq_len = weight_bytes/kv_per_token - KV sizing notebook100 Days of LLM Inference - Days 1, 2, 5 and 6
day05/kv-cache.ipynb: Memory Cost withkv_bytes=2*n_layers*n_embd*seq*bytes, Benchmark 518 ms to 196 ms at length 200, Try These Experiments for slope versus step and 300 and 500 lengthsVerify the slope formula against your own GPT-2 run. The notebook's formula uses
n_embd, which ignores GQA, so its Llama 3 rows overstate KV by the query-to-KV head ratio (4x for 8B, 8x for 70B); recompute them with KV heads at your precision and length.
Focus on
- KV bytes per token are . The shortcut assumes KV width equals model width and breaks under GQA and MQA.
- Llama-2-7b uses 524,288 bytes per token in fp16; Llama-3.1-8B uses 131,072 bytes in bf16 GQA-8, or 4x with MHA and 8x less with MQA; the invented model uses 262,144 bytes in int8.
- MLA compresses keys and values to a latent vector, as in DeepSeek-v3. It is not fewer heads; use latent width for its bytes.
- Logical bytes are not servable bytes. Pages,
max_model_lenover-allocation,reserved_memoryand fragmentation decide the fit; a 200-token request in an 8192 reservation wastes 97.6%.
Common mistakes · 3
- Using query heads for KV bytes. Llama-3.1-8B has 32 query heads but 8 KV heads; using 32 overstates bytes by 4x.
- Treating MLA as a head count. Its saving comes from latent compression, so recompute from latent width.
- Fitting logical bytes. The planner divides by per-request bytes with reserve ; omitting or page waste overstates batch.
Try it yourself
Closed-book, before checking anything
Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.What are KV bytes per token for a 40-layer, 8 KV head, 128-dim model in int8?Answer
bytes.
2.The invented model in bf16 uses what per token, and what would full MHA with 32 KV heads use?Answer
524,288 bytes in bf16 (262,144 in int8). Full MHA at 32 KV heads would use 2,097,152 bytes in bf16.
3.70B GQA-8 uses 327,680 bytes per token in fp16. What does single-head MQA use?Answer
40,960 bytes, an 8x cut. Capacity grows by about 8x before reserve and waste.
4.Why does a 200-token request waste 97.6% in an 8192 reservation?Answer
The reservation holds 8192 times per-token bytes (about 2.5 GiB for 70B) while 200 tokens use 62.5 MiB. Paging and exact reservation remove most of this.
Practice
- TensorTonic: Plan KV-Cache Capacity
Function
kv_cache_capacity_plannerreturningmodel_bytes,kv_bytes_per_request,max_batch_size,seconds_per_token,tokens_per_second; public cases check 27-fit, zero-fit when the model exceeds memory, and single-KV-head 18-fitDerive by hand first with , , as the floor of and . Then check the answer against your own worksheet for the same config.
You're done when
Your hand-derived 524,288, 131,072 and 262,144 match, and the planner passes the three public cases.
Only when you can do this without notes.
Leads to
Notes
Resources · 4 for this unit, 14 more in the section
- How to Scale Your Model - InferenceJAX Team · primary
Read the complete inference chapter for model, KV, batching, parallelism and capacity arithmetic. Reproduce every equation for one fixed model and workload, then use the public serving companion and book overview to connect the quantities to the request lifecycle.
- LLM Inference: From scratch, one token at a time - Modules 01, 02 and 04Tushar Amrit · support
Work the "Math by hand" and checkpoint parts of The Autoregressive Loop, The KV Cache and Metrics and the Roofline. Redo each worked number for your own model before reading the solution.
- Machine Learning Engineering Open Book - InferenceStas Bekman · required
Use inference/README.md for the prefill/decode distinction, memory formulas, MHA/GQA/MQA/MLA comparison and current glossary. Treat unfinished sections as a reference boundary, not as the main course.
- 100 Days of LLM Inference - Days 1, 2, 5 and 6Elizabeth Thomas · support
Run only the four named notebooks for request anatomy, model configuration, KV sizing and roofline orientation. Verify every formula independently because this public learning journal is a useful practice supplement, not the authority.
Also in this section
- Hands-On LLM Serving and Optimization - Chapters 2 and 5Chi Wang and Peiheng Hu (O'Reilly) · required
Read Chapter 2 for the decoder walk-through, the KV cache and the prefill and decode phases, and the Chapter 5 sections that estimate model size and KV-cache size. Run the Chapter 2 companion notebooks on a small model and redo every size estimate for the model you will serve.
- Transformer Inference ArithmeticKipply · required
Re-derive weight bytes, KV bytes per token, prefill work, decode work and arithmetic intensity with explicit units. Replace every example constant with your model configuration and compare the estimates with the book.
- LLM Inference Handbook - Key metrics for LLM inferenceModular · reference
Use the TTFT, TPOT and ITL definitions, and the difference between request-weighted average TPOT and token-weighted average ITL, when you define your own metrics.
- Stanford CS336 - Inference LectureStanford University · support
Watch the inference lecture once after the arithmetic reading. Pause to reproduce its model-memory and phase-bottleneck calculations; advanced serving mechanisms are routed to their later stages.
- TensorTonic Language Modeling from Scratch - Plan KV-Cache CapacityTensorTonic · support
Solve after the KV-bytes unit, then check the answer against your own worksheet for the same configuration.
- AI Performance Engineering - Minimum Mental ModelWafer · reference
A curated, dated index. Use Start Here only to find a primary source the other entries lack.
- LLM Inference Systems Laboratory - Workload and BaselineRoadmap-Final · support
Start the immutable workload manifest, deterministic fake server, request-state trace and arithmetic planner. Keep this same repository through INF-9 so later comparisons preserve the contract.
- Hugging Face Transformers - model configuration and revisionHugging Face · reference
Read PreTrainedConfig common attributes (
vocab_size,hidden_size,num_attention_heads,num_hidden_layers) andfrom_pretrainedrevision(branch, tag or commit id, defaultmain). Use the savedconfig.jsonas the identity record beside the book config dumps. - Hugging Face Transformers - chat templatesHugging Face · reference
Read
apply_chat_templatewith role and content dicts, the Mistral versus Zephyr control-token examples, andadd_generation_promptfor starting an assistant reply. Compare the template output token count with the raw prompt count. - Etalon: Holistic Performance Evaluation Framework for LLM Inference SystemsAgrawal et al. · support
Read Sections 2.2, 3.1 and 4.1 with Algorithm 1 and Figures 1 to 3 for TTFT, TBT, TPOT, normalized latency, capacity and fluidity-index; Section 4.2 for black-box and capacity recipes; Section 5.1 for hourly runs over 24 hours and LMSys-Chat-1M medians (417 median, 1418 p90 prefill tokens).
- DistServe: Disaggregating Prefill and Decoding for Goodput-optimized LLM ServingZhong et al. (OSDI 2024) · support
Read Section 1 with Figure 1 for per-GPU goodput: the highest request rate served while a target share of requests meets the TTFT and TPOT SLOs (13B model on one A100 reaches about 1.6 requests per second at 90% attainment).
- Nano-vLLM tiny serving engineGeeeekExplorer · reference
Read
nanovllm/engine/sequence.pyfor request state,scheduler.pyfor waiting and running sets,block_manager.pyfor allocate, append, deallocate and prefix-hash reuse,model_runner.pyfor prefill and decode steps, andllm_engine.pyfor the generate path. Trace one request through these files only; do not adopt the engine for load measurement. - Inference EngineeringPhilip Kiely (Baseten Books) · support
Read Sections 1.4 to 1.4.2 for TTFT, TPS, percentiles and end-to-end versus inference-only time; Section 4.5 with 4.5.1 for benchmark dimensions, tooling and eval inputs; Section 6.1 for vision encoders, image tokens and longer-context effects.
- Gil Tene - How NOT to Measure Latency (talk)Strange Loop Conference via YouTube · reference
Use for coordinated-omission vocabulary only: closed-loop testers that wait for each reply, the missing samples under queueing, and the correction concept of recording intended send time. Do not adopt
wrk,heyorab; write the small Python generator in the load-generator unit instead.