Deploying Long-Context LLMs: Estimate First, Then Choose a Solution
Deploying ultra-long context Large Language Models (LLMs) faces three main bottlenecks: quadratic attention computation growth, KV cache exhausting VRAM, and reading the full historical cache for every generated token. Sparse attention, cross-layer index reuse, speculative decoding, and inference service optimizations each target specific bottlenecks. The actual performance gains depend on the task, model, and hardware. This article provides formulas to estimate compute and memory bottlenecks, code examples for sparse attention and index reuse, and comprehensive evaluation guidelines for inference services and agent training to help you choose the right optimization strategy.
Conclusion First
Deploying ultra-long context faces three main bottlenecks: attention computation grows quadratically with sequence length, the KV cache exhausts VRAM, and the entire historical cache must be read from VRAM for each generated token. Sparse attention, cross-layer index reuse, speculative decoding, and inference service optimizations each target one or two of these bottlenecks. The actual yield depends on the task, model, and hardware. You should first use the formulas below to estimate the bottleneck location, and then confirm with your own data measurements.
1. Problem and VRAM/Compute Estimation
During the prefill phase, standard attention computes two matrix multiplications: QK^T and AV. Calculated per layer, the attention computation for a sequence of length s in a model with n_layers is approximately:
Attention FLOPs ≈ 4 × n_layers × s² × d_model
Here, FLOPs count both a multiplication and an addition as one operation each. If counted as Multiply-Accumulate operations (MACs), the result is half of the above, i.e., 2 × n_layers × s² × d_model. This article consistently uses FLOPs. This formula does not account for the causal mask. The causal mask only requires computing the lower triangle, so the actual computation is roughly half of this value, making the formula result conservative. d_model refers to the total dimension of the query heads; when using GQA or MQA, reducing KV heads does not decrease this computation.
Taking an 80-layer model, d_model of 8192, and s of 1 million as an example, the formula yields about 2.6 × 10^18 FLOPs, and approximately 1.3 × 10^18 considering the causal mask. Assuming a GPU with a peak performance of about 1000 TFLOPS, the theoretical lower limit is about 1300 seconds, or roughly 22 minutes. Actual utilization is usually far below peak, so the real time will be longer.
During the decode phase, the KV cache is the primary VRAM consumer:
KV cache bytes = 2 × n_layers × batch × s × kv_heads × head_dim × bytes_per_element
The coefficient 2 represents the two caches for K and V. Taking 80 layers, 8 KV heads, head_dim of 128, bf16 (2 bytes per element), and a single sequence of 1 million tokens, we get:
2 × 80 × 1 × 1,000,000 × 8 × 128 × 2 ≈ 3.28 × 10^11 bytes
In decimal terms, this is about 328 GB; in binary, about 305 GiB. This number does not include VRAM fragmentation, alignment padding, and the inference framework’s own cache, so actual usage will be higher. 328 GB already exceeds the VRAM of most single GPUs, so million-level context usually requires multi-GPU sharding, KV quantization, or reducing the retained history.
During full attention decoding, the entire cache must be read for each generated token. Assuming all 328 GB is located on a single GPU with a bandwidth of 3 TB/s, the lower limit for a single step read time is about 0.11 seconds (328 ÷ 3000 ≈ 0.109 seconds). This number is only used to judge the order of magnitude. After multi-GPU sharding, each GPU only reads its own portion, and the specific latency needs to be recalculated based on the sharding method.
2. Dynamic Sparse Attention
The core assumption of sparse attention is that for a given query, only a few historical positions actually contribute. The method consists of two steps. First, a lightweight indexer scores each historical position. Second, exact attention is computed only on the top_k positions with the highest scores.
Runtime environment: Python 3.9 and above, PyTorch 2.0 and above. The following code illustrates a single KV head, where q has the shape [d], and k_cache and v_cache have the shape [seq, d].
import torchimport torch.nn.functional as Fclass LightIndexer(torch.nn.Module):"""Scores historical positions using low-dimensional projection. d_idx should be significantly smaller than d."""def __init__(self, d, d_idx):super().__init__()self.wq = torch.nn.Linear(d, d_idx, bias=False)self.wk = torch.nn.Linear(d, d_idx, bias=False)def forward(self, q, k_cache):# q: [d], k_cache: [seq, d] -> scores: [seq]return self.wk(k_cache) @ self.wq(q)def attend_selected(q, k_cache, v_cache, idx):d = q.shape[-1]k_sel, v_sel = k_cache[idx], v_cache[idx] # [top_k, d]attn = F.softmax(k_sel @ q / d ** 0.5, dim=-1) # [top_k]return attn @ v_sel # [d]def sparse_attention_decode(q, k_cache, v_cache, indexer, top_k):scores = indexer(q, k_cache) # [seq]k = min(top_k, scores.numel())idx = torch.topk(scores, k=k).indices # [top_k]return attend_selected(q, k_cache, v_cache, idx)
When calling the example, the indexer’s weights need to be trained or distilled beforehand. Top_k results from randomly initialized weights are meaningless.
Regarding complexity, the indexer is roughly O(seq × d_idx), and exact attention is roughly O(top_k × d). When top_k is fixed, the exact attention part does not grow with sequence length, but the indexing part still grows linearly with the sequence. Therefore, sparse attention reduces the coefficients of read volume and computation, but does not make the complexity independent of sequence length. If d_idx approaches d, the indexing overhead will approach that of full attention, and the benefits will disappear.
Applicable conditions:
- Tasks where the required information is concentrated in a few positions, such as retrieval QA, code localization, and keyword search scenarios.
- The indexer can recall the positions with the highest weights in full attention on the target data. Recall rate should be determined by measurement.
top_kandd_idxmake the total overhead of indexing and exact attention significantly lower than full attention’s seq × d.
Not applicable conditions:
- Tasks requiring aggregation of full-text information, such as full-text summarization and large-scale statistics.
- Scenarios that must exactly reproduce the output of full attention.
Sparse attention and FlashAttention solve different problems. FlashAttention reduces memory reads and writes for full attention but still computes all positions. Whether the two can be combined depends on the specific inference framework implementation.
3. Grouped Index Reuse
Running an indexer for every layer results in significant cumulative overhead when there are many layers. Adjacent layers usually have similar focus on historical positions, so continuous layers can be grouped. Only the first layer in the group computes the index, and the rest directly reuse the positions of the first layer. Taking a group size of 4 layers as an example:
GROUP_SIZE = 4def forward_layers(hidden, layers, caches, top_k):"""hidden: [d], the hidden state of the current token (residual and feedforward network omitted to highlight index reuse logic)layers: each layer needs to provide q_proj and indexer attributescaches: (k_cache, v_cache) for each layer, both of shape [seq, d]"""shared_idx = Nonefor i, layer in enumerate(layers):k_cache, v_cache = caches[i]q = layer.q_proj(hidden)if i % GROUP_SIZE == 0: # Group first layer: compute indexscores = layer.indexer(q, k_cache)k = min(top_k, scores.numel())shared_idx = torch.topk(scores, k=k).indices# Other layers in group: reuse shared_idxhidden = attend_selected(q, k_cache, v_cache, shared_idx)return hidden
This code requires all layers to cache the same batch of token positions. If some layers perform different eviction or paging, the position indices will be misaligned and must be aligned first.
The risk of grouping lies in the difference in focus positions among layers within the group. The larger the difference, the greater the recall loss caused by index reuse. The group size should be determined based on inter-layer index similarity, and the recall rate of each group should be measured on your own model. You cannot directly apply a 4-layer grouping. This solution is suitable for models with similar inter-layer attention patterns, many layers, and high indexing overhead. When the attention patterns differ greatly across layers, or the model has fewer layers, the benefits are limited.
4. Multi-Token Prediction and Speculative Decoding
Multi-Token Prediction (MTP) allows the model to predict multiple subsequent tokens in a single forward pass, usually by appending several lightweight prediction heads. Speculative decoding uses a small draft model to first propose k tokens, and then the target LLM verifies them in one pass. Both have the same purpose: to make one LLM forward pass produce multiple candidates, rather than just one token.
The verification process is as follows. The draft model generates k candidate tokens. The target model computes probabilities for these k positions in parallel. It judges them one by one from front to back, accepting candidates with probability min(1, p_target / p_draft). When the first rejected position is encountered, all subsequent candidates are discarded, and a token is sampled from the corrected distribution. When this rejection sampling rule is used, the output distribution is consistent with the target model decoding alone. Under greedy decoding, the output is exactly the same character by character.
The speedup can be roughly estimated. Let the average acceptance rate of a single token be α, assume each position is independent, and let the draft length be k. Then the average number of tokens produced per target model forward pass is approximately:
(1 − α^(k+1)) / (1 − α)
When α is 0.8 and k is 4, it is about 3.36 tokens. This number ignores the overhead of the draft model and the extra computation for verification. The draft model must run every step; if its cost accounts for a high proportion of the target model’s forward pass, the benefits will be offset.
The main factors affecting the acceptance rate include:
- Temperature: As the sampling temperature increases, the difference between the draft distribution and the target distribution becomes more apparent, and the acceptance rate usually drops.
- Batch size: As the batch size increases, decoding gradually shifts from a memory-bound bottleneck to a compute-bound one. Verifying
kcandidates requires extra computation, which offsets the benefits under large batches. - Long context: The draft model also needs to read its own KV cache. If the draft model uses full attention, it will also be slow on a million tokens. A draft model that supports sparse attention or sliding windows should be used.
- Task distribution: If the draft model is trained on code data, its acceptance rate may drop significantly on conversational data.
The fallback strategy is to continuously monitor the acceptance rate within a sliding window. When the acceptance rate falls below a threshold, set k to 0, degrading to normal decoding. The threshold should be determined by your own measurement results and should not be a fixed value.
5. Inference Service and Agent Training Evaluation
The goal of evaluation is to confirm that the solution is actually effective for your tasks and hardware, and that the quality has not degraded significantly.
The core metrics of the inference service are as follows:
- Time To First Token (TTFT): Mainly reflects the prefill time.
- Time Per Output Token (TPOT): Reflects the memory access and computation efficiency during the decode phase.
- Throughput (tokens/s): Needs to be reported separately by concurrency level.
- Peak VRAM: Includes KV cache and the framework’s own usage.
- Acceptance rate: Only tracked when using speculative decoding.
It is recommended to follow these steps for evaluation:
- Fix the baseline. Use full attention as the baseline, running on the same hardware, with the same batch size and the same input length distribution.
- Construct a hierarchical dataset. Input lengths should cover at least short, medium, and long tiers, with sufficient samples for each tier.
- Collect statistics. Report the mean, as well as P50 and P95. Each set of experiments should be repeated at least 3 times to record variance.
- Check output quality. Use long-context retrieval tasks (embedding specific information in long text and then requiring the model to answer), as well as QA accuracy based on your own data. Also count the consistency rate with the baseline output.
- Run regression tests. Run a fixed set of test cases before going live to compare output differences and failure rates.
Evaluation for agent training focuses on stability over long trajectories. The following metrics need attention:
- Task success rate and average steps.
- Tool calling format error rate.
- Token cost per task.
- Information loss caused by context truncation or summarization.
Each configuration should be repeated with multiple random seeds, and confidence intervals reported. Whether the success rate drops synchronously as the trajectory lengthens is direct evidence of whether sparse attention or grouped reuse damages long-range reasoning capabilities.
Pre-launch checklist:
- The bottleneck estimated by formulas is consistent with the measured bottleneck.
- The recall rate of the sparse index meets your own set standards.
- The acceptance rate of speculative decoding is above the fallback threshold under target traffic.
- The degradation of quality metrics compared to the baseline is within an acceptable range.
- There is a margin in peak VRAM, and fragmentation and framework overhead have been accounted for.
