Skip to content

20.4.4 Engine controls and speculation

This part of Serving, Capacity & Load Testing: Math to Code develops the mechanisms below. Work the numerical examples or trace the code before checking the answer.

Concepts from other sections (23)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

Learning objectives

  • Map a performance symptom to a measurable scheduling or execution control.

With the hardware layout decided, the engine’s scheduler determines how well the GPUs are used. Every knob moves a point along one curve: bigger batches raise throughput and raise TPOT; chunked prefill trades a little TTFT for stable TPOT; speculative decoding buys latency at low load and costs throughput at high load. Five mechanisms underlie the flags.

Continuous batching (Orca) schedules per iteration rather than per request, so sequences join and leave the batch every step. Every modern engine does this. PagedAttention (2309.06180) stores KV in fixed-size blocks with a block table, so memory is allocated as tokens arrive; this removes fragmentation and enables block sharing for prefixes.

Chunked prefill (Sarathi-Serve) caps the tokens per step (max_num_batched_tokens). Long prompts are split into chunks and co-scheduled with decodes, which bounds the step time so ITL p99 stays flat. A smaller budget gives better ITL and worse TTFT for long prompts; a larger one, the reverse.

Prefix caching hashes KV blocks by token content (vLLM) or keeps a radix tree of prefixes (SGLang’s RadixAttention). System prompts, few-shot examples, multi-turn chat, and agent loops get TTFT near zero for the cached part. SGLang’s --schedule-policy lpm (longest prefix match) orders the queue to maximize hits.

Preemption happens when the KV pool fills mid-generation: the engine evicts a sequence and recomputes it later. It shows up as TPOT spikes and a preemption counter in metrics. Fix it with more KV memory, a lower --max-num-seqs, or FP8 KV.

These mechanisms are controlled by flags. For each one, the useful question is which term of the memory budget or the step-time equation it changes; if you cannot answer that, you do not yet understand the flag. Here are the vLLM flags (vllm serve, engine args):

FlagTerm it changesNotes
--tensor-parallel-size / -tpN in W/N, KV/NWithin NVLink domain
--pipeline-parallel-size / -ppLayers per GPUAcross nodes
--data-parallel-size / -dpReplicasAlso used for DP attention with EP
--enable-expert-parallel / -epMoE layoutEP instead of TP for MoE layers
--max-model-lenMax contextMust fit one sequence in the KV pool; lower it to start on small GPUs
--gpu-memory-utilizationutilFraction of GPU memory for the engine; the KV pool is what is left after weights and profiling
--max-num-seqsMax batch BUpper bound on concurrency per step
--max-num-batched-tokensTokens per stepThe chunked-prefill budget; defaults vary by version and GPU, read it from the startup log
--enable-chunked-prefillPrefill mixingOn by default in the V1 engine
--enable-prefix-cachingPrefix reuseOn by default in V1; --no-enable-prefix-caching for clean benchmarks
--kv-cache-dtypeb_kvauto, fp8 (and fp8_e4m3 / fp8_e5m2 variants)
--quantization / -qb for weightsfp8, awq, gptq, compressed-tensors checkpoints auto-detected
--speculative-config / -scTokens per stepJSON: {"method": "eagle3", "model": ..., "num_speculative_tokens": 3}; methods include draft_model, ngram, eagle, eagle3, mtp, suffix
--enable-lora, --max-loras, --max-lora-rankAdapter slots--max-loras adapters per batch (default 1), rank options up to 512
--kv-transfer-configP/D disaggregationJSON naming a KV connector
--async-schedulingCPU overheadOverlaps scheduling with GPU execution

SGLang (python -m sglang.launch_server, server arguments) exposes the same mechanisms under different names, plus a few scheduling controls of its own:

