Efficiency Optimization for Long-Context LLM Agents: KV Cache, Attention, MoE, Context Budgeting, and Model Evaluation
This article explains how to judge and improve the efficiency of large language models in long-context agent workloads. It covers KV cache size estimation, sparse, compressed, and sliding-window attention, the gap between total and active parameters in mixture-of-experts models, context budgeting for agents, and a workflow for evaluating a newly released model.
1. Moving from Parameter Count to Efficiency Metrics
For years, people judged a large model by its total parameter count and its benchmark scores. Developers and enterprise teams that deploy models need to answer three more questions. Can the GPU memory handle long inputs? Is the end-to-end time for a single task acceptable? Can inference costs stay under control at the same quality level?
Much of the recent work on model iterations focuses on reducing these three costs. Understanding how these improvements work is more useful than memorizing a version number.
2. The Core Bottleneck in Long Context: KV Cache
During autoregressive generation, the model stores a Key vector and a Value vector for every layer each time it processes a token. This data is called the KV cache. Its size grows in proportion to the context length, so longer inputs use more GPU memory.
You can estimate the KV cache size per token with this formula:
Bytes per token = 2 × number of layers × number of KV heads × head dimension × bytes per element
The factor of 2 accounts for storing both K and V. When grouped-query attention is used, the number of KV heads is much smaller than the number of query heads, which substantially reduces the cache size.
def kv_cache_bytes_per_token(num_layers, num_kv_heads, head_dim, bytes_per_elem=2):# K and V are each stored once, so multiply by 2return 2 * num_layers * num_kv_heads * head_dim * bytes_per_elem# The following parameters are for illustration only and do not reflect the configuration of any specific modelcfg = dict(num_layers=60, num_kv_heads=8, head_dim=128, bytes_per_elem=2)per_token = kv_cache_bytes_per_token(**cfg)context_len = 128_000total_gib = per_token * context_len / 1024**3print(f"About {per_token / 1024:.1f} KiB per token, about {total_gib:.2f} GiB for a 128K context")
With these example parameters, each token uses about 240 KiB, and a 128K context uses about 29.3 GiB. This figure does not include the model weights or intermediate activations. When the cache grows too large, the server can handle fewer concurrent requests. Throughput drops, and the cost per unit of work rises.
There are three main ways to reduce the cost of long context:
- Reduce the cache size per token, for example by using fewer KV heads, or by applying low-rank compression or quantization to the cache.
- Reduce the number of tokens that take part in full attention computation, for example with sparse attention or sliding windows.
- Reuse the cache for prefixes that were already computed, so the same content is not processed repeatedly.
3. Attention Design Approaches
3.1 Sparse Attention
Standard attention lets each query compare against every previous token. Sparse attention limits each query to a subset of positions, such as a nearby window, positions at fixed intervals, or candidate blocks selected by content. This reduces the amount of computation, but you need to verify that key information is not dropped.
3.2 Compressed Attention
Compressed attention merges several adjacent tokens into one block representation, and attention runs at the block level. This leaves fewer cache entries, but the model keeps less fine-grained information. The actual effect depends on the compression method and the task. For example, step-by-step reasoning and precise extraction respond differently to compression.
3.3 Sliding Windows and Global Tokens
Some layers attend only to a recent window, while a small number of global tokens keep a summary of the full text. This design is simple to implement and works well for data with strong local structure, such as logs.
3.4 KV Cache Quantization
Reducing the cache from 16-bit floating point to 8-bit or lower precision directly reduces GPU memory use. Quantization error can accumulate over long-range dependencies, so you should measure accuracy changes on your target tasks instead of relying only on general benchmarks.
4. Mixture-of-Experts: Look at Total and Active Parameters Separately
A mixture-of-experts (MoE) model contains several expert sub-networks, and each token activates only a few of them. The total parameter count and the compute per token are therefore two different numbers.
import numpy as npdef topk_route(x, w_gate, k=2):"""Select the top-k experts based on gate scores, and normalize their weights with softmax."""logits = x @ w_gate # one score per expertidx = np.argsort(logits)[-k:] # take the k highest scoresweights = np.exp(logits[idx])weights = weights / weights.sum()return idx, weightsrng = np.random.default_rng(0)x = rng.normal(size=16) # hidden vector of a single tokenw_gate = rng.normal(size=(16, 8)) # 8 expertsexperts, probs = topk_route(x, w_gate, k=2)print("Active experts:", experts, "weights:", probs.round(3))
Keep these points in mind when you use MoE:
- GPU memory must hold the weights of all experts, even though each token activates only some of them.
- Compute cost depends mainly on the active experts, so inference is usually faster than a dense model with the same total parameter count.
- Routing can become unbalanced, with some experts overused. Auxiliary losses or capacity limits help balance the load.
- In multi-GPU deployments, spreading experts across devices adds communication overhead. This is often one of the main sources of real-world latency.
5. Conditional Memory: Decoupling Knowledge Storage from Computation
Conditional memory refers to a class of mechanisms in which the model looks up information in an external or parameterized memory table, based on the context. The core idea is that the model’s knowledge capacity can grow by enlarging the memory table, without a proportional increase in the compute per token.
In theory, this decoupling lets model capacity grow separately from inference cost. In practice, the results depend on several factors:
- Memory access cost. If the memory table does not fit in fast cache, latency rises noticeably.
- Quality of the lookup key. Incorrect retrieval can inject unrelated information into the hidden state.
- Training stability. Memory slots need enough data to learn meaningful content.
The following simplified sketch shows the structure:
def conditional_memory_layer(h, memory_table, key_proj):"""Illustrative sketch: generate a query key from the hidden state, retrieve memory, and merge it back into the hidden state."""key = key_proj(h)slot = nearest_slot(key, memory_table) # assumes a nearest-neighbor lookup is already implementedreturn h + memory_table[slot]
When you evaluate modules like this, do not look only at parameter count. Also measure lookup latency, retrieval hit rate, and changes in downstream task performance.
6. Context Engineering for Agents
Agent tasks often require large inputs, such as an entire code repository, a full set of runtime logs, or a technical manual. Putting all of this content into the context creates three problems. Each call is expensive, repeated calls multiply the cost, and irrelevant content dilutes the model’s attention.
There are three common strategies:
| Strategy | Best for | Main trade-off |
|---|---|---|
| Full injection | Manageable content size that needs global understanding | High cost and latency |
| Retrieval-augmented | Questions that relate to local fragments | Depends on retrieval quality |
| Hierarchical summarization | Tasks that need an overview before details | Summaries may lose detail |
The basic cost formula is:
Cost per call = input tokens × input price + output tokens × output price
Agents usually make several calls, so the total cost is the per-call cost multiplied by the number of calls. Placing stable content, such as system instructions and manual text, at the start of the prompt helps prefix caching work, which reduces repeated computation.
Here is a simple budget function that loads context by relevance:
def build_context(chunks, budget, count_tokens):"""Greedily add chunks from highest to lowest relevance until the token budget is reached."""picked, used = [], 0for chunk in sorted(chunks, key=lambda c: c["score"], reverse=True):n = count_tokens(chunk["text"])if used + n > budget:continuepicked.append(chunk)used += nreturn picked, used
The output of this function depends on the quality of score. In real projects, relevance scores can come from vector retrieval, keyword matching, or the reranking results of the model itself.
7. How to Evaluate a Newly Released Model
Version numbers and release notes only describe what changed in the model. They do not tell you directly whether the model fits your use case. Use the following workflow for evaluation:
- Build your own evaluation set. Collect dozens to hundreds of samples from your real workload. Include inputs, expected outputs, and scoring criteria. General leaderboards are only a reference.
- Record quality, latency, and cost together. Looking at accuracy alone can hide response time and expense, so compare all three side by side.
- Separate retrieval ability from reasoning ability. A “needle in a haystack” test on long text shows only whether the model can locate information. Cross-paragraph reasoning and synthesis across multiple pieces of information require separate test cases.
- Test agent execution. Track the success rate of tool calls, the accuracy of parameters, recovery after failures, and the number of steps needed to complete a task.
- Check reproducibility. Fix the sampling parameters, run the tests repeatedly, and observe the variance in results.
A basic evaluation framework looks like this:
import timeresults = []for case in dataset:start = time.time()output = run_model(case["prompt"]) # call the model under evaluationlatency = time.time() - startresults.append({"id": case["id"],"correct": grade(output, case["expected"]),"latency_s": latency,"cost": estimate_cost(case, output),})
With a consistent results table, you can group and compare outcomes by task type. This shows which scenarios the new model actually improves and which ones show no change.
