Unit 4 of 13 · about 3 hours · derive

Prefill and decode operation counts per request

Operation counts are the numerator of every intensity and bound. A count that mixes prefill with decode corrupts all of them.

You'll be able to

  • Derive dense operations per token as from the qkv, output and MLP walk.
  • Derive prefill attention and decode attention counts separately and state when attention rivals dense work.
  • State what a FLOP count omits and when the omission stops being safe.

Covers

Approximate transformer prefill operationsApproximate autoregressive decode operations per token
1

Read

In this order, only the parts listed

0 of 4 done

  1. Dense walk: 2P operations per tokenTransformer Inference Arithmetic

    flops counting with the How many flops in a matmul box in kv cache (qkv, output and MLP sum to about ; 52B example at 51.5B)

    The count covers dense weights once per token in prefill and decode alike. Attention comes on top and grows with prompt length in prefill.

  2. Linear and attention operationsHow to Scale Your Model - Inference

    Linear operations: what bottlenecks us? with per matmul, and What about attention? with for scores plus values

  3. Prefill versus decode work with numbersLLM Inference: From scratch, one token at a time - Modules 01, 02 and 04

    Prefill compute-bound and decode memory-bound with per-token matmul and attention terms (16.1 GFLOP per token for Llama-3-8B); Math by hand at with 32.9 TFLOP dense plus 2.2 TFLOP attention

  4. Matmul and attention intensity100 Days of LLM Inference - Days 1, 2, 5 and 6

    day06/ops-byte-ratio.ipynb: matmul comp=2MKN with mem=(MK+KN+MN)*2, attention mem=8N^2+8Nd with comp=4N^2d+3N^2, prefill compute-bound versus decode memory-bound

    Use the count formulas only. The GB10 timings are the author's hardware result, not your target; your target is the crossover and the knee on your GPU in a later section.

2

Focus on

  • One matmul through all params costs by the rule. The qkv, output and MLP walk sums to the same within 2%.
  • Decode attention per token scales with cached length; prefill attention scales with prompt length squared. At 8192 cached tokens the invented model adds to dense.
  • Softmax and norms are per layer, and sampling plus unembedding run once per step, against dense per layer. They matter only when dense shrinks or a profile says so.
  • Attention work uses query heads times head dim , because every query head scores its group; KV bytes use KV heads times . Neither uses model width where the heads differ from it.
Common mistakes · 3
  • Taking per token as the whole prefill cost. Prefill pays dense per prompt token plus attention that grows with prompt length squared; for Llama-3-8B the attention term passes the dense term near 32k.
  • Writing the attention scale as division by head dim. The implemented scale is ; the count is unchanged but a later kernel must use the root.
  • Calling decode attention free because dense dominates. At 8192 it is nearly half the dense count; recompute the share before dropping it.
3

Try it yourself

Closed-book, before checking anything

Closed-book, derive decode operations per token for the invented 18.4e9-param model at cached length 8192: dense , attention , total about .
4

Quiz yourself

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

0 got · 0 missed

  1. 1.How many dense operations does one decode step take for the invented 18.4e9-param model?Answer

    About , from .

  2. 2.At cached length 8192, what is its decode attention count and share?Answer

    , nearly half the dense count, so it cannot be dropped there.

  3. 3.Why is per token not the whole cost of a prefill at ?Answer

    counts dense once per token (32.9 TFLOP for 8B at 2048). Prefill adds about 2.2 TFLOP of attention there, and at longer prompts attention dominates.

  4. 4.Without a cache, how does per-step work grow with length ?Answer

    Each step reruns the full forward over all tokens (the KV projections alone are about of a one-token forward pass), so totals grow quadratically.

5

Practice

  • 100 Days of LLM Inference Day 06: ops-byte experiments

    day06/ops-byte-ratio.ipynb, Try These Experiments: redo intensity with , find the crossover batch with cuda.get_device_properties, and the 7B fp16 14GB with 14 GFLOP per token calc

    Show every substitution with prefill and decode kept apart. Fix the matmul_intensity cell first: a typo (ompute) makes its stored batch sweep wrong. Then check the README's batch-64 crossover against the H100 ridge it quotes; this journal is practice, not authority.

You're done when

You derive the 5.4e10 decode count at 8192 without notes and complete the redo with the crossover stated.

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.

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

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

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

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