SGLang flagvLLM analogueNotes
--tp-size / --tp--tensor-parallel-size
--dp-size--data-parallel-sizeRouter across replicas built in
--ep-size, --enable-dp-attention--enable-expert-parallelStandard DeepSeek recipe
--context-length--max-model-len
--mem-fraction-static--gpu-memory-utilizationWeights + KV pool fraction; lower it if you see OOM during CUDA graph capture
--max-running-requests--max-num-seqs
--chunked-prefill-size--max-num-batched-tokens-1 disables chunking
--schedule-policy(none)fcfs default; lpm for prefix-heavy traffic; also dfs-weight, lof, priority, random
--schedule-conservativeness(none)Higher reserves more KV for running requests, fewer preemptions
--disable-radix-cache--no-enable-prefix-cachingRadixAttention is on by default
--kv-cache-dtype--kv-cache-dtypeauto, fp8_e4m3, fp8_e5m2, bf16, plus FP4 variants on Blackwell
--speculative-algorithm--speculative-config methodEAGLE, EAGLE3, NEXTN (MTP), STANDALONE (draft model), NGRAM; with --speculative-draft-model-path, --speculative-num-steps, --speculative-eagle-topk, --speculative-num-draft-tokens
--enable-lora, --lora-paths, --max-loras-per-batch--enable-lora, --max-loras--max-loras-per-batch default 8
--disaggregation-mode--kv-transfer-configSeparate prefill and decode servers

Two other systems round out the picture. TensorRT-LLM compiles the model (or, with its PyTorch backend, loads it) with fused kernels tuned per GPU, and serves through trtllm-serve with an OpenAI-compatible API. It typically wins on NVIDIA hardware at fixed shapes and loses on iteration speed when the customer changes models weekly. NVIDIA Dynamo is a layer above engines: an OpenAI-compatible frontend, a KV-aware router that sends a request to the worker already holding its prefix, disaggregated prefill and decode with NIXL transfers, and a planner that scales the prefill and decode pools on SLO signals.

In practice you work backward from a broken metric, diagnosing with the engine’s Prometheus metrics first. This table maps each common symptom to its likely cause and the knob that addresses it:

SymptomLikely causeKnob
TTFT p99 spikes under load, TPOT fineQueueing: arrival rate near capacityAdd replicas (DP), raise --max-num-seqs if KV allows
ITL p99 spikes when long prompts arrivePrefill stalls decodeLower --max-num-batched-tokens / --chunked-prefill-size; at scale, disaggregate P/D
TTFT high for long prompts at low loadPrefill computeRaise chunk budget, TP, or CP; FP8 weights; prefix caching for shared context
TPOT high at low loadBandwidth per GPUTP up, FP8/INT4 weights, speculative decoding, H200/B200
TPOT degrades steadily with loadBatch growing, KV reads dominateCap --max-num-seqs; FP8 KV; accept the curve
Preemptions / recompute in logsKV pool exhausted--kv-cache-dtype fp8, raise util, lower --max-num-seqs or --max-model-len, add TP
OOM at startupProfiling or CUDA graph captureLower util / --mem-fraction-static, lower --max-num-batched-tokens
Low prefix-cache hit rate on chatUnstable prompt prefix, or replicas not prefix-awarePut static content first; use prefix-aware routing (SGLang router, Dynamo, llm-d)
GPU util high, tok/s lowCPU-bound scheduler, tiny batches, detokenization--async-scheduling, more API server processes, check client
Throughput fine, cost too highOver-provisioned for SLOFind goodput knee, run nearer it, consider FP8 or a smaller model

The same table works as a decision path, starting from the metric that breaks the SLO:

