Unit 10 of 13 · about 4 hours · explain, implement
Streaming, cancellation, failure and cleanup states and ownership invariants
A cancelled request still owns blocks, streams and sampler state until someone frees them. Leaks and double frees hide there.
You'll be able to
- State ownership invariants and cleanup obligations at every request transition, including cancellation and failure.
- Instrument state transitions and resource ownership in a minimal serving path.
- Diagnose lost, duplicated, leaked or double-freed requests from state and resource traces.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Streaming and abortHands-On LLM Serving and Optimization - Chapters 2 and 5
Chapter 2, LLM Streaming Serving Basics (pp 60-61):
engine.generatewithrequest_id,async for request_outputwithchunk.text, andengine.abort(request_id)for cancellation - Scheduler and block ownershipNano-vLLM tiny serving engine
scheduler.pywithwaiting,running,preemptandpostprocess;block_manager.pywithref_count,free_block_ids,used_block_ids,allocate,deallocateandcan_append;sequence.pywithSequenceStatusWAITING, RUNNING and FINISHED - Failure, correctness and trace requirementsLLM Inference Systems Laboratory - Workload and Baseline
Milestone B for correlated events, observer overhead and trace queries over TTFT and every decode gap; Milestone D with Failure-injection requirements for cancellation and disconnect at every phase and every terminal phase; Correctness requirements for KV ownership, refcounts, cleanup and scheduler invariants
Focus on
- Cancellation can arrive in queue, prefill, decode or streaming. Abort must stop scheduling, free blocks, close the stream and mark exactly one terminal state.
- One owner per block with
ref_count; one terminal mark perrequest_id. Freeing asserts zero refs; draining leaves no used blocks and no waiting or running entries. - Failure, cancellation and timeout differ in trigger but share cleanup. Retries need idempotent handling by
request_idor they duplicate work. - Instrument each transition with
request_id, state, owner and timestamps. Trace queries must explain TTFT and every decode gap without per-token sync overhead.
Common mistakes · 3
- Freeing blocks without removing the request from scheduler sets. The freed blocks get reallocated while the stale entry still schedules.
- Marking terminal twice. Stream close plus scheduler free can emit two completions unless one path owns the mark.
- Retrying a cancelled
request_idwithout idempotence. The retry duplicates sampler and stream side effects or loses the cancellation.
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.Where can cancellation arrive, and what must abort do?Answer
Queue, prefill, decode or streaming. Stop scheduling, free blocks, close the stream and mark one terminal state.
2.What holds at a clean drain?Answer
No used blocks, empty waiting and running sets, and each
request_idwith exactly one terminal mark.3.How do traces distinguish lost, leaked and double-freed requests?Answer
Lost has no terminal mark; leaked has a terminal mark but held blocks; double-freed shows two frees or a refcount assert.
4.Why must retries be idempotent by
request_id?AnswerA retry after cancel or failure must not duplicate sampler, cache or stream effects. The id owns dedup and cleanup.
Practice
- Hands-On LLM Serving companion: streaming with abort
ch02/ch2_Streaming.ipynbwithch02/streaming.py: stream withengine.generateand cancel one mid-stream request withengine.abort(request_id)Record request state and block use before and after abort. Assert single terminal output and no held blocks.
You're done when
Your state machine passes one success plus two cancels with no leaks and single marks, and your streaming abort run shows freed blocks.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 15 more in the 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.
- 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.
- 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.
Also in this 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.
- 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.
- 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.
- 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).
- 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.