Unit 12 of 12 · about 3 hours · explain
Adapter and prefix affinity, grammar cost and multimodal co-scheduling
Real batches mix adapters, grammars and images. Each one adds a scheduling dimension beyond tokens and blocks, and ignoring any of them turns a tuned policy into queueing surprises.
You'll be able to
- Explain adapter-affinity scheduling from LoRA slot and rank pressure.
- Explain grammar-constrained decoding as per-step scheduling cost that varies with the constraint.
- Explain multimodal encoder and decoder co-scheduling with media-scoped cache reuse.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Per-request LoRA serving and slot pressurevLLM v0.31.0 LoRA adapters
Per-request
LoRARequestserved in parallel with base-model and other-adapter requests whenmax_lorasallows; server-wide--lora-moduleswithmax_lorasandmax_lora_rank, including the warning against oversized rank for memory and performance - Constrained decoding options and backendsvLLM v0.31.0 structured outputs
xgrammar and guidance backends with
--structured-outputs-config.backend;choice,regex,json,grammarandstructural_taginStructuredOutputsParamswith the offlinechoiceexample - Multimodal inputs, caching and encoder-side costvLLM v0.31.0 multimodal inputs
limit_mm_per_promptbounding media per request; Cached Inputs with content hashing and caller-suppliedmulti_modal_uuids, including skipping media on expected cache hits;--video-pruning-ratewith--video-pruning-methodas encoder-side scheduling cost
Focus on
- Group same-adapter requests together. Mixing adapters is supported up to
max_lorasconcurrent adapters, but each active adapter consumes slot and rank-budgeted memory, so affinity scheduling avoids slot churn and oversized-rank waste. - Grammar cost lands on decode steps: the backend builds a token mask every step, and its cost depends on the compiled constraint. The cited page gives no cost order, so time choice, regex, schema and grammar steps yourself and budget that work with the token budget.
- Media tokens join the prompt token budget, and encoder work must be scheduled before or beside the decode stream. Identical text with different images is a different cache entry: reuse is scoped by media identity through content hashes or UUIDs.
- All three topics are optional extensions of the same rule: schedule the scarce shared state, whether adapter slots, grammar engines or encoder results, rather than only tokens and blocks.
Common mistakes · 3
- Claiming different adapters cannot batch together. They can up to
max_loras; affinity is about slot pressure and memory, not correctness, so the failure mode is churn and waste rather than errors. - Treating grammar constraints as free because outputs look the same length. The constraint engine works every decode step, and wider grammars usually cost more per step than a fixed choice; measure it.
- Expecting prefix hits across different images with matching text. Media identity scopes the entry, so a changed image is a cache miss even when every word matches.
Try it yourself
Closed-book, before checking anything
max_loras at 2 and three queued adapters: group the two already-active adapters first and state which request waits for a slot. Predict an order of per-step cost for choice, regex, JSON schema and full grammar, and name the timing run that would test it. Then decide cache sharing for two requests with identical text where one pair shares an image UUID and the other uses different images: only the UUID pair shares encoder and prefix-cache work.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Three adapters queue with two LoRA slots. What does affinity scheduling do?Answer
It groups requests of the two already-active adapters first and holds the third adapter's requests until a slot frees. This avoids loading churn and oversized-rank memory waste.
2.How do you establish the per-step cost of choice, regex, JSON schema and full grammar constraints?Answer
Time constrained decode steps for each on your engine and backend with identical prompts and lengths. Expect wider constraints to cost more, but the documentation states no order, so the measurement decides.
3.Two requests share all text but carry different images. Do they share prefix-cache work?Answer
No. Cache identity includes the media through content hashes or UUIDs, so different images make different entries even with identical text.
4.A request skips sending its image and provides only a UUID. When does that work?Answer
Only when the caller can expect a cache hit for that UUID with caching enabled. The page documents skipping on expected hits, not the miss path, so treat a miss as needing the media and verify the fallback on your engine.
Practice
- TensorTonic: Route Cache-Aware Prefill Requests
Implement
cache_aware_prefill_routing(request_token_counts, cached_prefix_lengths, worker_ids, worker_capacities); public casesrouting_public_1,routing_public_2androuting_public_3The public cases check feasibility by full request length against capacity, ranking by longest cached prefix then lowest projected uncached load then greatest remaining capacity then lowest worker id, and -1 when no worker fits.
You're done when
You can schedule adapters under slot pressure, order grammar costs and scope media reuse without notes, and your routing solution passes the public cases.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 15 more in the section
- 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.
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.
- 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.
- 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).
- 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.
- 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.
- 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: 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.
- 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.
- 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. - 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.