flowchart TD
    A["Which SLO or metric is failing?"] --> T["TTFT p99 high"]
    A --> P["TPOT or ITL high"]
    A --> M["Memory: OOM or preemptions"]
    A --> X["Throughput or cost"]
    T --> T1{"Only under load?"}
    T1 -->|"yes, TPOT fine"| T2["Queueing: add DP replicas, raise --max-num-seqs if KV allows"]
    T1 -->|"no, long prompts at low load"| T3["Prefill compute: bigger chunk budget, TP or CP, FP8, prefix caching"]
    T --> T4{"Chat with shared prefix but low hit rate?"}
    T4 -->|"yes"| T5["Static content first, prefix-aware routing"]
    P --> P1{"Pattern?"}
    P1 -->|"high even at low load"| P2["Bandwidth bound: TP up, FP8 or INT4 weights, spec decoding, H200 or B200"]
    P1 -->|"ITL spikes when long prompts arrive"| P3["Prefill stalls decode: lower --max-num-batched-tokens, then disaggregate P/D"]
    P1 -->|"rises steadily with load"| P4["KV reads dominate: cap --max-num-seqs, FP8 KV"]
    M --> M1{"When?"}
    M1 -->|"at startup"| M2["Profiling or CUDA graphs: lower util or --mem-fraction-static, lower --max-num-batched-tokens"]
    M1 -->|"preemptions mid-run"| M3["KV pool exhausted: --kv-cache-dtype fp8, raise util, lower --max-num-seqs or --max-model-len, add TP"]
    X --> X1{"GPU util high but tok/s low?"}
    X1 -->|"yes"| X2["CPU bound: --async-scheduling, more API server processes, check client"]
    X1 -->|"no, SLO met with margin"| X3["Over-provisioned: run nearer the goodput knee, FP8 or smaller model"]

One knob deserves its own derivation, because whether it helps depends on exactly where you sit on the roofline. The idea (Leviathan et al.) is that a cheap drafter proposes γ\gamma tokens and the target model verifies all γ+1\gamma + 1 positions in one forward pass. Since decode is memory-bound, verifying 5 tokens costs about the same bytes as producing 1. Rejection sampling keeps the output distribution exactly the target’s.

With a per-token acceptance rate α\alpha, assumed independent across positions, the expected number of tokens produced per target step is

E[tokens]=1−αγ+11−α\mathbb{E}[\text{tokens}] = \frac{1 - \alpha^{\gamma+1}}{1 - \alpha}

and the speedup is S=E[tokens]/(1+γc)S = \mathbb{E}[\text{tokens}] / (1 + \gamma c), where cc is the drafter’s step cost relative to the target. For example, with α=0.8\alpha = 0.8 and γ=4\gamma = 4, E=(1−0.328)/0.2=3.36\mathbb{E} = (1 - 0.328)/0.2 = 3.36; with c=0.05c = 0.05, the size of an EAGLE head, S=3.36/1.2=2.8×S = 3.36 / 1.2 = 2.8\times.

The same arithmetic shows when it hurts. At high batch the target step is already near the ridge point. Verification multiplies the tokens per step by γ+1\gamma + 1, so once the step is compute-bound it costs about (γ+1)×(\gamma + 1)\times as much, and S→E/(γ+1)=3.36/5=0.67S \to \mathbb{E} / (\gamma + 1) = 3.36 / 5 = 0.67: a 33% slowdown. The rule is a big win at low concurrency and neutral to negative at high concurrency. Measure α\alpha on the customer’s traffic, not on a benchmark.

The drafter can come from several places, and each family’s acceptance rate is driven by something different:

MethodDrafterα driverEngine support
Draft modelSmall model of the same family (e.g. 1B for 70B)Family similarityvLLM draft_model, SGLang STANDALONE
MedusaExtra decoding heads on the targetHead trainingLargely superseded by EAGLE
EAGLE-3One-layer head on target’s multi-layer features, trained with test-time simulationFused low/mid/high featuresvLLM eagle3, SGLang EAGLE3
MTP (DeepSeek-V3)Multi-token-prediction modules trained with the modelNativevLLM mtp, SGLang NEXTN
N-gram / prompt lookupCopy spans from the promptOutput repeats input (RAG, code edit, summarization)vLLM ngram, SGLang NGRAM
Suffix decodingSuffix trees over prompt and prior outputsRepetitive agent loopsvLLM suffix

Tip: Configure low. Start at num_speculative_tokens of 2 or 3: the acceptance-weighted gain flattens fast, while the high-batch penalty grows linearly in γ\gamma.

Map a performance symptom to a measurable scheduling or execution control. State the assumptions before applying the result to a different workload.

  1. What must remain fixed during a speculative decoding speed comparison?

    Answer

    The target model and distribution, request mix, output budget, hardware, and quality criteria. Count draft and verification cost.

Chapter contents · Next: Adapters and elastic capacity