Part III / Inference Engineering
Remembering the prompt
Autoregressive decode avoids recomputing the entire past by storing attention keys and values. That optimization creates the serving engine's most important dynamic memory budget.
Per-layer key and value vectors for cached tokens.
Linear with active tokens, layers, KV heads, and element size.
Page, reuse, admit, preempt, and evict under memory pressure.
A notebook for every active conversation
Without notes, a speaker would reread the entire transcript before saying each new word. The KV cache is the model's layer-by-layer notebook of attention representations for previous tokens. During decode, each layer computes K and V only for the new token and attends to cached history.
Weights are the shared book every request reads. KV cache is the private growing notebook each active sequence owns. Serving capacity depends on both.
For a decoder-only transformer, a common rough formula is:
Architectures with multi-query or grouped-query attention use fewer KV heads than query heads, reducing cache size and bandwidth.[source] Quantized KV formats reduce bytes per element. Sliding-window attention may retain only a recent region for selected layers. Runtime metadata and allocator overhead add to the ideal formula.
The transcript grows while tools run
An incident-reasoning session begins at 8,000 tokens and grows to 24,000 after topology, telemetry, logs, and two candidate analyses. Ten concurrent investigations can hold hundreds of thousands of cached token positions even while some wait on tools.
The calculator shows per-sequence KV under simplified assumptions. Multiply by active sequences and add weights, runtime workspace, temporary prefill activations, CUDA graphs, and fragmentation. Admission control must leave safety margin. An out-of-memory failure at peak load is a capacity-policy failure, not an exceptional surprise.
Tool waits create a choice. Keep the sequence's cache resident for fast resumption, swap or offload it to reclaim accelerator memory, or discard and recompute the prefix later. The right answer depends on expected wait, cache size, transfer bandwidth, recompute cost, and SLO.
Why ordinary contiguous allocation wastes capacity
If a runtime reserves one contiguous region for each sequence's maximum possible length, short outputs waste space and unpredictable growth causes fragmentation. PagedAttention applies virtual-memory ideas: split KV storage into fixed-size blocks, map a sequence's logical token positions to non-contiguous physical blocks, and allocate blocks as it grows.[source]
Paging reduces internal waste and enables block sharing, copy-on-write, and flexible admission. It does not make memory free. Block tables consume metadata, small blocks increase management overhead, large blocks increase tail waste, and attention kernels must follow the mapping efficiently.
Prefix caching turns repetition into capacity
Many requests share system prompts, tool schemas, few-shot examples, repository context, or conversation prefixes. A prefix cache reuses the KV blocks for an exact token prefix instead of recomputing prefill. SGLang's RadixAttention organizes reusable prefixes in a radix tree and integrates cache-aware scheduling.[source]
Cache identity is stricter than equal-looking text. Token IDs, model weights, adapters, positions, attention behavior, precision assumptions, and relevant prompt transformations must match. Mutable external data inside a cached prefix raises freshness questions. Security boundaries must prevent one tenant from inferring or receiving another tenant's private context through shared cache state.
Measure hit rate in saved prefill tokens or time, not request count alone. A hit on a 20,000-token prefix is worth more than one on 50 tokens. Also measure lookup overhead, eviction churn, and whether cache-aware routing increases queueing.
Eviction is a product policy
When memory fills, the runtime chooses what loses residency. Least-recently-used is simple; longest-prefix, recompute-cost, priority, tenant quota, and expected reuse may be better signals. Active decode KV is usually harder to evict than an inactive reusable prefix. Preemption can swap cache, recompute it, or reject new work.
| Candidate | Benefit of keeping | Cost of eviction |
|---|---|---|
| Active user sequence | Maintains ITL and progress | Swap or expensive recompute; visible latency |
| Tool-waiting agent | Fast resumption | Depends on wait duration and prefix size |
| Shared system prefix | Saves future prefill across many requests | Recompute on next hit |
| Low-priority rollout | Preserves offline throughput | Can often pause under an explicit policy |
Make these priorities explicit. Otherwise allocator accident decides which customers and workloads lose latency under pressure.
It stores attention keys and values computed from tokens at each layer, not a human-readable memory or a guaranteed semantic summary. It accelerates exact continuation for that model execution.
Context length is a fleet multiplier
Increasing maximum context affects more than one request's memory. It changes admission headroom, batch size, cache eviction, prefill latency, attention traffic, and worst-case capacity. Most requests may be short, but a few large agents can dominate peak memory. Use length-aware quotas, separate pools, chunking, or explicit pricing rather than one unlimited class.
For RL, long trajectories multiply cache pressure across many concurrent samples. Prefix sharing across group rollouts can be especially valuable because all samples begin with the same prompt and scenario context, then branch. The serving runtime and rollout sampler should expose that structure rather than serializing eight independent cold prefills.
References
- Kwon et al. is the primary PagedAttention source.
- SGLang is the source for RadixAttention and cache-aware structured serving.
- Ainslie et al. is the primary source for grouped-query attention.