{
  "id": "serving-engines",
  "module": "inference",
  "level": 3,
  "minutes": 35,
  "audiences": [
    "developer"
  ],
  "software": [
    "llama-cpp",
    "ollama",
    "mlx-lm"
  ],
  "text": {
    "en": {
      "title": "LLM Serving Engines: PagedAttention, Continuous Batching, Prefix Caching and Speculative Decoding",
      "description": "What it takes to serve a large language model to many users at once: how TTFT, TPOT and throughput are defined; what PagedAttention, continuous batching, chunked prefill, prefix caching (RadixAttention), speculative decoding (Medusa, EAGLE) and prefill/decode disaggregation each solve; and how to deploy and load-test with vLLM and SGLang. Based on the original papers and the official vLLM, SGLang and llama.cpp docs, with tested code.",
      "updated": "2026-10-25",
      "takeaways": [
        "A serving engine is judged on three things: time to first token (TTFT), time per output token (TPOT) and throughput. Bigger batches raise throughput but slow each request; tuning is about finding the balance.",
        "PagedAttention splits the KV cache into fixed-size blocks allocated on demand, like OS paging. The paper found earlier systems used only 20.4%–38.2% of KV-cache memory for actual token state; vLLM bounds waste to under one block and improves throughput 2–4×.",
        "Continuous batching (Orca's iteration-level scheduling) lets requests join or leave the batch after every step; chunked prefill splits long prompts into chunks batched together with decodes, so a long prompt does not stall requests that are generating.",
        "Prefix caching lets requests that share an opening (system prompt, long document, chat history) reuse the KV cache, cutting prefill time only. vLLM implements it with block hashes; SGLang uses a radix tree (RadixAttention) with LRU eviction.",
        "Speculative decoding has a cheap draft guess several tokens that the large model verifies in one pass; the standard acceptance rule leaves the output distribution unchanged. EAGLE and Medusa replace the separate draft model with small heads, and gains are largest at low concurrency, when decoding is memory-bandwidth bound."
      ],
      "faq": [
        {
          "q": "Should I choose vLLM or SGLang?",
          "a": "Both support continuous batching, prefix caching, speculative decoding, an OpenAI-compatible API and prefill/decode disaggregation, so their features overlap heavily. The reliable way to decide is to load-test both on the same GPU with your own model, real prompt lengths and concurrency. SGLang's RadixAttention and cache-aware scheduling are the core of its paper, so compare closely for multi-turn chat, agents and workloads with long shared prefixes."
        },
        {
          "q": "My benchmark showed low TTFT and high throughput, but production is much slower. Why?",
          "a": "A common cause is the benchmark repeatedly hitting the prefix cache. The vLLM docs warn that running vllm bench serve repeatedly against the same server can reuse cached prompts and inflate throughput; the random dataset is reproducible with a fixed --seed, so change the seed, restart the server, or use the sweep mode that resets the cache. Input and output lengths should also match your real traffic."
        },
        {
          "q": "Does speculative decoding always speed things up?",
          "a": "No. It trades extra compute for fewer sequential steps, and the gain depends on how many draft tokens are accepted. The vLLM docs position it as a way to reduce inter-token latency at medium-to-low QPS in memory-bound workloads; at high concurrency, when GPU compute is saturated, the gain shrinks or can turn negative."
        },
        {
          "q": "Do I need prefill/decode (PD) disaggregation?",
          "a": "Most single-node, small deployments do not. Its value is tuning TTFT and TPOT separately and controlling tail latency; the vLLM docs state plainly that it does not improve throughput and that the feature is still experimental. Get chunked prefill right first, and consider disaggregation at large scale with strict latency targets."
        }
      ],
      "sources": [
        {
          "title": "Kwon et al. (2023), Efficient Memory Management for Large Language Model Serving with PagedAttention (vLLM)",
          "url": "https://arxiv.org/abs/2309.06180"
        },
        {
          "title": "Yu et al. (2022), Orca: A Distributed Serving System for Transformer-Based Generative Models (OSDI '22)",
          "url": "https://www.usenix.org/conference/osdi22/presentation/yu"
        },
        {
          "title": "Zheng et al. (2023), SGLang: Efficient Execution of Structured Language Model Programs (RadixAttention)",
          "url": "https://arxiv.org/abs/2312.07104"
        },
        {
          "title": "Agrawal et al. (2024), Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve (chunked prefill)",
          "url": "https://arxiv.org/abs/2403.02310"
        },
        {
          "title": "Leviathan et al. (2022), Fast Inference from Transformers via Speculative Decoding",
          "url": "https://arxiv.org/abs/2211.17192"
        },
        {
          "title": "Chen et al. (2023), Accelerating Large Language Model Decoding with Speculative Sampling",
          "url": "https://arxiv.org/abs/2302.01318"
        },
        {
          "title": "Cai et al. (2024), Medusa: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads",
          "url": "https://arxiv.org/abs/2401.10774"
        },
        {
          "title": "Li et al. (2024), EAGLE: Speculative Sampling Requires Rethinking Feature Uncertainty",
          "url": "https://arxiv.org/abs/2401.15077"
        },
        {
          "title": "Li et al. (2024), EAGLE-2: Faster Inference of Language Models with Dynamic Draft Trees",
          "url": "https://arxiv.org/abs/2406.16858"
        },
        {
          "title": "Li et al. (2025), EAGLE-3: Scaling up Inference Acceleration of Large Language Models via Training-Time Test",
          "url": "https://arxiv.org/abs/2503.01840"
        },
        {
          "title": "Zhong et al. (2024), DistServe: Disaggregating Prefill and Decoding for Goodput-optimized LLM Serving",
          "url": "https://arxiv.org/abs/2401.09670"
        },
        {
          "title": "Patel et al. (2023), Splitwise: Efficient generative LLM inference using phase splitting",
          "url": "https://arxiv.org/abs/2311.18677"
        },
        {
          "title": "vLLM docs: Quickstart",
          "url": "https://docs.vllm.ai/en/latest/getting_started/quickstart/"
        },
        {
          "title": "vLLM docs: Automatic Prefix Caching",
          "url": "https://docs.vllm.ai/en/latest/features/automatic_prefix_caching/"
        },
        {
          "title": "vLLM docs: Automatic Prefix Caching (design)",
          "url": "https://docs.vllm.ai/en/latest/design/prefix_caching/"
        },
        {
          "title": "vLLM docs: Optimization and Tuning (preemption, chunked prefill, parallelism)",
          "url": "https://docs.vllm.ai/en/latest/configuration/optimization/"
        },
        {
          "title": "vLLM docs: Speculative Decoding",
          "url": "https://docs.vllm.ai/en/latest/features/speculative_decoding/"
        },
        {
          "title": "vLLM docs: Disaggregated Prefilling",
          "url": "https://docs.vllm.ai/en/latest/features/disagg_prefill/"
        },
        {
          "title": "vLLM docs: Benchmark CLI (vllm bench serve and latency metric definitions)",
          "url": "https://docs.vllm.ai/en/latest/benchmarking/cli/"
        },
        {
          "title": "SGLang docs: Quick Start",
          "url": "https://docs.sglang.io/docs/get-started/quickstart"
        },
        {
          "title": "SGLang docs: Server Arguments",
          "url": "https://docs.sglang.io/docs/advanced_features/server_arguments"
        },
        {
          "title": "SGLang docs: Speculative Decoding",
          "url": "https://docs.sglang.io/docs/advanced_features/speculative_decoding"
        },
        {
          "title": "SGLang docs: PD Disaggregation",
          "url": "https://docs.sglang.io/docs/advanced_features/pd_disaggregation"
        },
        {
          "title": "SGLang docs: Bench Serving Guide",
          "url": "https://docs.sglang.io/docs/developer_guide/bench_serving"
        },
        {
          "title": "vllm-project/vllm (official code)",
          "url": "https://github.com/vllm-project/vllm"
        },
        {
          "title": "sgl-project/sglang (official code)",
          "url": "https://github.com/sgl-project/sglang"
        },
        {
          "title": "SafeAILab/EAGLE (official EAGLE implementation)",
          "url": "https://github.com/SafeAILab/EAGLE"
        },
        {
          "title": "llama.cpp docs: llama-server (parallel slots, prompt cache)",
          "url": "https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md"
        },
        {
          "title": "Hugging Face blog: Assisted Generation",
          "url": "https://huggingface.co/blog/assisted-generation"
        }
      ],
      "url": "https://aimap.page/en/learn/inference/serving-engines/",
      "markdown": "## The short answer\n\nA **serving engine** turns a large model into an API that many people can use at the same time. Its core problem: GPU memory is limited, and each request's KV cache is large and keeps growing, so how do you fit as many requests as possible into one batch while keeping everyone's wait short? Engines such as vLLM and SGLang answer with **PagedAttention + continuous batching + prefix caching + speculative decoding**. This lesson belongs to the [Inference engines and serving](/learn/unit/u62-serving) unit; the prerequisite is [How LLMs generate text](/learn/llm-inference) (prefill, decode and the KV cache).\n\n## Step 1: Define \"fast\" — serving metrics\n\nA single user only cares about tokens per second; a server has to watch latency and throughput together. The [vLLM benchmarking docs](https://docs.vllm.ai/en/latest/benchmarking/cli/) define them as follows (measured on the client):\n\n| Metric | Definition | Mainly driven by |\n|---|---|---|\n| **TTFT** (time to first token) | From sending the request to receiving the first streamed output | Queueing + prefill (longer prompts are slower) |\n| **TPOT** (time per output token) | (end-to-end latency − TTFT) ÷ (output tokens − 1), computed per request | Decode speed, number of requests in the batch |\n| **ITL** (inter-token latency) | Gap between consecutive streamed chunks | Close to TPOT in normal decoding; differs with speculative decoding, which can emit several tokens at once |\n| **Throughput** | Requests completed per second, output tokens per second | Batch size, how much KV cache fits in memory |\n\nThe vLLM docs warn that benchmarking tools do not define these names consistently, so check where and how they are measured before comparing numbers. The [DistServe paper](https://arxiv.org/abs/2401.09670) also introduces **goodput**: the maximum request rate per GPU while meeting both TTFT and TPOT targets (SLOs) — closer to real serving capacity than peak throughput.\n\n**The batching trade-off.** Every decode step reads all of the weights; serving several requests per read raises throughput, but each step does more work, so individual requests slow down. Here are the results measured for this lesson on an 8-core CPU with llama.cpp's `llama-server` (Qwen3-0.6B, Q4_K_M quantization, 4 parallel slots); the benchmark script is in Step 7:\n\n| Concurrency | Median TTFT | Median TPOT | Output throughput |\n|---|---|---|---|\n| 1 | 63 ms | 10.8 ms | 87 tok/s |\n| 4 | 194 ms | 19.7 ms | 185 tok/s |\n\nGoing from 1 to 4 concurrent requests roughly doubled total throughput, but per-request TPOT also roughly doubled and TTFT rose about 3× (the machine was running other jobs, so the numbers fluctuate — look at the trend). GPU numbers are completely different, but the trade-off is the same: **set the latency target first, then maximize throughput within it**.\n\n## Step 2: PagedAttention — managing the KV cache like an operating system\n\nThe [PagedAttention paper](https://arxiv.org/abs/2309.06180) observed that existing systems reserved one **contiguous** chunk of memory per request, sized for the maximum possible length (for example 2,048 tokens). That causes three problems: space reserved for future tokens sits idle; actual outputs are shorter than the limit, causing internal fragmentation; and different reservation sizes cause external fragmentation. They measured that only **20.4%–38.2%** of KV-cache memory in those systems actually held token state.\n\nPagedAttention borrows virtual memory and paging from operating systems:\n\n- Each request's KV cache is split into fixed-size **blocks** (each holding the K and V of a few tokens). Blocks need not be contiguous; a block table maps logical blocks to physical blocks.\n- A new block is allocated only when the current one is full, so each request wastes **less than one block**; when a request finishes, its blocks go straight back to the pool.\n- When several outputs are sampled from the same prompt, the prompt's blocks are shared and copied only on write (copy-on-write).\n\nThe paper reports 2–4× higher throughput than FasterTransformer and Orca at the same latency, with larger gains for longer sequences, larger models and more complex decoding algorithms. Block size is a trade-off: too small underuses GPU parallelism, too large increases fragmentation and reduces sharing, so the paper sets the default block size to 16 tokens.\n\n## Step 3: Scheduling — continuous batching and chunked prefill\n\n**Continuous batching.** The traditional approach runs a batch until every request in it finishes: early finishers cannot return, and new requests wait for the whole batch. [Orca (OSDI '22)](https://www.usenix.org/conference/osdi22/presentation/yu) introduced **iteration-level scheduling**: the scheduler runs the model one step (one token) at a time, and after each step finished requests can leave and new ones can join. On GPT-3 175B the paper reports 36.9× the throughput of NVIDIA FasterTransformer at the same latency. Today's mainstream engines schedule this way by default.\n\n**Chunked prefill.** Prefill processes a whole prompt at once — compute-saturated but slow; decode computes one token per step and underuses compute. Mixing them means a very long prompt makes requests that are generating stall. [Sarathi-Serve](https://arxiv.org/abs/2403.02310) splits long prompts into near-equal chunks and batches them with decode requests without pausing ongoing decodes; the paper reports 2.6× the serving capacity of vLLM for Mistral-7B on a single A100. The [vLLM docs](https://docs.vllm.ai/en/latest/configuration/optimization/) explain that the V1 engine enables chunked prefill whenever possible and schedules decode requests first, then fills the remaining `max_num_batched_tokens` budget with prefill: a small value (such as 2048) gives better ITL, a larger value better TTFT.\n\n**Preemption when memory runs out.** When the KV cache cannot hold every request, vLLM preempts some and recomputes them later (`RECOMPUTE` is the V1 default). If preemption warnings appear often, the docs suggest raising `gpu_memory_utilization`, lowering `max_num_seqs` or `max_num_batched_tokens`, or using tensor parallelism to spread the weights across GPUs and free memory for the KV cache.\n\n## Step 4: Prefix caching — compute a shared opening once\n\nMany requests start the same way: the same system prompt, the same long document, the history of a multi-turn chat. **Prefix caching** keeps the computed KV cache so a new request with the same opening can reuse it and skip that part of prefill.\n\n- **vLLM's Automatic Prefix Caching (APC)**: the [design doc](https://docs.vllm.ai/en/latest/design/prefix_caching/) explains that each KV block gets a hash built from the parent block's hash, the block's tokens and extra information (LoRA ID, image hashes, a cache salt for multi-tenant isolation); only full blocks are cached. Since v0.11 the default hash is sha256, lowering the risk of collisions. It is on by default in current versions.\n- **SGLang's RadixAttention**: the [SGLang paper](https://arxiv.org/abs/2312.07104) stores the prompts and outputs of all requests in a **radix tree**, evicting leaves first with an LRU policy; the cache and running requests share one memory pool. The scheduler sorts requests by matched prefix length and runs longer matches first (cache-aware scheduling), and the paper proves that, offline, visiting the radix tree in depth-first order achieves the optimal hit rate. It reports up to 6.4× higher throughput on agent control, few-shot, JSON decoding, RAG and multi-turn chat workloads.\n\n**Where the gains stop.** The [vLLM docs](https://docs.vllm.ai/en/latest/features/automatic_prefix_caching/) are explicit: prefix caching reduces prefill time only, not decode time, and helps little when answers are long or requests share no prefix. So when building applications, **put fixed content at the start of the prompt and variable content at the end**, or the cache will not hit.\n\nMeasured for this lesson with llama.cpp's `llama-server` (its `cache_prompt` is on by default; see the [official docs](https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md)): with a \"product manual\" of roughly 1,150 tokens as the system prompt, the first question had a TTFT of 1,457 ms and a different follow-up question only 118 ms; the server log shows the second request prefilled only 9 new tokens and reused the cache for the rest.\n\n```python\nimport time\nfrom openai import OpenAI\nclient = OpenAI(base_url=\"http://localhost:8080/v1\", api_key=\"not-needed\")\ndoc = \"Product manual. \" + \"The product works offline, has a multilingual UI and automatic backups. \" * 80\n\ndef ttft(question):\n    t0 = time.perf_counter()\n    stream = client.chat.completions.create(\n        model=\"local\", stream=True, max_tokens=8, temperature=0,\n        messages=[{\"role\": \"system\", \"content\": doc},          # fixed content first\n                  {\"role\": \"user\", \"content\": question}])      # variable content last\n    first = None\n    for chunk in stream:                                        # drain the stream before the next request\n        d = chunk.choices[0].delta if chunk.choices else None\n        if first is None and d and (d.content or getattr(d, \"reasoning_content\", None)):\n            first = time.perf_counter()                         # thinking models stream reasoning first\n    return (first - t0) * 1000\n\nprint(f\"first:  {ttft('Does it work offline?'):.0f} ms\")       # measured 1457 ms\nprint(f\"second: {ttft('Does it back up automatically?'):.0f} ms\")  # measured 118 ms, prefix cache hit\n```\n\n## Step 5: Speculative decoding — let the large model verify several tokens at once\n\nDecoding is memory-bandwidth bound: computing 1 token or checking 5 tokens in parallel takes about the same time for a large model. **Speculative decoding** ([Leviathan et al., 2022](https://arxiv.org/abs/2211.17192); concurrently DeepMind's [speculative sampling](https://arxiv.org/abs/2302.01318)) exploits this:\n\n1. A cheap draft model guesses γ tokens in a row.\n2. The large model runs one forward pass, computing probabilities at all γ positions.\n3. Each draft token x is accepted with probability min(1, p(x)/q(x)) (p is the large model's distribution, q the draft's). At the first rejection, one token is resampled from norm(max(0, p − q)) and the remaining drafts are discarded.\n\nEach round yields at least 1 and at most γ+1 tokens, and **the output distribution is exactly the large model's**. The paper defines the acceptance rate α = E[Σ min(p, q)]; each round yields (1 − α^(γ+1)) / (1 − α) tokens on average. The original paper measured 2–3× speedups on T5-XXL with identical outputs; speculative sampling sped up the 70B Chinchilla by 2–2.5×.\n\nThis NumPy snippet checks that the accept/reject rule does not change the distribution (run for this lesson):\n\n```python\nimport numpy as np\nrng = np.random.default_rng(0)\np = np.array([0.40, 0.25, 0.15, 0.12, 0.08])   # large model's next-token distribution\nq = np.array([0.20, 0.40, 0.20, 0.10, 0.10])   # draft distribution, deliberately off\n\ndef step():\n    x = rng.choice(5, p=q)                       # draft guesses\n    if rng.random() < min(1, p[x] / q[x]):       # accept with min(1, p/q)\n        return x, True\n    r = np.maximum(p - q, 0)                     # reject: resample from norm(max(0, p-q))\n    return rng.choice(5, p=r / r.sum()), False\n\nN = 200_000\nxs, acc = zip(*(step() for _ in range(N)))\nprint(np.round(np.bincount(xs, minlength=5) / N, 3))   # [0.402 0.25 0.149 0.12 0.079] ≈ p\nalpha = np.minimum(p, q).sum()\nprint(f\"{np.mean(acc):.3f} {alpha:.3f}\")                # 0.780 0.780: acceptance rate = Σmin(p,q)\nprint(f\"{(1 - alpha**5) / (1 - alpha):.2f}\")            # γ=4: 3.23 tokens per round on average\n```\n\n**Variants without a separate draft model:**\n\n- [Medusa](https://arxiv.org/abs/2401.10774) adds extra decoding heads to the large model to predict several future tokens at once, verifying multiple candidates in one pass with tree attention. Medusa-1 freezes the backbone and trains only the new heads, reporting over 2.2× speedup without quality loss; Medusa-2 trains them together with the backbone for 2.3–3.6×.\n- [EAGLE](https://arxiv.org/abs/2401.15077) autoregresses on second-to-top-layer **features**, also feeding in the token sequence advanced by one step to resolve uncertainty; on LLaMA2-Chat 70B it reports 2.7–3.5× lower latency and doubled throughput without changing the output distribution. [EAGLE-2](https://arxiv.org/abs/2406.16858) uses a context-dependent dynamic draft tree for 3.05–4.26×; [EAGLE-3](https://arxiv.org/abs/2503.01840) drops feature prediction, predicts tokens directly and fuses multi-layer features, reaching up to 6.5× and a 1.38× throughput gain at batch size 64 in SGLang.\n\n**Turning it on.** vLLM takes JSON via `--speculative-config`, for example `{\"method\": \"eagle3\", \"model\": \"<draft weights>\", \"num_speculative_tokens\": 2}`, and also supports draft models, MTP, n-gram and other methods ([vLLM docs](https://docs.vllm.ai/en/latest/features/speculative_decoding/)). SGLang uses `--speculative-algorithm EAGLE3 --speculative-draft-model-path ... --speculative-num-steps 3 --speculative-eagle-topk 4 --speculative-num-draft-tokens 16` ([SGLang docs](https://docs.sglang.io/docs/advanced_features/speculative_decoding)). Note how the vLLM docs position it: speculative decoding reduces inter-token latency at **medium-to-low QPS** in memory-bound workloads, and the gain shrinks at high concurrency. Draft weights must match the target model.\n\n## Step 6: Prefill/decode disaggregation\n\nPrefill is compute-bound and decode is memory-bandwidth-bound; on the same GPUs they interfere. [DistServe](https://arxiv.org/abs/2401.09670) puts the two phases on different GPUs and picks resources and parallelism for each against TTFT and TPOT targets, reporting 7.4× more requests served, or 12.6× tighter SLOs, while meeting latency constraints for over 90% of requests. Microsoft's [Splitwise](https://arxiv.org/abs/2311.18677) puts the phases on different machines and reports 1.4× higher throughput at 20% lower cost.\n\nThere is an engineering cost: the KV cache has to move between machines, which needs fast interconnects. The [vLLM docs](https://docs.vllm.ai/en/latest/features/disagg_prefill/) say the feature is still experimental, that its value is tuning TTFT and ITL separately and controlling tail ITL, and that it **does not improve throughput**; chunked prefill with a well-chosen chunk size can achieve similar goals, though the chunk size is hard to tune. SGLang supports PD disaggregation with KV transfer over Mooncake or NIXL ([docs](https://docs.sglang.io/docs/advanced_features/pd_disaggregation)).\n\n## Step 7: Deploy and load-test\n\n**vLLM** (NVIDIA GPU; [quickstart](https://docs.vllm.ai/en/latest/getting_started/quickstart/)):\n\n```bash\nuv venv --python 3.12 --seed && source .venv/bin/activate\nuv pip install vllm --torch-backend=auto\nvllm serve Qwen/Qwen2.5-1.5B-Instruct            # listens on http://localhost:8000, OpenAI-compatible\n# keys are checked only with --api-key; always set it before going live\n\n# in another terminal: random data, 1024 input / 128 output tokens, max concurrency 16\nvllm bench serve --backend vllm --model Qwen/Qwen2.5-1.5B-Instruct \\\n  --endpoint /v1/completions --dataset-name random \\\n  --random-input-len 1024 --random-output-len 128 \\\n  --num-prompts 200 --max-concurrency 16\n```\n\nThe output reports request throughput, output-token throughput, and mean, median and P99 of TTFT, TPOT and ITL. `--request-rate` defaults to `inf` (all requests sent at once, measuring maximum throughput); with a finite value, arrivals follow a Poisson process, closer to real traffic. The vLLM docs also recommend GuideLLM for production benchmarking.\n\n**SGLang** ([quickstart](https://docs.sglang.io/docs/get-started/quickstart), [benchmarking guide](https://docs.sglang.io/docs/developer_guide/bench_serving)):\n\n```bash\nuv pip install --prerelease=allow sglang\nsglang serve Qwen/Qwen2.5-1.5B-Instruct --host 0.0.0.0 --port 30000\npython3 -m sglang.bench_serving --backend sglang --host 127.0.0.1 --port 30000 \\\n  --dataset-name random --num-prompts 200 --max-concurrency 16\n```\n\nIf memory runs short, lower `--mem-fraction-static` (the fraction of GPU memory for weights plus the KV-cache pool); `--chunked-prefill-size` sets the prefill chunk size; `--disable-radix-cache` turns RadixAttention off, which is handy for measuring what prefix caching buys you ([server arguments](https://docs.sglang.io/docs/advanced_features/server_arguments)).\n\nThe vLLM and SGLang commands above were checked against the official docs on 2026-10-25 but not run here (no GPU). **You can practice benchmarking without a GPU**: the script below measures TTFT, TPOT and throughput against any OpenAI-compatible server. For this lesson it ran against llama.cpp's `llama-server -m Qwen3-0.6B-Q4_K_M.gguf -c 8192 -np 4 --port 8080`, producing the table in Step 1 (with the Chinese prompt from the Chinese version of this lesson):\n\n```python\nimport asyncio, time, statistics\nfrom openai import AsyncOpenAI\nclient = AsyncOpenAI(base_url=\"http://localhost:8080/v1\", api_key=\"not-needed\")\n\nasync def one(prompt, max_tokens=128):\n    t0 = time.perf_counter(); first = None; n = 0\n    stream = await client.chat.completions.create(\n        model=\"local\", stream=True, max_tokens=max_tokens, temperature=0,\n        stream_options={\"include_usage\": True},          # last chunk carries token usage\n        messages=[{\"role\": \"user\", \"content\": prompt}])\n    async for chunk in stream:\n        d = chunk.choices[0].delta if chunk.choices else None\n        if d and (d.content or getattr(d, \"reasoning_content\", None)) and first is None:\n            first = time.perf_counter()                   # first output arrives → TTFT\n        if chunk.usage:\n            n = chunk.usage.completion_tokens\n    end = time.perf_counter()\n    return first - t0, (end - first) / max(n - 1, 1), n   # TTFT, TPOT, output tokens\n\nasync def run(concurrency, total=16):\n    sem = asyncio.Semaphore(concurrency)\n    async def guarded(i):\n        async with sem:\n            return await one(f\"Question {i}: explain the KV cache in three sentences.\")\n    t0 = time.perf_counter()\n    res = await asyncio.gather(*(guarded(i) for i in range(total)))\n    wall = time.perf_counter() - t0\n    print(f\"concurrency {concurrency}: median TTFT {statistics.median(r[0] for r in res)*1000:.0f} ms, \"\n          f\"median TPOT {statistics.median(r[1] for r in res)*1000:.1f} ms, \"\n          f\"throughput {sum(r[2] for r in res)/wall:.1f} tok/s\")\n\nfor c in (1, 4):\n    asyncio.run(run(c))\n```\n\nNote: in our test, setting `-np 4` explicitly on `llama-server` split the `-c 8192` context evenly across 4 slots, so each request could use at most 2,048 tokens and longer ones were rejected with an error; when `-np` is left at auto, the server defaults to one unified KV buffer shared by all slots (`--kv-unified`).\n\n## Choosing an engine\n\n| Scenario | Common choice | Notes |\n|---|---|---|\n| Datacenter GPUs, multi-user API | [vLLM](https://github.com/vllm-project/vllm), [SGLang](https://github.com/sgl-project/sglang) | Both have PagedAttention-style block KV management, continuous batching, prefix caching, speculative decoding and an OpenAI-compatible API; decide after load-testing your own workload |\n| Multi-turn chat, agents, lots of shared prefixes | Test both, look closely at SGLang | RadixAttention and cache-aware scheduling target exactly this |\n| Personal computers, CPU, Apple silicon, small internal services | [llama.cpp](/apps/llama-cpp), [Ollama](/apps/ollama), [MLX LM](/apps/mlx-lm) | Quantized models, cross-platform; `llama-server` has parallel slots and a prompt cache but is not built for large-scale high concurrency. See [Running LLMs on your own computer](/learn/local-llm) |\n| One entry point for many providers, fallbacks, rate limits, cost tracking | Put a model gateway in front of the engine | See [Model gateways, routing and cost control](/learn/model-gateway) |\n\n## Common pitfalls\n\n| Symptom | Cause | Fix |\n|---|---|---|\n| Great benchmark, slow in production | Benchmark keeps hitting the prefix cache, or input/output lengths differ from real traffic | Change the seed or restart the server; use realistic length distributions and arrival rates |\n| Frequent \"preempted\" warnings in logs | KV cache cannot hold current concurrency | Raise `gpu_memory_utilization`, lower `max_num_seqs`, or use tensor parallelism |\n| Other users' output stutters when a long prompt arrives | Prefill interrupts decoding | Make sure chunked prefill is on; lower `max_num_batched_tokens` |\n| Low prefix-cache hit rate | Timestamps, user names or other changing content at the start of the prompt | Fixed content first, variable content last |\n| Speculative decoding makes things slower | High concurrency with compute saturated, or a mismatched draft with low acceptance | Enable it for low-concurrency workloads; use the official matching EAGLE/MTP weights and watch the acceptance metrics |\n| Strangers are calling your server | Keys are not checked by default | Use `--api-key` and put the server behind a gateway or reverse proxy |\n\n## Try it yourself\n\n1. **Get vLLM running**: follow the [vLLM quickstart](https://docs.vllm.ai/en/latest/getting_started/quickstart/) to start an OpenAI-compatible server, run `vllm bench serve` at concurrency 1, 8 and 32, and plot throughput against TTFT.\n2. **Compare prefix caching**: on [SGLang](https://github.com/sgl-project/sglang), run the same workload twice (default and `--disable-radix-cache`) where 80% of requests share a 2,000-token system prompt, and compare TTFT.\n3. **No GPU**: run the benchmark script above against [llama.cpp](/apps/llama-cpp)'s `llama-server` and change `-np` to see how throughput and latency move.\n4. **Unit project**: deploy a 7B/8B open model, measure throughput and P99 TTFT at concurrency 1–64, then enable speculative decoding (EAGLE-3 or n-gram), compare low and high concurrency, and write down when it is worth turning on.\n\nRelated algorithm cards: [PagedAttention](/learn/algorithms/paged-attention), [Continuous batching](/learn/algorithms/continuous-batching), [RadixAttention prefix caching](/learn/algorithms/radix-attention), [Speculative decoding](/learn/algorithms/speculative-decoding), [Medusa](/learn/algorithms/medusa), [EAGLE](/learn/algorithms/eagle), [Prefill/decode disaggregation](/learn/algorithms/pd-disaggregation)."
    },
    "zh-hans": {
      "title": "推理引擎与服务：PagedAttention、连续批处理、前缀缓存与推测解码",
      "description": "把大模型做成多人同时使用的服务，要解决什么问题：TTFT、TPOT、吞吐等指标怎么定义；PagedAttention、连续批处理、分块预填充、前缀缓存（RadixAttention）、推测解码（Medusa、EAGLE）和预填充/解码分离各自解决什么；以及怎样用 vLLM、SGLang 部署和压测。依据原始论文和 vLLM、SGLang、llama.cpp 官方文档，附实测代码。",
      "updated": "2026-10-25",
      "takeaways": [
        "服务端看三类指标：首 token 延迟（TTFT）、每个输出 token 的时间（TPOT）和吞吐；批越大吞吐越高，但单个请求会变慢，调参就是在这两者之间找平衡。",
        "PagedAttention 把 KV Cache 切成固定大小的块、像操作系统分页一样按需分配；论文测得旧系统只有 20.4%–38.2% 的 KV 显存真正存了 token，vLLM 把浪费压到一个块以内，吞吐提升 2–4 倍。",
        "连续批处理（Orca 提出的迭代级调度）每生成一步就可以让请求加入或离开批次；分块预填充把长提示切块，和解码混在同一批里，避免长提示卡住正在生成的请求。",
        "前缀缓存让共享同一段开头（系统提示、长文档、多轮历史）的请求直接复用 KV Cache，只减少预填充时间；vLLM 用块哈希实现，SGLang 用基数树（RadixAttention）加 LRU 淘汰。",
        "推测解码让便宜的草稿先猜几个 token、大模型一次验证，按标准接受规则不改变输出分布；EAGLE、Medusa 等方法用小头代替独立草稿模型，主要在低并发、受内存带宽限制时收益最大。"
      ],
      "faq": [
        {
          "q": "vLLM 和 SGLang 选哪个？",
          "a": "两者都支持连续批处理、前缀缓存、推测解码、OpenAI 兼容接口和预填充/解码分离，功能高度重合。最可靠的办法是用你自己的模型、真实的提示长度和并发，在同一张卡上各压测一次。SGLang 的 RadixAttention 和缓存感知调度是论文里的核心卖点，多轮对话、Agent、共享长前缀的场景值得重点对比。"
        },
        {
          "q": "压测时 TTFT 很低、吞吐很高，上线后却慢很多，为什么？",
          "a": "常见原因是压测数据重复命中了前缀缓存。vLLM 文档专门提醒：对同一个服务反复跑 vllm bench serve，可能复用缓存里的提示、虚高吞吐；随机数据集在固定 --seed 时可复现，要么换 seed、重启服务，要么用会重置缓存的 sweep 模式。另外压测的输入/输出长度要接近真实业务。"
        },
        {
          "q": "推测解码一定能加速吗？",
          "a": "不一定。它用额外计算换更少的串行步数，收益取决于草稿被接受的比例。vLLM 文档说明推测解码主要用于降低中低 QPS、受内存带宽限制场景下的 token 间延迟；并发很高、GPU 算力已经吃满时，收益会变小，甚至变慢。"
        },
        {
          "q": "预填充/解码分离（PD 分离）适合我吗？",
          "a": "多数单机、小规模部署用不上。它的价值是把 TTFT 和 TPOT 分开调优、控制尾部延迟；vLLM 文档明确写着它不提高吞吐，而且目前仍是实验功能。先用好分块预填充，规模大、延迟要求严格时再考虑。"
        }
      ],
      "sources": [
        {
          "title": "Kwon et al. (2023), Efficient Memory Management for Large Language Model Serving with PagedAttention（vLLM）",
          "url": "https://arxiv.org/abs/2309.06180"
        },
        {
          "title": "Yu et al. (2022), Orca: A Distributed Serving System for Transformer-Based Generative Models（OSDI '22）",
          "url": "https://www.usenix.org/conference/osdi22/presentation/yu"
        },
        {
          "title": "Zheng et al. (2023), SGLang: Efficient Execution of Structured Language Model Programs（RadixAttention）",
          "url": "https://arxiv.org/abs/2312.07104"
        },
        {
          "title": "Agrawal et al. (2024), Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve（分块预填充）",
          "url": "https://arxiv.org/abs/2403.02310"
        },
        {
          "title": "Leviathan et al. (2022), Fast Inference from Transformers via Speculative Decoding",
          "url": "https://arxiv.org/abs/2211.17192"
        },
        {
          "title": "Chen et al. (2023), Accelerating Large Language Model Decoding with Speculative Sampling",
          "url": "https://arxiv.org/abs/2302.01318"
        },
        {
          "title": "Cai et al. (2024), Medusa: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads",
          "url": "https://arxiv.org/abs/2401.10774"
        },
        {
          "title": "Li et al. (2024), EAGLE: Speculative Sampling Requires Rethinking Feature Uncertainty",
          "url": "https://arxiv.org/abs/2401.15077"
        },
        {
          "title": "Li et al. (2024), EAGLE-2: Faster Inference of Language Models with Dynamic Draft Trees",
          "url": "https://arxiv.org/abs/2406.16858"
        },
        {
          "title": "Li et al. (2025), EAGLE-3: Scaling up Inference Acceleration of Large Language Models via Training-Time Test",
          "url": "https://arxiv.org/abs/2503.01840"
        },
        {
          "title": "Zhong et al. (2024), DistServe: Disaggregating Prefill and Decoding for Goodput-optimized LLM Serving",
          "url": "https://arxiv.org/abs/2401.09670"
        },
        {
          "title": "Patel et al. (2023), Splitwise: Efficient generative LLM inference using phase splitting",
          "url": "https://arxiv.org/abs/2311.18677"
        },
        {
          "title": "vLLM 文档：Quickstart",
          "url": "https://docs.vllm.ai/en/latest/getting_started/quickstart/"
        },
        {
          "title": "vLLM 文档：Automatic Prefix Caching",
          "url": "https://docs.vllm.ai/en/latest/features/automatic_prefix_caching/"
        },
        {
          "title": "vLLM 文档：Automatic Prefix Caching 设计说明",
          "url": "https://docs.vllm.ai/en/latest/design/prefix_caching/"
        },
        {
          "title": "vLLM 文档：Optimization and Tuning（抢占、分块预填充、并行）",
          "url": "https://docs.vllm.ai/en/latest/configuration/optimization/"
        },
        {
          "title": "vLLM 文档：Speculative Decoding",
          "url": "https://docs.vllm.ai/en/latest/features/speculative_decoding/"
        },
        {
          "title": "vLLM 文档：Disaggregated Prefilling",
          "url": "https://docs.vllm.ai/en/latest/features/disagg_prefill/"
        },
        {
          "title": "vLLM 文档：Benchmark CLI（vllm bench serve 与延迟指标定义）",
          "url": "https://docs.vllm.ai/en/latest/benchmarking/cli/"
        },
        {
          "title": "SGLang 文档：Quick Start",
          "url": "https://docs.sglang.io/docs/get-started/quickstart"
        },
        {
          "title": "SGLang 文档：Server Arguments",
          "url": "https://docs.sglang.io/docs/advanced_features/server_arguments"
        },
        {
          "title": "SGLang 文档：Speculative Decoding",
          "url": "https://docs.sglang.io/docs/advanced_features/speculative_decoding"
        },
        {
          "title": "SGLang 文档：PD Disaggregation",
          "url": "https://docs.sglang.io/docs/advanced_features/pd_disaggregation"
        },
        {
          "title": "SGLang 文档：Bench Serving Guide",
          "url": "https://docs.sglang.io/docs/developer_guide/bench_serving"
        },
        {
          "title": "vllm-project/vllm（官方代码）",
          "url": "https://github.com/vllm-project/vllm"
        },
        {
          "title": "sgl-project/sglang（官方代码）",
          "url": "https://github.com/sgl-project/sglang"
        },
        {
          "title": "SafeAILab/EAGLE（EAGLE 官方实现）",
          "url": "https://github.com/SafeAILab/EAGLE"
        },
        {
          "title": "llama.cpp 文档：llama-server（并行槽位、提示缓存）",
          "url": "https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md"
        },
        {
          "title": "Hugging Face 博客：Assisted Generation",
          "url": "https://huggingface.co/blog/assisted-generation"
        }
      ],
      "url": "https://aimap.page/zh-hans/learn/inference/serving-engines/",
      "markdown": "## 一句话回答\n\n**推理引擎（serving engine）**负责把一个大模型变成能同时服务很多人的 API。它要解决的核心问题是：GPU 显存有限、每个请求的 KV Cache 又大又在不断变长，怎样把尽可能多的请求塞进同一批里，同时让每个人等得不太久。vLLM、SGLang 这类引擎的答案是 **PagedAttention + 连续批处理 + 前缀缓存 + 推测解码**。本课属于[推理引擎与服务](/learn/unit/u62-serving)单元，前置知识是[大模型如何生成文本](/learn/llm-inference)（预填充、解码和 KV Cache）。\n\n## 第一步：先定义“快”——服务端的指标\n\n单人使用只关心“每秒出几个字”；服务端要同时看延迟和吞吐。[vLLM 的压测文档](https://docs.vllm.ai/en/latest/benchmarking/cli/)这样定义（在客户端测量）：\n\n| 指标 | 定义 | 主要受什么影响 |\n|---|---|---|\n| **TTFT**（首 token 延迟） | 从发出请求到收到第一段流式输出 | 排队时间 + 预填充（提示越长越慢） |\n| **TPOT**（每个输出 token 的时间） | （端到端延迟 − TTFT）÷（输出 token 数 − 1），每个请求算一次 | 解码速度、同批请求数 |\n| **ITL**（token 间延迟） | 相邻两段流式输出的间隔 | 普通解码时和 TPOT 接近；推测解码一次可能吐出多个 token，两者会不同 |\n| **吞吐** | 每秒完成的请求数、每秒输出 token 数 | 批大小、显存能容纳多少 KV Cache |\n\nvLLM 文档特别提醒：不同压测工具对这些名字的定义并不统一，比较结果时要看测量点和公式。[DistServe 论文](https://arxiv.org/abs/2401.09670)还提出 **goodput**：在同时满足 TTFT 和 TPOT 目标（SLO）的前提下，每张 GPU 能承受的最大请求速率——这比“峰值吞吐”更接近真实的服务能力。\n\n**批处理的取舍。** 解码时每一步都要把全部权重读一遍，一次读权重服务多个请求，吞吐就上去了；代价是每一步要算的东西变多，单个请求变慢。下面是本课在一台 8 核 CPU 上用 llama.cpp 的 `llama-server`（Qwen3-0.6B，Q4_K_M 量化，4 个并行槽位）实测的结果，压测脚本见第七步：\n\n| 并发 | TTFT 中位数 | TPOT 中位数 | 输出吞吐 |\n|---|---|---|---|\n| 1 | 63 ms | 10.8 ms | 87 tok/s |\n| 4 | 194 ms | 19.7 ms | 185 tok/s |\n\n并发从 1 到 4，总吞吐约翻倍，但每个请求的 TPOT 也约翻倍，TTFT 涨到约 3 倍（这台机器同时跑着其他任务，数字会有波动，看趋势即可）。GPU 上数字完全不同，但这种取舍是一样的：**先定延迟目标，再在目标内把吞吐做到最大**。\n\n## 第二步：PagedAttention——像操作系统一样管理 KV Cache\n\n[PagedAttention 论文](https://arxiv.org/abs/2309.06180)发现，当时的系统为每个请求预留一整段**连续**显存，长度按最大可能长度（例如 2048 个 token）来留。问题有三个：预留给未来 token 的空间暂时空着；实际回答比上限短，造成内部碎片；不同请求预留的大小不同，又造成外部碎片。他们测得，旧系统里只有 **20.4%–38.2%** 的 KV Cache 显存真正存了 token 的状态。\n\nPagedAttention 借鉴操作系统的虚拟内存和分页：\n\n- 把每个请求的 KV Cache 切成固定大小的**块**（每块存若干个 token 的 K 和 V），块在显存里不必连续，用一张“块表”记录逻辑块到物理块的映射；\n- 新 token 填满当前块后才分配下一块，所以每个请求的浪费**不超过一个块**；请求结束，块立刻还给其他请求；\n- 同一个提示要采样多个回答时，提示部分的块可以共享，写入时再复制（copy-on-write）。\n\n论文报告，vLLM 在相同延迟下比 FasterTransformer、Orca 等系统吞吐提升 **2–4 倍**，序列越长、模型越大、解码算法越复杂，提升越明显。块大小也有取舍：太小不能充分利用 GPU 并行，太大又增加碎片、降低共享机会，论文因此把默认块大小定为 16 个 token。\n\n## 第三步：调度——连续批处理与分块预填充\n\n**连续批处理（continuous batching）。** 传统做法是凑一批请求一起跑，直到整批都结束：先结束的请求不能提前返回，新请求要等整批结束才能进来。[Orca（OSDI '22）](https://www.usenix.org/conference/osdi22/presentation/yu)提出**迭代级调度**：调度器每次只让模型跑一步（生成一个 token），每一步之后都可以让结束的请求离开、新请求加入。论文在 GPT-3 175B 上报告，相同延迟下吞吐比 NVIDIA FasterTransformer 高 36.9 倍。今天的主流引擎都默认这样调度。\n\n**分块预填充（chunked prefill）。** 预填充一次处理整段提示，算力吃满但耗时长；解码每步只算一个 token，算力利用率低。两者混在一起时，一个很长的提示会让正在生成的请求“卡一下”。[Sarathi-Serve](https://arxiv.org/abs/2403.02310) 把长提示切成大小相近的块，和解码请求放进同一批，不暂停正在进行的解码；论文报告 Mistral-7B 在单张 A100 上服务能力比 vLLM 高 2.6 倍。[vLLM 文档](https://docs.vllm.ai/en/latest/configuration/optimization/)说明，V1 架构默认尽可能开启分块预填充，调度时优先放解码请求，再用 `max_num_batched_tokens` 的剩余额度安排预填充：这个值小（如 2048）ITL 更好，大一些 TTFT 更好。\n\n**显存不够时的抢占。** KV Cache 放不下所有请求时，vLLM 会抢占部分请求、之后重新计算（V1 默认 `RECOMPUTE`）。日志里频繁出现抢占警告时，文档建议提高 `gpu_memory_utilization`、降低 `max_num_seqs` 或 `max_num_batched_tokens`，或者用张量并行把权重分到多张卡上，给 KV Cache 腾地方。\n\n## 第四步：前缀缓存——共享开头只算一次\n\n很多请求的开头是一样的：同一段系统提示、同一份长文档、多轮对话的历史。**前缀缓存**把算好的 KV Cache 留下来，新请求开头相同就直接复用，跳过这部分预填充。\n\n- **vLLM 的自动前缀缓存（APC）**：[设计文档](https://docs.vllm.ai/en/latest/design/prefix_caching/)说明，它给每个 KV 块算一个哈希，哈希由“父块的哈希 + 本块的 token + 额外信息（LoRA ID、图片哈希、多租户隔离用的 cache salt）”组成，只缓存填满的块；从 v0.11 起默认用 sha256，降低哈希碰撞风险。当前版本默认开启。\n- **SGLang 的 RadixAttention**：[SGLang 论文](https://arxiv.org/abs/2312.07104)把所有请求的提示和生成结果放进一棵**基数树（radix tree）**，用 LRU 策略从叶子开始淘汰；缓存和正在运行的请求共用同一块显存池。调度时按匹配到的前缀长度排序、优先跑前缀更长的请求（缓存感知调度），论文证明离线情况下按深度优先顺序访问基数树能达到最优命中率。论文报告在 Agent 控制、少样本、JSON 解码、RAG、多轮对话等任务上吞吐最高提升 6.4 倍。\n\n**收益边界。** [vLLM 文档](https://docs.vllm.ai/en/latest/features/automatic_prefix_caching/)写得很清楚：前缀缓存只减少预填充时间，不减少解码时间；回答很长、或者请求之间没有共同前缀时，几乎没有收益。所以写应用时要**把固定内容放在提示开头、变化的内容放在后面**，否则缓存命中不了。\n\n本课用 llama.cpp 的 `llama-server`（它的 `cache_prompt` 默认开启，见[官方文档](https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md)）实测：同一份约 1,150 个 token 的“产品手册”作为系统提示，第一次提问 TTFT 为 2,280 ms，换一个问题再问只要 164 ms；服务日志显示第二次只对新增的 9 个 token 做了预填充，其余 1,100 多个 token 直接复用了缓存。\n\n```python\nimport time\nfrom openai import OpenAI\nclient = OpenAI(base_url=\"http://localhost:8080/v1\", api_key=\"not-needed\")\ndoc = \"以下是产品手册。\" + \"本产品支持离线运行、多语言界面和自动备份。\" * 80\n\ndef ttft(question):\n    t0 = time.perf_counter()\n    stream = client.chat.completions.create(\n        model=\"local\", stream=True, max_tokens=8, temperature=0,\n        messages=[{\"role\": \"system\", \"content\": doc},          # 固定内容放前面\n                  {\"role\": \"user\", \"content\": question}])      # 变化的放后面\n    first = None\n    for chunk in stream:                                        # 读完整个流再发下一个请求\n        d = chunk.choices[0].delta if chunk.choices else None\n        if first is None and d and (d.content or getattr(d, \"reasoning_content\", None)):\n            first = time.perf_counter()                         # 思考模型先输出推理内容\n    return (first - t0) * 1000\n\nprint(f\"第一次：{ttft('产品支持离线吗？'):.0f} ms\")    # 实测 2280 ms\nprint(f\"第二次：{ttft('有没有自动备份？'):.0f} ms\")    # 实测 164 ms，前缀命中缓存\n```\n\n## 第五步：推测解码——让大模型一次验证多个 token\n\n解码受内存带宽限制：大模型算 1 个 token 和并行检查 5 个 token 的耗时差不多。**推测解码**（[Leviathan 等，2022](https://arxiv.org/abs/2211.17192)；同期 DeepMind 的[推测采样](https://arxiv.org/abs/2302.01318)）利用这一点：\n\n1. 便宜的草稿模型先连续猜 γ 个 token；\n2. 大模型一次前向，同时算出这 γ 个位置的概率；\n3. 逐个决定接受还是拒绝：草稿 token x 以 min(1, p(x)/q(x)) 的概率接受（p 是大模型分布，q 是草稿分布）；一旦拒绝，就从 norm(max(0, p − q)) 里重新采样一个 token，后面的草稿全部丢弃。\n\n这样每轮至少产出 1 个 token，最多 γ+1 个，而且**输出分布和只用大模型完全相同**。论文定义接受率 α = E[Σ min(p, q)]，每轮平均产出 (1 − α^(γ+1)) / (1 − α) 个 token。原论文在 T5-XXL 上实测加速 2–3 倍、输出不变；推测采样在 70B 的 Chinchilla 上加速 2–2.5 倍。\n\n下面用 NumPy 验证“接受/拒绝规则不改变分布”（本课实测运行）：\n\n```python\nimport numpy as np\nrng = np.random.default_rng(0)\np = np.array([0.40, 0.25, 0.15, 0.12, 0.08])   # 大模型的下一个 token 分布\nq = np.array([0.20, 0.40, 0.20, 0.10, 0.10])   # 草稿模型的分布，故意不准\n\ndef step():\n    x = rng.choice(5, p=q)                       # 草稿先猜\n    if rng.random() < min(1, p[x] / q[x]):       # 以 min(1, p/q) 接受\n        return x, True\n    r = np.maximum(p - q, 0)                     # 拒绝：从 norm(max(0, p-q)) 重采样\n    return rng.choice(5, p=r / r.sum()), False\n\nN = 200_000\nxs, acc = zip(*(step() for _ in range(N)))\nprint(np.round(np.bincount(xs, minlength=5) / N, 3))   # [0.402 0.25 0.149 0.12 0.079] ≈ p\nalpha = np.minimum(p, q).sum()\nprint(f\"{np.mean(acc):.3f} {alpha:.3f}\")                # 0.780 0.780：接受率 = Σmin(p,q)\nprint(f\"{(1 - alpha**5) / (1 - alpha):.2f}\")            # γ=4 时每轮平均产出 3.23 个 token\n```\n\n**不用独立草稿模型的变体：**\n\n- [Medusa](https://arxiv.org/abs/2401.10774)：在大模型上加几个额外的解码头，同时预测后面几个 token，用树状注意力一次验证多条候选。Medusa-1 冻结主干只训练新头，论文报告加速 2.2 倍以上且不损失质量；Medusa-2 和主干一起训练，加速 2.3–3.6 倍。\n- [EAGLE](https://arxiv.org/abs/2401.15077)：在倒数第二层的**特征**上做自回归预测，再输入提前一步的 token 序列消除不确定性；LLaMA2-Chat 70B 上延迟加速 2.7–3.5 倍、吞吐翻倍，且不改变输出分布。[EAGLE-2](https://arxiv.org/abs/2406.16858) 改用随上下文变化的动态草稿树，加速 3.05–4.26 倍；[EAGLE-3](https://arxiv.org/abs/2503.01840) 放弃特征预测、直接预测 token 并融合多层特征，最高加速 6.5 倍，在 SGLang 中 batch 64 时吞吐提升 1.38 倍。\n\n**在引擎里开启。** vLLM 用 `--speculative-config` 传 JSON，例如 `{\"method\": \"eagle3\", \"model\": \"<草稿权重>\", \"num_speculative_tokens\": 2}`，还支持草稿模型、MTP、n-gram 等方法（[vLLM 文档](https://docs.vllm.ai/en/latest/features/speculative_decoding/)）；SGLang 用 `--speculative-algorithm EAGLE3 --speculative-draft-model-path ... --speculative-num-steps 3 --speculative-eagle-topk 4 --speculative-num-draft-tokens 16`（[SGLang 文档](https://docs.sglang.io/docs/advanced_features/speculative_decoding)）。注意 vLLM 文档的定位：推测解码用来降低**中低 QPS**、受内存带宽限制时的 token 间延迟；高并发下收益会变小。草稿权重必须和目标模型配套。\n\n## 第六步：预填充/解码分离（PD 分离）\n\n预填充是算力密集型，解码是内存带宽密集型，放在同一组 GPU 上会互相干扰。[DistServe](https://arxiv.org/abs/2401.09670) 把两个阶段放到不同 GPU 上，按 TTFT 和 TPOT 目标分别选择资源和并行方式，报告在满足延迟约束（>90% 请求达标）时可服务 7.4 倍的请求，或把 SLO 收紧 12.6 倍。微软的 [Splitwise](https://arxiv.org/abs/2311.18677) 把两个阶段放到不同机器上，报告在成本降低 20% 时吞吐提高 1.4 倍。\n\n工程上要付出代价：KV Cache 要在机器之间传输，需要高速互联。[vLLM 文档](https://docs.vllm.ai/en/latest/features/disagg_prefill/)说明这项功能仍是实验性的，它的价值是分别调优 TTFT 和 ITL、控制尾部 ITL，**不提高吞吐**；用合适的分块大小做分块预填充也能达到类似目的，只是块大小难调。SGLang 支持用 Mooncake 或 NIXL 传输 KV 的 PD 分离（[文档](https://docs.sglang.io/docs/advanced_features/pd_disaggregation)）。\n\n## 第七步：动手部署与压测\n\n**vLLM**（NVIDIA GPU；[快速上手](https://docs.vllm.ai/en/latest/getting_started/quickstart/)）：\n\n```bash\nuv venv --python 3.12 --seed && source .venv/bin/activate\nuv pip install vllm --torch-backend=auto\nvllm serve Qwen/Qwen2.5-1.5B-Instruct            # 默认监听 http://localhost:8000，OpenAI 兼容\n# 加 --api-key 才会校验密钥；上线前务必加上\n\n# 另开终端压测：随机数据，输入 1024 / 输出 128 token，限制最大并发 16\nvllm bench serve --backend vllm --model Qwen/Qwen2.5-1.5B-Instruct \\\n  --endpoint /v1/completions --dataset-name random \\\n  --random-input-len 1024 --random-output-len 128 \\\n  --num-prompts 200 --max-concurrency 16\n```\n\n输出会给出请求吞吐、输出 token 吞吐，以及 TTFT、TPOT、ITL 的均值、中位数和 P99。`--request-rate` 默认 `inf`（所有请求一开始就发出，测最大吞吐）；设成有限值时按泊松过程发请求，更接近真实流量。vLLM 文档还推荐用 GuideLLM 做生产环境压测。\n\n**SGLang**（[快速上手](https://docs.sglang.io/docs/get-started/quickstart)、[压测指南](https://docs.sglang.io/docs/developer_guide/bench_serving)）：\n\n```bash\nuv pip install --prerelease=allow sglang\nsglang serve Qwen/Qwen2.5-1.5B-Instruct --host 0.0.0.0 --port 30000\npython3 -m sglang.bench_serving --backend sglang --host 127.0.0.1 --port 30000 \\\n  --dataset-name random --num-prompts 200 --max-concurrency 16\n```\n\n显存不够时调小 `--mem-fraction-static`（权重 + KV Cache 池占显存的比例）；`--chunked-prefill-size` 控制分块预填充大小；`--disable-radix-cache` 关掉 RadixAttention，可以用来对比前缀缓存的收益（[参数文档](https://docs.sglang.io/docs/advanced_features/server_arguments)）。\n\n上面 vLLM / SGLang 命令按 2026-10-25 的官方文档核对，本机没有 GPU，未实测。**没有 GPU 也能练习压测方法**：下面的脚本对任何 OpenAI 兼容服务测 TTFT、TPOT 和吞吐，本课用 llama.cpp 的 `llama-server -m Qwen3-0.6B-Q4_K_M.gguf -c 8192 -np 4 --port 8080` 实测，结果就是第一步的表格：\n\n```python\nimport asyncio, time, statistics\nfrom openai import AsyncOpenAI\nclient = AsyncOpenAI(base_url=\"http://localhost:8080/v1\", api_key=\"not-needed\")\n\nasync def one(prompt, max_tokens=128):\n    t0 = time.perf_counter(); first = None; n = 0\n    stream = await client.chat.completions.create(\n        model=\"local\", stream=True, max_tokens=max_tokens, temperature=0,\n        stream_options={\"include_usage\": True},          # 最后一块返回 token 用量\n        messages=[{\"role\": \"user\", \"content\": prompt}])\n    async for chunk in stream:\n        d = chunk.choices[0].delta if chunk.choices else None\n        if d and (d.content or getattr(d, \"reasoning_content\", None)) and first is None:\n            first = time.perf_counter()                   # 第一段输出到达 → TTFT\n        if chunk.usage:\n            n = chunk.usage.completion_tokens\n    end = time.perf_counter()\n    return first - t0, (end - first) / max(n - 1, 1), n   # TTFT、TPOT、输出 token 数\n\nasync def run(concurrency, total=16):\n    sem = asyncio.Semaphore(concurrency)\n    async def guarded(i):\n        async with sem:\n            return await one(f\"第 {i} 题：用三句话解释什么是 KV Cache。\")\n    t0 = time.perf_counter()\n    res = await asyncio.gather(*(guarded(i) for i in range(total)))\n    wall = time.perf_counter() - t0\n    print(f\"并发 {concurrency}: TTFT 中位 {statistics.median(r[0] for r in res)*1000:.0f} ms, \"\n          f\"TPOT 中位 {statistics.median(r[1] for r in res)*1000:.1f} ms, \"\n          f\"吞吐 {sum(r[2] for r in res)/wall:.1f} tok/s\")\n\nfor c in (1, 4):\n    asyncio.run(run(c))\n```\n\n注意：`llama-server` 显式设置 `-np 4` 时，本课实测 `-c 8192` 的上下文被平分给 4 个槽位，每个请求最多 2048 个 token，超长请求会直接报错；`-np` 不设（自动）时默认使用所有槽位共享的统一 KV 缓冲区（`--kv-unified`）。\n\n## 怎么选推理引擎\n\n| 场景 | 常见选择 | 说明 |\n|---|---|---|\n| 数据中心 GPU，多用户 API 服务 | [vLLM](https://github.com/vllm-project/vllm)、[SGLang](https://github.com/sgl-project/sglang) | 都有 PagedAttention 式的分块 KV 管理、连续批处理、前缀缓存、推测解码、OpenAI 兼容接口；用自己的负载压测后再定 |\n| 多轮对话、Agent、大量共享前缀 | 两者都测，重点看 SGLang | RadixAttention 和缓存感知调度针对的就是这类负载 |\n| 个人电脑、CPU、Apple 芯片、小规模内网服务 | [llama.cpp](/apps/llama-cpp)、[Ollama](/apps/ollama)、[MLX LM](/apps/mlx-lm) | 量化模型、跨平台；`llama-server` 也有并行槽位和提示缓存，但不是为大规模高并发设计的。详见[在自己电脑上运行大模型](/learn/local-llm) |\n| 多家模型统一接入、回退、限流、记账 | 在引擎前面加模型网关 | 见[模型网关、路由与成本控制](/learn/model-gateway) |\n\n## 常见坑\n\n| 现象 | 原因 | 解决 |\n|---|---|---|\n| 压测成绩很好，上线后慢 | 压测数据重复命中前缀缓存，或输入/输出长度与真实业务差别大 | 换 seed 或重启服务；用接近真实分布的长度和到达速率 |\n| 日志频繁出现抢占（preempted）警告 | KV Cache 放不下当前并发 | 提高 `gpu_memory_utilization`、降低 `max_num_seqs`，或用张量并行 |\n| 长提示请求进来时，其他用户输出明显卡顿 | 预填充打断解码 | 确认分块预填充开启，调小 `max_num_batched_tokens` |\n| 前缀缓存命中率很低 | 提示开头放了时间戳、用户名等每次都变的内容 | 固定内容放开头，变化内容放末尾 |\n| 开了推测解码反而变慢 | 并发高、算力已满，或草稿与目标模型不配套、接受率低 | 低并发场景再开；换官方配套的 EAGLE/MTP 权重，看接受率指标 |\n| 服务被陌生人调用 | 默认不校验密钥 | `--api-key`，并放在网关或反向代理后面 |\n\n## 动手试试\n\n1. **跑通 vLLM**：按 [vLLM 快速上手](https://docs.vllm.ai/en/latest/getting_started/quickstart/)起一个 OpenAI 兼容服务，用 `vllm bench serve` 在并发 1、8、32 下各测一次，画出“吞吐–TTFT”曲线。\n2. **对比前缀缓存**：在 [SGLang](https://github.com/sgl-project/sglang) 上用同样的负载各跑一次（默认、`--disable-radix-cache`），负载里让 80% 的请求共享一段 2,000 token 的系统提示，比较 TTFT。\n3. **没有 GPU**：用 [llama.cpp](/apps/llama-cpp) 的 `llama-server` 跑上面的压测脚本，改变 `-np` 看吞吐和延迟怎么变。\n4. **单元项目**：部署一个 7B/8B 开源模型，测并发 1–64 下的吞吐和 P99 TTFT，再开启推测解码（EAGLE-3 或 n-gram）对比低并发和高并发两种情况，写下“什么时候值得开”的结论。\n\n相关算法卡片：[PagedAttention](/learn/algorithms/paged-attention)、[连续批处理](/learn/algorithms/continuous-batching)、[RadixAttention 前缀缓存](/learn/algorithms/radix-attention)、[推测解码](/learn/algorithms/speculative-decoding)、[Medusa](/learn/algorithms/medusa)、[EAGLE](/learn/algorithms/eagle)、[预填充/解码分离](/learn/algorithms/pd-disaggregation)。"
    }
  }
}