Unit 2 of 13 · about 4 hours · derive, measure

Weight memory by dtype and the runtime memory categories

Memory sets the maximum batch before timing starts. A fit that forgets precision, file overhead or allocator reserve fails at load time.

You'll be able to

  • Derive weight bytes from parameter count and stored bytes per value, keeping stored and execution precision apart.
  • Write a runtime budget with weights, KV, activations, workspace, graphs and allocator reserve, and fit a batch under capacity.
  • Measure resident weights and reserve on your GPU and name what the estimate omitted.

Covers

Parameter count and weight memory by dtypeRuntime, workspace, graph and allocator memory categories
1

Read

In this order, only the parts listed

0 of 4 done

  1. Estimating model size and batch reserveHands-On LLM Serving and Optimization - Chapters 2 and 5

    Chapter 5, Estimating Model Size (pp 172-177): 7B times 2 bytes is 14 GB, config.json torch_dtype, Table 5-6 precision bytes; Estimating KV Cache Size with Table 5-7 (A10 10 GB left gives 5 theory but 4 served; L40S 34 GB left gives 17 theory but 16 served) and the 2x model-size reserve rule

  2. LLaMA-2-13B bytes and batch tablesHow to Scale Your Model - Inference

    What about memory? (bf16 26 GB weights, 80 MB activations versus 6.7 GB cache at 8192 context) and Modeling throughput and latency for LLaMA 2-13B with both batch tables

    The tables label memory GiB but divide decimal gigabytes by bytes per second. Recompute in bytes and keep GB apart from GiB.

  3. Weight bytes and model loadingMachine Learning Engineering Open Book - Inference

    Anatomy of Model's Memory Usage, Model Weights: bytes = bytes_per_param * num_params with fp32 4 down to 1-bit 0.125 and MXFP8 1.03125, Llama-3.1-8B bf16 16 GB; Speeding up model loading time with pre-sharded weights and prebuilt engines

  4. Serving arguments that set runtime memoryHands-On LLM Serving and Optimization - Chapters 2 and 5

    Chapter 2, Serve the LLM (Qwen) with vLLM (pp 57-59): LLM with swap_space, max_model_len, block_size, max_num_seqs and enable_prefix_caching beside SamplingParams (the book also prints enable_cuda_graph=True and max_num_sequences, which are not vLLM 0.31.0 arguments; use enforce_eager and max_num_seqs)

    Read the argument list as the runtime lines to budget. Tuning them belongs to later sections.

2

Focus on

  • Weight bytes are count times stored bytes per value. Execution precision can differ, as int8 weights with bf16 compute, and changes intensity later, not this line.
  • The file holds more than learned params. GPT-2 holds 137,022,720 values (522.7 MiB in fp32) against 124,439,808 learned params; its 12,582,912 causal-mask values explain the gap.
  • Budget weights first, then KV, then activations, workspace, graphs and allocator. The book reserves about twice model size and still serves one less than theory in Table 5-7.
  • Activations are megabytes beside gigabytes of cache at long context, but they set the workspace line that stops a theoretical fit from loading.
Common mistakes · 3
  • Reading the name as the count. Llama-2-7b is about 7e9 params, and its bin reads about 13 GB against the 14 GB product; publish the exact count.
  • Counting tied embeddings twice. Shared input and output matrices contribute once to weight bytes.
  • Treating the Table 5-7 quotient as servable. Reserve, workspace, graphs and fragmentation take the last slot; state the overhead line.
3

Try it yourself

Closed-book, before checking anything

Closed-book, derive 7B fp16 as bytes, 8B bf16 as bytes, 13B bf16 as bytes, and GPT-2 learned versus file as bytes against bytes (522.7 MiB).
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Qwen2.5-0.5B holds 494,032,768 params. What are its bf16 weight bytes?Answer

    bytes, about 0.99 GB. Count tied embeddings once.

  2. 2.Why does the 7B bin read about 13 GB when the product says 14 GB?Answer

    The name is rounded and the exact count is smaller. The product with the exact count plus header explains the bin; the name alone does not.

  3. 3.A10 holds 24 GB with 14 GB weights and 4096 context at 0.5 MB per token. Why does it serve 4, not 5?Answer

    in theory, but activations, workspace and allocator take the last slot. The book serves 4 and keeps the reserve explicit.

  4. 4.When do activations stop being negligible?Answer

    At short context with large batch, where cache per request is small and workspace plus graphs set the limit. At 8192 context they are 80 MB against 6.7 GB cache.

5

Practice

  • Hands-On LLM Serving companion: inside the transformer

    ch02/ch2_Inside_the_Mind_of_a_Transformer.ipynb: run print_module_structure on Qwen2.5-0.5B and reconcile the summed params with 494,032,768

    Sum by matrix before trusting the config total, and record stored versus execution dtype for the later intensity unit.

You're done when

Your weight lines match 14, 16 and 26 GB plus the GPT-2 file split, and your budget names the reserve that explains the Table 5-7 gap.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 15 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.

  • 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.

  • 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.

Also in this section

  • 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: 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.

  • 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.

  • 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.

  • 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) and from_pretrained revision (branch, tag or commit id, default main). Use the saved config.json as the identity record beside the book config dumps.

  • Hugging Face Transformers - chat templatesHugging Face · reference

    Read apply_chat_template with role and content dicts, the Mistral versus Zephyr control-token examples, and add_generation_prompt for 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.py for request state, scheduler.py for waiting and running sets, block_manager.py for allocate, append, deallocate and prefix-hash reuse, model_runner.py for prefill and decode steps, and llm_engine.py for 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, hey or ab; write the small Python generator in the load-generator unit instead.