Chapter 55
Serving, Attention, and Memory Hierarchies
On this page
- Attention pipelines on newer accelerators
- Blackwell attention and the limits of FP4
- Read the 2026 developments through the earlier chapters
- Draft quality must repay its own cost
- KV-centric disaggregation
- A cache is now part of the architecture
- Worked admission ledger: count the complete worker
- Runnable load experiment: admission is not useful throughput
- From simulation to a measured GPU serving run
- Long-context memory is becoming hierarchical
- Design Exercises
- Worked Solutions
The recent inference frontier is defined less by one universal engine than by explicit management of asynchronous hardware, phase-specific work, KV placement, and overload.
Attention pipelines on newer accelerators¶
The 2024 FlashAttention-3 paper targets Hopper GPUs with warp specialization, asynchronous Tensor Memory Accelerator transfers, overlap between matrix multiplication and softmax, and an FP8 path with block quantization. The paper reports 1.5 to 2.0 times speedup over FlashAttention-2 on H100, up to 740 FP16 TFLOP/s, and nearly 1.2 PFLOP/s for FP8. These are attention-kernel results over the evaluated shapes, not whole-model or service speedups. It also reports lower numerical error than a baseline FP8 attention implementation.
The buffer and dependency mechanisms are derived in Part IV's Blackwell Pipelines and Modern Attention Kernels. Here the adoption question is which part of a measured workload can benefit. Suppose attention consumes 30% of execution time and a candidate accelerates that component by 1.5x without changing any other cost. The ideal whole-model speedup is 1/(0.70+0.30/1.5) = 1.111, about 11.1%. If only half the attention calls have supported shapes, it falls to 1/(0.85+0.15/1.5) = 1.053, about 5.3%. These are calculated bounds, not reproduced paper results.
A useful dispatch experiment therefore records the fraction of calls and elapsed time that actually take the new path. Include ragged and causal shapes, head dimensions, backward/decode variants and fallback behavior. A faster supported path can coexist with unchanged or slower total throughput when most work falls back or shape conversions consume the saving. This changed-shape calculation connects the research claim to a decision without repeating the kernel derivation.
Blackwell attention and the limits of FP4¶
FlashAttention-4, published in March 2026, addresses asymmetric hardware scaling: matrix throughput improves faster than exponential evaluation and shared-memory bandwidth. Its pipeline uses asynchronous matrix operations, tensor memory, and software techniques that reduce softmax overhead; its implementation uses CuTe-DSL. The paper reports up to 1.3 times the BF16 throughput of cuDNN 9.13 on B200 for its evaluated attention kernels. That comparator and hardware are essential; this is not a general service-level improvement over FlashAttention-3.
The September 3 preprint Hardware-Aware FP4 FlashAttention-4, version 1, sharpens the distinction between a fast kernel and a sound training recipe. It reports an FP4 noncausal inference path and a separate causal training path, but also reports divergence in every tested distributed-training trajectory using MXFP4 probabilities and values. Its matched distributed runs retain FP8 for those operands. Treat this as provisional, boundary-specific evidence, not proof that attention can now use four bits everywhere.
The engineering implication is to keep a precision ledger for Q, K, V, scores, probabilities, accumulators, gradients, and scaling factors. Test long reductions, outliers, masks, and backward stability independently. A matrix unit's nominal throughput cannot compensate for conversion overhead, a softmax bottleneck, or failed optimization. Part IV supplies the ownership and synchronization details behind this pipeline.
Read the 2026 developments through the earlier chapters¶
Part IV derives Blackwell ownership and the FlashAttention-4 pipeline. Part III compares feature-based and block-parallel speculative drafts, including EAGLE-3 and DFlash, while retaining the target-distribution verification contract. Part II develops group-relative RL, sequence-level ratios, and feedback-conditioned self-distillation; Part V explains why asynchronous training needs policy-freshness control. These changes act on different parts of the system, so each needs its own acceptance test.
| Change | Quantity it tries to improve | Evidence that could reject it |
|---|---|---|
| Better speculative draft | Committed target tokens per unit time | Draft/verification overhead or state rollback defeats the gain |
| New attention pipeline | Kernel critical-path time | Unsupported shapes, numerical drift, or another layer dominates |
| Recurrent / compressed state | Persistent bytes and history processing | Required long-range information is lost |
| Better RL feedback | Useful learning signal per rollout | Verifier shortcuts or held-out regression |
| Asynchronous RL | Useful learner/rollout utilization | Stale-data bias, variance, or selection changes quality |
Draft quality must repay its own cost¶
The 2026 speculative frontier extends beyond choosing a fixed draft length. DFlare, version 2, conditions different draft layers on learned combinations of target-layer features to increase block-draft capacity. CaDDTree, version 1, chooses both the candidate-tree structure and node budget against expected throughput, explicitly accounting for verification latency. These are research proposals with evaluated model/task boundaries, not universal engine defaults.
For an independent worked example, a candidate that commits six tokens in a 12-millisecond draft/verify round yields 500 committed tokens per second. A wider candidate that commits eight in 20 milliseconds yields 400. Acceptance length increased while throughput fell. At larger serving batches, extra draft or verification work may also displace other requests. Measure committed tokens and SLO goodput, including rollback and scheduling, rather than acceptance alone. Exact target-distribution preservation still requires the correct proposal and verification procedure; it cannot be inferred from a model's use of the word "speculative."
KV-centric disaggregation¶
Mooncake reports a disaggregated serving architecture that separates prefill and decode clusters and treats KV state as a distributed object across GPU memory, CPU memory, and SSD. Its scheduler chooses placement and admission under latency objectives. The paper reports up to 525 percent higher throughput than its baseline in selected simulations and 75 percent more handled requests on a production workload. A 525 percent increase means 6.25 times the baseline throughput; it is not the production-workload result and is not a matched comparison against every current serving engine.
The general lesson is that disaggregation works only when state movement is first-class. A phase boundary needs:
- a stable identity for model, adapter, tokenizer, prompt prefix, and KV format;
- an ownership transfer protocol with completion and retry semantics;
- bandwidth and tail-latency budgets for the transfer path;
- admission that rejects work before expensive partial execution when overload is unavoidable;
- observability for cache hit, transfer, queue, recompute, and abandoned state.
Disaggregation can improve independent scaling and isolation while adding network dependence and a new distributed lifecycle. It wins when phase imbalance and placement flexibility repay the transfer and coordination cost.
The implementation frontier now exposes this lifecycle as composable subsystems. The September 28 source records cite Dynamo's disaggregated-serving guide and router concepts for prefill/decode pools, KV handoff, and cache-aware routing; LMCache's architecture guide for multi-tier KV storage; and llm-d's cache-index architecture for event ingestion, prefix scoring and GPU/CPU tier indexing. The relocated llm-d reference was rechecked October 12; its index is distinct from a data-transfer service. These project documents are mutable; their date-stamped excerpts and hashes are retained in docs/source-snapshots/. Record a tested revision before implementation. A useful bake-off replays the same trace and measures stale-route rate, reusable-token fraction, transfer versus recompute choice, admission failures after prefill, failover, and SLO goodput—not just a warm-cache microbenchmark.
For the practical reading path, return to Serving Engines and Cache Backends in Practice in Part III. It distinguishes an engine iteration from a kernel call, a cache transfer, and a fleet-routing decision. The purpose of this research snapshot is to identify which of those boundaries a result changes, not to select a stack by counting project names.
Within each pool, long-context sharding is also phase-specific. The vLLM 0.16.0 context-parallel guide distinguishes prefill context parallelism, which partitions prompt queries and either gathers or circulates K/V, from decode context parallelism, which shards historical KV tokens and combines partial attention results. Disaggregation adds another axis: the prefill and decode pools may select different TP, PP, PCP, or DCP plans, but a heterogeneous boundary must reshard compatible state during handoff. Part V gives the full ownership ledger. The source wording checked September 28 is retained in docs/source-snapshots/.
A cache is now part of the architecture¶
The September-inspected DeepSeek-V4.1-Flash card describes a causal encoder-decoder whose decoder global KV comes from final encoder states. Its CSA2 scheme shares KV and indexing state across layers; a sliding-window replay mechanism reconstructs recent local state. The card reports 890 bytes per token for global KV using FP4 main-cache storage. This is a component-level figure, not the entire request footprint. It also explicitly names Engram and DSpark, so those mechanisms can be attributed to this checkpoint; the earlier V4 discussion alone cannot establish that attribution.
Using the reported global-KV figure, one million tokens occupy about 890 million bytes, or 0.83 GiB, for that component. Do not count that as the memory required to serve the model: weights, local/reconstructed state, vision processing, workspace, and concurrent requests remain. Similarly, a reusable global cache is not necessarily a zero-compute prefix hit if local state must be replayed.
A cache-hit result should therefore report at least bytes reused, bytes transferred, state reconstructed, and resumed computation. A disaggregated handoff must carry the architecture's state schema, not only a list of ordinary per-layer K/V tensors. Mixing model revisions, quantization scales, compression layouts, or recurrent snapshots can produce plausible but incorrect continuations. Validate cold execution against cache reuse, offload/reload, interruption, and branch rollback at the intended numerical tolerance.
Worked admission ledger: count the complete worker¶
Consider a hypothetical inference worker with 80 GiB of usable device memory. These are planning numbers, not measurements or the specification of a named checkpoint. All entries below are local to this worker after its chosen sharding; weights include their quantization metadata. Shared fixed allocations appear once, while request allocations scale with concurrent requests.
| Allocation | GiB | Scope and assumption |
|---|---|---|
| Resident weights and scales | 40 | Shared, already placed on this worker |
| Runtime and communication buffers | 6 | Shared worst-case allocation |
| Captured graphs and fixed scratch | 4 | Shared; excludes scratch below |
| Admission reserve | 6 | Held back for fragmentation and uncertainty |
| Attention KV | 4 | Per request, including reserved output growth |
| Recurrent and local state | 1 | Per request, hypothetical hybrid layers |
| Cache metadata and alignment | 0.25 | Per request, separate from raw KV |
| Replay, draft and transfer scratch | 2.25 | Per request at simultaneous peak |
The raw KV row follows an uncompressed example with 32 attention layers, eight KV heads, head dimension 128, two-byte elements, and a reserved total length of 32,768 tokens: 2 * 32 * 8 * 128 * 32768 * 2 = 4,294,967,296 bytes = 4 GiB. The leading two counts K and V. It is unrelated to the 890-byte global-cache component reported for the different architecture above.
Fixed allocations plus reserve total 56 GiB. Each request needs at most 7.5 GiB under these assumptions. Three concurrent requests need 56 + 3*7.5 = 78.5 GiB; four need 86 GiB and must not be admitted. Three leave 1.5 GiB beyond the explicit six-GiB reserve. Counting only raw KV would incorrectly suggest room for six requests. If a request exceeds its reserved output length, admission must obtain more capacity before growth or enforce the declared stop policy.
This is a memory ceiling, not a throughput promise. If every newly admitted request imports 4 GiB and measured usable transfer bandwidth is 20 GiB/s, five such imports per second already consume the entire link budget, before competing traffic. Transfer queues and latency may force a smaller admission rate. In a sharded deployment, repeat the ledger on every worker: free memory on one rank cannot satisfy an allocation on another, and replicated buffers must not be divided by the shard count.
Runnable load experiment: admission is not useful throughput¶
Run python -m examples.serving_load from the source repository. This deterministic CPU simulation sends 60 requests at five arrivals per second through one FIFO transfer link and one FIFO compute server. Transfers can overlap computation, but compute executes whole requests in admission order; there is no continuous batching, preemption, GPU contention model, or learned quality model. The purpose is to expose queueing and accounting errors, not predict a serving engine's performance.
Each ordinary request has 8,192 prompt tokens and reserves 128 output tokens. The model keeps the ledger's 56-GiB fixed allocation and 3.5-GiB non-KV request allocation, plus total_tokens/8192 GiB of KV. Resident slots and memory are held from admission through completion, including time waiting for import or compute. Arrivals that exceed either limit are rejected immediately. When both limits would fail, this implementation records a memory rejection first; the rejection counters are mutually exclusive bookkeeping categories. A completion at exactly an arrival time releases its reservation first. These choices are part of the experiment, not universal scheduler rules.
The invented service rates are 32,768 uncached prompt tokens/s, 131,072 cached tokens/s for local replay, and 512 output tokens/s. Reused prompt state arrives from an external tier: imported GiB divided by link GiB/s determines transfer service, and cache reuse does not reduce resident KV allocation. A request passes only if first-token latency is at most one second and completion latency at most two seconds, both measured from arrival. Goodput counts these passing completions divided by elapsed time from the first arrival through the final drain or last arrival, whichever is later. Rejections remain in the 60-request denominator for the pass fraction; accepted-only latency percentiles would hide them.
| Scenario | Admitted / offered | Slot / memory rejects | Pass both SLOs | Goodput, requests/s |
|---|---|---|---|---|
| One resident slot | 20 / 60 | 40 / 0 | 20 | 1.681 |
| Three resident slots | 26 / 60 | 34 / 0 | 3 | 0.231 |
| Six configured slots | 28 / 60 | 0 / 32 | 3 | 0.214 |
| Three slots, 32,768-token prompts | 12 / 60 | 0 / 48 | 0 | 0.000 |
| Three slots, 75% reuse, 20 GiB/s link | 35 / 60 | 25 / 0 | 35 | 2.774 |
| Three slots, 75% reuse, 1 GiB/s link | 18 / 60 | 42 / 0 | 1 | 0.072 |
More slots admit more work while accumulating a compute queue; this server has no batching speedup to repay it. Six configured slots cannot all be occupied under the memory ledger: ordinary requests need about 4.516 GiB each, so only five fit. Longer prompts hit both memory and the first-token floor. Reuse improves goodput on the fast link, but on the slow link its transfer queue makes it worse than cold computation. The example deliberately imports reused state; a production scheduler should compare that choice with recomputation before dispatch.
Worked check: should the one-slot policy ship because it beats three slots? No: it rejects two thirds of offered requests. All six configurations need an explicit acceptable rejection rate as well as latency and quality gates. The script teaches why capacity, completed throughput, SLO goodput and offered-workload success are different quantities.
For a real experiment, replace the constant rates with measured shape- and batch-dependent service distributions; include bursty arrivals, cache misses and invalidation, transfer overlap, cancellation, and retries. Record engine revision, hardware, parallelism, warmup and cold-start policy. Replay the same workload against cold recomputation and cache reuse, and validate outputs separately. The simulation and its tests establish event bookkeeping only; they establish no GPU speedup or production capacity.
From simulation to a measured GPU serving run¶
The repository now includes examples/benchmarks/gpu_serving.py, a standard-library HTTP client for an isolated NVIDIA serving host. Its default experiment sends 120 deterministic synthetic text prompts through four closed-loop workers, repeated three times after eight warmup requests. Each worker waits for its preceding response before submitting another. This tests achieved throughput at fixed client concurrency, not an independent arrival rate or open-loop overload. Prompts contain 256 sampled words plus an instruction; they are not fixed-length token sequences. Generation stops naturally or at 128 output tokens, and actual token counts are retained.
The companion docs/gpu-serving-benchmark.md provides the setup and evidence checklist. Pin the model and tokenizer to immutable revisions, record the exact engine build and resolved server configuration, and disable prefix caching for this baseline. The runner records the local NVIDIA inventory, workload and harness hashes, request outcomes and separate repeat summaries. Operator-supplied configuration still needs to be checked against the server startup log; a device inventory alone does not establish which GPU executed a request.
Completion throughput and successful output-token throughput use the entire repeat wall time, including failures and final drain. Successful-response latency percentiles are labeled as such; HTTP errors, timeouts and invalid responses remain in the attempted-request denominator. The declared five-second completion threshold produces latency-qualified throughput, not quality-qualified goodput. Model loading and warmup are excluded. Non-streaming HTTP responses cannot establish first-token latency or inter-token gaps, and the socket-inactivity timeout is not an end-to-end deadline. With only 120 requests per repeat, the p99 estimate also has very little tail evidence.
Evidence status: this harness has CPU contract tests, but no measured GPU run is recorded for this addition. The development host has no NVIDIA runtime. Do not fill a performance table from the simulation, a dry-run plan or passing client tests. Publish hardware results only with the raw request records, server configuration and logs, model revisions, failures and repeated-run variation. Quality, cold-start readiness and streaming latency remain separate acceptance checks.
Long-context memory is becoming hierarchical¶
Recent work explores two complementary ways to reduce long-context pressure. RocketKV, version 1, combines coarse eviction with fine-grained sparse attention and reports up to 3 times end-to-end decode speedup and up to 31 percent peak-memory reduction on H100 against a full-KV-cache baseline, with negligible loss on its evaluated tasks. These numbers belong to the February 2025 version; later revisions report a different hardware evaluation. SparseServe places unselected KV state in host memory, controls batch size from the active working set, and segments prefill by layer; it reports up to a 9.26-fold reduction in mean time to first token and up to 3.14 times higher generation throughput than its evaluated baselines. These maxima need not occur in the same configuration.
These are paper-reported maxima, not portable constants. They do establish a broader systems pattern: when attention becomes sparse, the bottleneck can move from HBM bandwidth to HBM capacity, irregular selection, or host-device movement. A valid comparison must include retrieval quality, task accuracy, selection overhead, cache thrashing, tail latency, and worst-case dense fallbacks.
Design Exercises¶
- Build an end-to-end benchmark that could reject a FlashAttention-4 deployment despite a faster kernel.
- Derive the break-even condition for moving KV between prefill and decode workers.
- How would admission control change when host memory is a KV backing tier?
- Compare KV eviction, sparse attention, quantization, and offload as long-context policies.
- A cache reports 890 bytes per token. What must be established before using it for fleet admission?
- Why might a speculative tree with a longer accepted prefix reduce throughput?
Worked Solutions¶
- Include production sequence and head shapes, padding, causal masks, graph capture, competing kernels, full-layer time, accuracy drift, memory, compile cost, and tail latency. Reject it if layout conversion or unsupported shapes erase the kernel gain.
- Disaggregation wins when saved queueing and improved phase utilization exceed transfer, synchronization, retry, and additional network-tail cost while KV fits within the destination's admission reserve.
- Admit from predicted active working set and transfer bandwidth, not nominal host capacity. Reserve headroom, bound concurrent promotions, detect thrashing, and reject or degrade before latency collapses.
- Eviction removes state and risks quality; sparse attention retains or tiers state but pays selection cost; quantization reduces bytes with numerical risk; offload preserves values but adds transfer latency. Hybrids should be evaluated against a full-attention quality and latency baseline.
- Establish exactly which state the figure includes, then add weights, local or recurrent state, replay workspace, scales, temporary buffers, concurrency, and reserve. Measure cache-hit reconstruction work and transfer tails rather than treating a component footprint as total service memory.
- More candidate nodes can increase verification, draft, and rollback costs faster than useful committed tokens. Compare committed tokens per complete round and fleet goodput under concurrency, not accepted length alone.