Unit 8 of 12 · about 6 hours · implement
A continuous-batching simulator with deterministic replay and event traces
Policies cannot be compared on a live server with random arrivals. A deterministic simulator with event traces turns scheduling opinions into checkable claims before touching a real engine.
You'll be able to
- Implement a continuous-batching simulator with admission, token and memory budgets, chunking, preemption, priority, cancellation and overload.
- Replay a fixed workload deterministically and emit per-request state and timing traces.
- Compare two policies from request traces rather than aggregate throughput alone.
Covers
Read
In this order, only the parts listed
0 of 5 done
- Nano-vLLM engine loop as the simulation skeletonNano-vLLM - Scheduler, Block Manager and Engine Loop
LLMEngine.stepinnanovllm/engine/llm_engine.py: schedule, model call, postprocess; mirror it as admit, step, complete and free in your simulator, withScheduler.schedule,preemptandpostprocessinnanovllm/engine/scheduler.pyas the policy surface - Orca scheduling algorithm as the correctness baselineOrca: A Distributed Serving System for Transformer-Based Generative Models
Section 4.2 Algorithm 1 with
Selectin arrival order,max_bscap andmax_tokensreservation; hand-trace one small timeline through it before trusting your simulator on the same input - Deterministic replay contractTensorTonic Language Modeling from Scratch - Simulate Continuous Decode Batching
The
continuous_batching_schedulerstatement: arrival-time ordering with input-order tiebreaks, admission before decoding and again after completions release capacity, idle-gap skipping, and recorded step dicts with admitted, active, finished andkv_tokens_in_useas actual use - Mini-SGLang scheduler loop and driver scriptMini-SGLang - Scheduler and Overlap Scheduling
Scheduler._schedule_next_batchwithPrefillManager.schedule_next_batch(prefill_budget)and overlap against normal loop inpython/minisgl/scheduler/scheduler.py; the manual end-to-end driver intests/core/test_scheduler.pyas a single-prompt loop (it sends one request and drains detokenizer messages; it emits no scheduler traces, so record them in your own simulator) - Scheduler laboratory pathLLM Inference Systems Laboratory - Scheduler
The scheduler and KV checkpoints and the contribution requirement: a recorded corpus with priority and cancellation distributions, no-overcommit and bounded-overload invariants, and one contribution carried through the real engine path with a reference fallback and versioned configuration
Focus on
- One loop does everything: admit arrivals, assemble the iteration within budgets, advance one step, retire finished requests and free their state. Every policy is a different admit-and-assemble rule inside that loop.
- Determinism needs a fixed request corpus, a fixed seed and a recorded configuration. Same inputs must yield byte-identical traces, including preemption and cancel events.
- Trace per request, not per batch: arrival, admit, each state move, preemptions, cancel and completion with timestamps. Policy differences hide in request timelines that batch averages erase.
- The simulator proves scheduling logic, not speed. Execution times, kernel shapes, cache reuse and host overhead are modeled coarsely, so every simulated win needs a bounded real-engine check later.
Common mistakes · 3
- Iterating over sets or dicts for admission order. Iteration order is not arrival order, so the replay diverges run to run; sort explicitly by arrival time and input order.
- Recording state after the first admission pass. Completions free capacity for a second pass in the same step, so record after the second pass or the trace understates fill.
- Quoting simulator milliseconds as engine results. The cost model is approximate by construction; the simulator ranks policies and the engine decides by how much.
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 three inputs must be fixed for a deterministic replay?Answer
The request corpus with arrivals and lengths, the random seed, and the full scheduler configuration. Any one of them drifting breaks trace equality.
2.Why record traces per request instead of per batch?Answer
Batch aggregates average away who waited, who preempted and who starved. Request timelines show which policy decision caused each delay.
3.Your simulator says policy X beats Y by 30%. What is still unknown?Answer
Whether the win transfers: real execution times, kernel shapes, cache reuse and host overhead differ from the model, so X needs a bounded real-engine run before the claim stands.
4.Where does the second admission pass fit in one simulated step?Answer
After completions release capacity and before recording. Admit, decode, complete, admit again, then record admitted, active, finished and tokens in use.
You're done when
Two runs of your simulator on the fixed corpus produce identical traces, and your hand trace matches the implementation exactly.
Only when you can do this without notes.
Leads to
Notes
Resources · 5 for this unit, 13 more in the section
- Orca: A Distributed Serving System for Transformer-Based Generative ModelsUSENIX OSDI · required
Study iteration-level scheduling and selective batching, including the workload assumptions. Reproduce one scheduling timeline by hand and use it as the correctness baseline for the simulator.
- Nano-vLLM - Scheduler, Block Manager and Engine LoopGeeeekExplorer · required
Trace scheduler.py with llm_engine.py and block_manager.py. Add event logging in your own fork or project, explain every transition, and implement one bounded admission or chunking change with regression tests.
- Mini-SGLang - Scheduler and Overlap SchedulingSGLang Project · required
Read docs/structures.md, scheduler implementation and tests/core/test_scheduler.py, then compare overlap scheduling with the Nano-vLLM loop. Use the online benchmark only after fixing the same workload and hardware contract.
- TensorTonic Language Modeling from Scratch - Simulate Continuous Decode BatchingTensorTonic · support
Solve after the continuous-batching unit, then compare its admission rule with your own simulator.
- LLM Inference Systems Laboratory - SchedulerRoadmap-Final · support
Add token and memory admission, chunking, priority, cancellation, overload and fairness to the simulator, then carry one policy through the real engine path with a reference fallback.
Also in this section
- Hands-On LLM Serving and Optimization - Chapter 6, batching and schedulingChi Wang and Peiheng Hu (O'Reilly) · primary
Read "Request Batching and Scheduling-Level Optimizations" in Chapter 6: dynamic, continuous and chunked-prefill batching. Rebuild each policy in a small event simulator and state the user-visible metric it can improve or harm.
- Sarathi-Serve: Tackling Throughput-Latency Tradeoffs in LLM InferenceMicrosoft Research · required
Focus on chunked prefills, stall-free batching and the throughput-latency trade-off. Implement a fixed-token chunk policy and preserve a workload where chunking loses to the simpler scheduler.
- AI Systems Performance Engineering - Chapters 16 and 18, scheduling and admissionChris Fregly (O'Reilly) · required
Read "Dynamic Batching, Scheduling, and Routing" in Chapter 16 and "SLO-Aware Request Management and Fault Tolerance" in Chapter 18 (early rejection, quality of service).
- AI Systems Performance Engineering - Continuous Batching LabChris Fregly · support
Run the Chapter 15 baseline and optimized continuous-batching pair under CPU-safe or available-GPU settings. Inspect the shared comparison contract and re-measure rather than quoting bundled deltas.
- LLM Inference: From scratch, one token at a time - Module 05Tushar Amrit · support
Work the Batching module's arithmetic and checkpoint before the static and continuous batching units.
- vLLM v0.31.0 serve CLI and scheduler argumentsvLLM Project · reference
Look up scheduler flags and defaults:
--max-num-seqs,--max-num-batched-tokens,--max-num-active-seqs,--enable-chunked-prefill,--long-prefill-token-thresholdand--scheduling-policy. Runtime defaults vary by GPU class, so check them against the installed v0.31.0 behavior. - vLLM v0.31.0 metrics designvLLM Project · reference
Read the WAITING, RUNNING and PREEMPTED request states and the queue, inference, prefill and decode interval definitions. Swapped-preemption metrics are legacy in v1. The exported counters, including
vllm:num_requests_waiting_by_reasonandvllm:num_preemptions, are listed on the Production Metrics page, https://docs.vllm.ai/en/v0.31.0/usage/metrics/ - vLLM v0.31.0 benchmark CLIvLLM Project · support
Use
vllm bench servewith--request-ratefor offered-load sweeps, andvllm bench throughputandvllm bench latencyfor offline endpoint and phase baselines. Fix the dataset, lengths, request rate, warmup and sampling, and keep raw per-request results; do not copy example rates as targets. - vLLM v0.31.0 online servingvLLM Project · reference
Read the
/abort_requestsendpoint and the Responses cancel API for request cancellation. Verify client-disconnect aborts on your engine; the page does not cover them. - vLLM v0.31.0 LoRA adaptersvLLM Project · reference
Read per-request
LoRARequestserving, server-wide--lora-moduleswithmax_lorasandmax_lora_rank, and why adapter-slot pressure rewards grouping same-adapter requests. - vLLM v0.31.0 structured outputsvLLM Project · reference
Read the xgrammar and guidance backends, the
choice,regex,json,grammarandstructural_tagoptions inStructuredOutputsParams, and the--structured-outputs-config.backendflag. - vLLM v0.31.0 multimodal inputsvLLM Project · reference
Read
limit_mm_per_prompt, content hashing withmulti_modal_uuidsin Cached Inputs, and the video pruning flags as examples of encoder-side scheduling cost. - TensorTonic Language Modeling from Scratch - Route Cache-Aware Prefill RequestsTensorTonic · support
Solve after the affinity unit: assign each request to a feasible worker by longest cached prefix, lowest projected uncached load, greatest remaining capacity, then lowest worker id, with -1 when infeasible.