页面简介
正文摘录
The language models in this book generated text in a notebook, one prompt at a time, for the person who ran the cell. Suppose instead that a hundred colleagues send requests to the same language model whenever they like. If the GPU answers them one after another at two seconds each, the last colleague waits more than three minutes. What has to change between calling a model and serving it? Serving makes one accelerator work on many requests at once. Generating a token reads the weights and the key–value cache from memory (Section 27.4). All requests share the weights, so an engine that advances many requests in the same step reads the weights once for all of them, provided memory holds the cache of every active request. We start with the latency numbers that users notice, survey local and server engines as of November 2026, and explain the techniques that make the engines fast. 27.7.1 Workloads and Latency Metrics A user of a chat assistant notices two delays: the wait before the first word appears, and the pace of the words that follow. The first is the time to first token (TTFT), counted from the arrival of the request. On an idle server it is dominated by prefill, which processes all prompt tokens in parallel and is bound by compute. The second is the time per output token (TPOT), dominated by decode, which produces one token per sequence and step and is bound by memory bandwidth. Throughput, the tokens per second summed over all users, trades against both. Figure 27.7.1: Prompt prefill is parallel and often compute-heavy; autoregressive decode advances one token per sequence and stresses memory movement. Which numbers matter depends on the workload, and the workload picks the tool: Table 27.7.1: Serving workloads and example starting points (as of November 2026) Workload Optimize for Start with Personal assistant on your machine simplicity, privacy Ollama / LM Studio (llama.cpp), MLX on Macs Offline batch scoring throughput per dollar vLLM offline mode One application’s API operability vLLM behind a small authenticated proxy Multi-user / agentic service goodput under an SLO vLLM or SGLang, then NVIDIA Dynamo at scale Max throughput on fixed NVIDIA fleet throughput per GPU TensorRT-LLM A service level objective (SLO) sets a latency target, such as a TTFT below 1 s. Goodput, the rate of completed requests that also met their target, is the production metric. Overload can raise raw throughput while goodput collapses, because requests queue until they miss their targets. 27.7.2 Local Serving On a laptop or a workstation with one user, the questions are whether a model fits and how fast it answers. Many local inference tools use llama.cpp and its GGUF file format, and community repositories commonly publish GGUF conversions of open-weight models. Users often reach llama.cpp through a wrapper: Ollama builds on llama.cpp and, on Apple silicon, also on MLX. ollama run qwen3:8b downloads, caches, and serves a model, with an OpenAI-compatible API at http://localhost:11434/v1. LM Studio offers the same engines behind a graphical interface, with control over how much of the model is offloaded to the GPU. MLX is Apple’s array framework. Its package mlx-lm runs and fine-tunes models on Apple silicon, and the mlx-community organization on Hugging Face publishes thousands of converted models. Common GGUF quantizations include Q4_K_M (about 4.9 bits per weight), Q5_K_M (about 5.7), and Q8_0 (about 8.5). For the 8.2 billion parameters of Qwen3-8B, Q4_K_M gives \(8.2 \times 10^9 \times 4.9 / 8 \approx 5.0\) GB, close to the 5.2 GB of Ollama’s qwen3:8b download. The 4.9 bits were measured on Llama 3.1 8B, and Q4_K_M keeps a model-dependent share of tensors at higher precision. The cache of a full 32,768-token context in bf16 adds almost as much again. Higher-bit formats usually retain quality better; measure the effect on your own task. Decode speed is at most the memory bandwidth divided by the bytes read per token, so every extra bit costs speed as well as memory. A common rule is to pick the largest model whose quantized weights fit in memory with room for the cache, then the highest-bit format that still fits. 27.7.3 Server Engines 27.7.3.1 Open-Source and NVIDIA Engines A shared server needs an engine that schedules requests together. For an open-source GPU server, vLLM provides continuous batching, paged KV-cache management, prefix caching, tensor parallelism, quantized-model support, and an OpenAI-compatible server in one command: vllm serve Qwen/Qwen3-8B --max-model-len 32768 SGLang is its closest peer. Its RadixAttention (Zheng et al. 2024) keeps cached keys and values in a radix tree shared across requests, which helps when many requests share long prefixes: chat with a system prompt, retrieval over the same documents, or trees of agent calls. Both projects evolve quickly and support several accelerator backends; benchmark both on your distributions of prompt length and concurrency before selecting one. NVIDIA’s tools trade portability for hardware-specific optimization. TensorRT-LLM runs models on PyTorch with NVIDIA-tuned kernels, which can improve steady-state throughput at the cost of more setup. Dynamo coordinates many GPUs and nodes, with vLLM, SGLang, or TensorRT-LLM as backends. It runs prefill and decode on separate pools of GPUs and routes each request by worker load and by how much of its prefix a worker already caches. These tools matter at datacenter scale; on a few GPUs, vLLM or SGLang alone is simpler. 27.7.3.2 A Common Client API An application should not need rewriting when it moves from a laptop to a server. Many of these tools implement the OpenAI chat-completions API, so the same client code targets a local Ollama, your vLLM server, or a commercial provider after a change of the base URL and the model name: from openai import OpenAI client = OpenAI(base_url="http://127.0.0.1:8000/v1", api_key="local") response = client.chat.completions.create( model="Qwen/Qwen3-8B", messages=[{"role": "user", "content": "Explain KV caching briefly."}], temperature=0, ) print(response.choices[0].message.content) Servers that accept the same requests can still answer them differently: tokenization, sampling defaults, structured-output support, streaming behavior, and token accounting all vary. Keep a small conformance test and rerun it before swapping engines. 27.7.4 Engine Techniques Four composable techniques explain much of the speed of these engines. Continuous batching. A static batch waits for its slowest member. Continuous batching admits new requests and retires finished ones between decode steps, keeping the batch nearly full: Figure 27.7.2: Two batch slots serving requests of 5, 2, 7, and 3 output tokens, as in the toy scheduler below. Static batching pads each batch to its longest member; continuous batching refills a finished slot at the next step and finishes in 9 steps instead of 12. The toy scheduler below captures the idea in a few lines. Exercise 4 extends it with arrival times and a memory budget: from collections import deque requests = deque([5, 2, 7, 3]) # output tokens requested capacity = 2 active, timeline = [], [] while requests or active: while requests and len(active) < capacity: active.append(requests.popleft()) timeline.append(tuple(active)) active = [remaining - 1 for remaining in active if remaining > 1] timeline [(5, 2), (4, 1), (3, 7), (2, 6), (1, 5), (4, 3), (3, 2), (2, 1), (1,)] Paged KV cache. Each active sequence’s key–value cache grows with its length. vLLM’s PagedAttention (Kwon et al. 2023) allocates it in fixed-size blocks, like virtual memory, and so nearly eliminates the fragmentation that once capped batch sizes. Capacity planning follows: GPU memory must hold the weights plus the cache of every concurrent sequence. A model that fits for one request may therefore exceed memory under high concurrency. Prefix caching. When two requests share a tokenized prefix (the same system prompt, the same document), its cached keys and values can be computed once and reused: Figure 27.7.3: A prefix cache reuses KV state only when tokenized prefixes match, then computes each request’s unique suffix. Some commercial APIs charge less for cached input tokens, under rules that differ by provider. Placing shared, stable content before the variable part of a prompt then saves money as well as prefill time. Speculative decoding and quantization. A small draft model proposes several tokens, and the target model verifies them in one parallel pass. This speeds up decoding when most proposals are accepted and preserves the target distribution. Quantization reduces the bytes read during decode: fewer bytes per weight give more tokens per second, until quality degrades at the lowest bit widths. Recent NVIDIA tensor cores support FP8 (from the Hopper and Ada generations on) and NVFP4 (from Blackwell on), and vLLM and SGLang also load 4-bit AWQ weights. GGUF formats play the same role locally. 27.7.5 Operations An engine listening on a port still lacks the controls that a shared service needs. Put authentication, TLS, and rate limits in a proxy in front of the engine, and do not expose the engine’s own port. Admission control should reject or queue requests before memory runs out, not after an out-of-memory error. Propagate client cancellations so that abandoned generations stop consuming compute. Measure TTFT, TPOT, and end-to-end latency as p50 and p95 under realistic arrival patterns, not as averages under a closed loop of clients. Avoid logging raw prompts by default. Pin the model, tokenizer, quantization, and engine versions together: a faster server that answers differently is a different system, so gate rollouts on task quality as well as on latency. You can now estimate whether a model and the caches of its users fit on a card, and which engine to try first. How a server should admit and order requests under load remains open; the simulators of the exercises explore it. 27.7.6 Summary Servin