Unit 9 of 13 · about 4 hours · explain

One request through the engine, from API to detokenizer

An optimization without a lifecycle map optimizes the wrong stage. Every later queue, cache and kernel claim hangs off this path.

You'll be able to

  • Trace one request from API through tokenizer, queue, admission and scheduler with owners named.
  • Trace it through block manager, model runner, sampler and detokenizer to streaming output.
  • Name the measurement points that falsify a bottleneck hypothesis.

Covers

API, tokenizer, queue, admission and scheduler lifecycleBlock manager, model runner, sampler and detokenizer lifecycle
1

Read

In this order, only the parts listed

0 of 4 done

  1. Engine orchestration and JetStreamHow to Scale Your Model - Inference

    Designing an Effective Inference Engine: Continuous batching with queue, prefill, generate, cache and stream orchestration; Prefix caching; Let's look at an implementation: JetStream with prefill and generate engines, controller and transfer thread

  2. Serve, stream and batch with vLLMHands-On LLM Serving and Optimization - Chapters 2 and 5

    Chapter 2, Serve the LLM (Qwen) with vLLM (pp 57-59) with LLM, SamplingParams and llm.generate; LLM Streaming Serving Basics (pp 60-61) with engine.generate and engine.abort; LLM Batch Serving Basics (pp 61-63) with batched llm.generate at 2.2x for 4 prompts

  3. Tiny engine request pathNano-vLLM tiny serving engine

    sequence.py with SequenceStatus WAITING, RUNNING and FINISHED plus block_table; scheduler.py with waiting and running sets, schedule, preempt and postprocess; model_runner.py with prepare_prefill, prepare_decode and run; llm_engine.py with generate, add_request and tokenizer.decode

  4. Batching and online versus offlineMachine Learning Engineering Open Book - Inference

    Batching with Static versus Continuous batching; Online vs Offline inference for interactive latency versus batch throughput

2

Focus on

  • The GPU unit One request through prefill and decode, and the shapes that set its cost gives tensor shapes; here follow ownership: API to tokenizer to queue to admission to scheduler to block manager to runner to sampler to detokenizer to stream.
  • Waiting holds admitted but unscheduled requests; running holds scheduled with blocks. schedule moves waiting to running on can_allocate; preempt returns running to waiting.
  • Prefill writes cache for the whole prompt and returns first logits; decode reads full cache, samples one token and appends one pair. prepare_prefill and prepare_decode build different block_tables and slot maps.
  • Each handoff is a measurement point: arrival, tokenized, queued, scheduled, prefill done, first token, each decode gap, sampled, streamed and freed. A bottleneck claim must name which gap moved.
Common mistakes · 3
  • Treating llm.generate as streaming. It blocks until all outputs finish; only engine.generate yields RequestOutput chunks during the run.
  • Calling the scheduler queue the only queue. Tokenizer, admission, block allocation and detokenizer queues add waits with different owners.
  • Skipping the transfer thread in disaggregated paths. Prefill and decode engines plus controller plus transfer each hold state that must be traced.
3

Try it yourself

Closed-book, before checking anything

Closed-book, walk one prompt through the tiny engine: add_request creates a WAITING Sequence, schedule moves it to running after can_allocate and allocate, prepare_prefill then prepare_decode run the model, postprocess appends tokens until FINISHED, and tokenizer.decode renders output. Name the owner that frees blocks.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.What moves a request from waiting to running in the tiny engine?Answer

    schedule after can_allocate succeeds, followed by allocate filling block_table. Without free blocks it stays waiting or a running request is preempted.

  2. 2.What differs between prepare_prefill and prepare_decode?Answer

    Prefill builds tables and slot maps for the whole prompt and writes cache; decode maps one new token per sequence against the full cache and appends one pair.

  3. 3.Where do TTFT and per-token latency attach on this path?Answer

    TTFT spans arrival through scheduled prefill to first streamed token. Per-token latency spans one decode step with cache read, sample and stream.

  4. 4.Which lifecycle evidence falsifies a queueing versus execution claim?Answer

    Arrival-to-start versus start-to-done splits with queue depth. Queue growth with flat execution implicates scheduling and load, not the model.

5

Practice

  • Hands-On LLM Serving companion: LLM execution walkthrough

    ch02/ch2_Workthrough_LLM_execution.ipynb: Examples 2-1 and 2-2 token-by-token without and with past_key_values and use_cache

    Run on a small model. Record arrival, prefill, first-token, decode gaps and detokenized output; the cached run stays stable after the first token.

You're done when

You walk one request end to end without notes, and your walkthrough run shows cached decode stable after the first token.

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.

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

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

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

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