Deploying Ultra-Long-Context LLMs: KV Cache, Sparse Attention, and Prefill–Decode Practice
When context windows reach the million-token range, serving limits shift from parameter count to KV-cache size, attention cost, and request scheduling. This article explains how FP8 KV caches, sparse attention with low-precision index caches, expert and data parallelism, graph compilation, prefill–decode separation, and multi-level reasoning effort address memory, latency, and throughput, and outlines a practical rollout order.
1. Background: Ultra-Long Context Changes the Serving Baseline
When a model’s context window grows to the million-token scale, deployment complexity is no longer driven mainly by parameter count. The bottleneck becomes the explosive growth of state size. Autoregressive inference must keep a full KV cache for every request, and that cache scales with context length, layer count, and the number of attention heads. For a model with dozens of layers and a multi-head structure, a single request at full context can occupy tens of gigabytes of GPU memory for KV cache alone. That directly implies:
- Limited concurrency. Once KV cache consumes most of the memory, the number of requests that can be served at once drops sharply.
- Higher time to first token. Prefill over a long input is compute-heavy, so users wait longer before the first token appears.
- Coarser scheduling. Large memory allocations and frees fragment the allocator and lower overall utilization.
The core approach for ultra-long-context serving can be stated in one line: shrink the KV cache, sparsify attention, and run prefill and decode separately.
2. Lower-Precision KV Cache: The Most Direct Memory Win
A common industry practice is to compress the KV cache from FP16/BF16 to FP8. That saves close to half of the cache memory, and accuracy loss is usually acceptable in long-context settings. Three points matter in production:
- Hardware support. FP8 compute depends on newer GPU instruction sets. Older hardware can only quantize for storage, so the benefit is smaller.
- Aligned compute and storage paths. If attention still runs in high precision, frequent dequantization eats part of the savings. Quantized cache should participate in the core computation whenever possible.
- Hard constraints on block size. A large block (for example, on the order of 256) cuts memory-management metadata overhead and raises copy and transfer throughput, but both the memory allocator and the attention kernel must support that granularity. This is not a free tuning knob; it is a value bound to the kernel implementation.
An illustrative configuration looks like this (use the parameters defined by your inference framework’s documentation):
kv_cache:dtype: fp8block_size: 256attention:fp4_indexer_cache: true # low-precision switch for the sparse-attention index cacheparallel:expert_parallel: enableddata_parallel_size: 4
3. Sparse Attention and Index Caches: A Second Compression Layer
In ultra-long-context inference, attention is O(n²). Quantization alone does not remove the compute bottleneck. Modern designs commonly add sparse attention / index-based retrieval: a lightweight indexer decides which KV blocks are relevant to the current query, and full attention runs only on those blocks.
The indexer itself has a cache cost, which is why designs such as an FP4-level index cache appear. They store intermediate index results at even lower precision and cut memory further with little effect on recall quality. At million-token context, the gains multiply: a smaller index cache and fewer blocks that actually run attention.
4. Parallelism: Combining Expert Parallelism and Data Parallelism
Mixture-of-experts (MoE) models usually need two forms of parallelism together:
- Expert parallelism (EP). Different experts live on different GPUs so expert weights are not replicated on every card. With a capacity factor and load balancing, this can sharply reduce per-GPU memory pressure.
- Data parallelism (DP). Multiple copies of the same model each handle requests independently to raise throughput. On a single multi-GPU machine, the DP size is often equal to the GPU count; at larger scale, tensor parallelism is added.
A practical rule is: set the minimum expert-parallel size first, then use the remaining GPUs for data parallelism to scale throughput. Blindly increasing tensor parallelism on MoE models can hurt efficiency because of all-to-all communication.
5. Operator-Graph Compilation: Stabilizing Kernel Scheduling
Each long-context decode step runs many small operators. Default just-in-time compilation can introduce unpredictable scheduling jitter. Graph capture, with full-graph or mixed full-graph and piecewise compilation, freezes the decode step into an efficient execution graph. Custom operators can also turn off unnecessary generic fallback paths. The benefits include:
- Lower per-step decode latency
- Less CPU-side scheduling overhead
- More stable performance across batches, which makes capacity planning easier
Watch compatibility with dynamic shapes. When context lengths vary widely, use a piecewise strategy and capture full graphs only for regions whose shapes stay stable.
6. Separating Prefill and Decode: Trading Architecture for Latency
Under long context, prefill (highly parallel compute) and decode (serial and bandwidth-bound) have very different resource profiles. Placing them on different GPU groups—a prefill–decode (PD) disaggregated architecture—lets each side be tuned on its own:
- Prefill nodes focus on high-throughput batched matrix work and can use higher parallelism.
- Decode nodes focus on low-latency token-by-token generation and on using memory bandwidth well.
- KV transfer. After prefill, the KV cache must move from the prefill side to the decode side. RDMA-based transfer components are typically used to bypass host memory and cut copy latency.
- Routing. An entry router that understands PD separation forwards each request to the right nodes by stage and balances load with strategies such as round-robin.
PD separation can also stay inside one machine (for example, four GPUs for prefill and four for decode), which suits memory-rich, latency-sensitive setups. When scaling across nodes, check that network bandwidth matches KV-migration traffic; otherwise the router becomes the new bottleneck.
7. Dynamic Reasoning Effort: Let the Task Decide How Long the Model Thinks
For agents and complex reasoning, APIs increasingly expose several levels of reasoning effort. A typical split is:
- Non-thinking mode. Generate the answer directly, with the lowest latency. Suited to classification, extraction, and simple Q&A.
- Medium thinking. Produce a moderate reasoning trace before the answer, balancing quality and cost.
- Deep thinking. Allow a longer internal reasoning chain for math, code, and complex planning.
From a serving perspective, capacity plans must account for very different output-token distributions. A deep-thinking request may spend several times as long in decode as an ordinary request, so queuing and timeouts need to be finer-grained so long requests do not crowd out the queue.
8. Rollout Checklist and Capacity Planning
When combining these techniques into a deployable plan, a sensible order is:
- Fix context and concurrency targets. Clarify typical input and output length distributions and the target concurrency, then back out KV-cache memory demand.
- Enable FP8 KV cache and pin the block size. This is usually the highest return for the effort.
- Turn on sparse-attention indexing and a low-precision index cache. Check that quality metrics on long-text tasks do not regress meaningfully.
- Configure expert parallelism plus data parallelism. Solve for the smallest parallel footprint under the per-GPU memory limit.
- Enable graph compilation and load-test. Compare latency percentiles and throughput before and after compilation.
- Add PD separation only if needed. Make the architectural change when latency or throughput still misses the target.
- Add monitoring. Track KV-cache hit rate, memory fragmentation, prefill and decode time distributions, and queue wait time.
On cloud infrastructure, general GPU container scheduling, autoscaling, and monitoring and alerting—capabilities offered by platforms such as Baidu AI Cloud—can reduce the cost of running your own infrastructure while you keep full control of model-serving details.
9. Summary
Deploying ultra-long-context models is no longer “fit the weights into GPU memory.” It is a systems problem around KV-cache volume, attention compute, parallelism, and request scheduling. FP8 KV cache and FP4 index cache address memory; sparse attention and graph compilation address compute and scheduling; PD separation and multi-level reasoning effort address latency and cost. Understanding the resource trade-off behind each optimization matters more than memorizing any single parameter. That is the line between “it runs” and “it runs steadily and economically.”
