Long-Context Inference Is Too Expensive: Three Cost-Cutting Paths in Next-Generation Architectures

    Long-context AI agents can require hundreds of thousands or even millions of tokens, making prefill latency and KV cache capacity major deployment bottlenecks. This article explains where the costs come from and examines three architectural strategies for reducing them: asymmetric computation, cross-layer KV reuse with low-precision quantization, and decoupling knowledge storage from core computation. It also covers model selection, inference deployment, context management, and common evaluation pitfalls.

    1. Where Long-Context Inference Costs Come From

    AI agent workloads are pushing context windows toward hundreds of thousands or even millions of tokens. A complex software engineering task may involve hundreds of tool calls, extensive terminal output, and an entire code repository. Deep research, graphical user interface automation, and enterprise workflows similarly require models to retain long interaction histories.

    The longer the context, the higher the inference cost. This becomes especially visible during deployment.

    Traditional decoder-only Transformers face two major costs in long-context scenarios.

    Prefill computation

    Assume a model has (L) layers, an input prompt length of (N), and a hidden dimension of (d). Each layer contains two main types of computation:

    • Linear layers, including the Q, K, and V projections, output projection, and feed-forward network, with cost proportional to (N \cdot d^2);
    • Attention score computation, with cost proportional to (N^2 \cdot d).

    The total prefill computation can therefore be approximated as:

    [
    O(L \cdot (N \cdot d^2 + N^2 \cdot d))
    ]

    When (N) is relatively small, the linear layers dominate. Once (N) reaches hundreds of thousands of tokens, the attention component grows much faster, causing time to first token (TTFT) to rise sharply.

    FlashAttention and similar optimizations mainly reduce memory traffic. They do not change the computational complexity of attention.

    KV cache memory

    During decoding, the model must store the Key and Value states for every layer. The approximate number of bytes required per token is:

    [
    \text{KV bytes per token} \approx 2 \times \text{number of layers} \times \text{number of KV heads} \times \text{head dimension} \times \text{bytes per element}
    ]

    Consider a hypothetical configuration with 60 layers, 8 KV heads, a head dimension of 128, and FP16 storage, where each element uses 2 bytes. The result is approximately 245,760 bytes per token, or about 240 KB.

    At a context length of one million tokens, the KV cache for a single request would approach 246 GB, far beyond the memory capacity of many individual GPUs. This is only an illustrative calculation. Actual usage depends on the model architecture and precision configuration.

    In high-concurrency inference clusters, KV cache capacity often becomes a bottleneck before model weights do. Multi-turn conversations can also introduce additional costs from moving cache data to host memory, writing it to disk, and transferring it over the network.

    Overall, next-generation efficient architectures are pursuing several related directions:

    1. Reduce the size of each KV entry;
    2. Reduce the number of historical positions that participate in attention;
    3. Eliminate duplicated cache storage across layers;
    4. Shorten the computation path that must be fully executed during prefill.

    The following sections describe representative approaches.

    2. When Prefill Is Too Slow: Asymmetric Computation

    Mixture-of-Experts (MoE) models reduce per-token decoding computation through sparse activation. However, during prefill, the entire sequence still passes through dense computation across the model layers.

    A useful observation is that prompt tokens and generated tokens do not necessarily require the same computational depth. Prompt tokens are primarily being processed and understood, while generated tokens require a more complete computation path.

    Based on this idea, some research has proposed asymmetric architectures referred to here as causal encoder-decoder structures. The basic approach is to let most prompt tokens pass through only the first portion of the network during prefill, while preserving the full decoding path.

    Terminology is not consistent across different sources, so implementation decisions should be based on the specific paper or model documentation.

    Estimating the potential benefit

    Consider a hypothetical MoE model that activates approximately 16B parameters for each decoding token. If prompt tokens pass through only half of the layers during prefill, the activated parameter count might fall to approximately 8B.

    The computation required by the linear layers would then be roughly halved. However, the attention component would still depend on (N^2), and its cost would also vary with the number of layers used during prefill.

    As a result, the overall prefill benefit depends on the relative share of linear and attention computation in the total runtime:

    • For shorter sequences, the gain may approach a 50% reduction;
    • For very long sequences, attention represents a larger share of runtime, so the actual improvement will be smaller.

    These figures illustrate the estimation method only. They are not benchmark results for any published model.

    Because the decoding path remains complete, this design does not necessarily sacrifice generation quality. It does, however, impose additional training requirements. The first and second halves of the network must learn a useful division of labor during training. Otherwise, shallow representations produced during prefill may reduce the accuracy of later attention retrieval.

    For this reason, such architectures generally need to be introduced during pretraining rather than applied as direct pruning after training is complete.

    For enterprises and developers, two metrics are particularly important:

    • TTFT under long-prompt workloads;
    • Quality stability on long-context retrieval tasks.

    3. When the KV Cache Is Too Large: Cross-Layer Reuse and Low-Precision Quantization

    KV cache optimization can be considered along two independent dimensions:

    1. Reduce the number of cache entries;
    2. Reduce the size of each retained entry.

    Cross-layer reuse: reducing duplicated cache

    In a conventional architecture, every layer independently computes and stores its own KV states and attention indexes. The top-K attention positions selected by neighboring layers are often highly overlapping, and intermediate results from index computation may also be duplicated.

    Cross-layer reuse allows multiple layers to share a primary KV cache, index vectors, or Top-K selection results.

    Comparison dimension Independent KV storage per layer Shared KV across layers
    Number of cache entries Proportional to the number of layers Reduced according to the sharing groups
    Memory usage Higher Significantly lower
    Repeated index computation Performed independently by each layer Can be reused
    Diversity of deep representations Fully preserved Must be protected; some independent layers are often retained
    Quality risk Lower Depends on the sharing scope and training method
    Implementation complexity Low; standard implementations are usually sufficient High; model-specific kernels are often required

    In practice, a common compromise is to retain a small number of independent layers while allowing most layers to share cache. This balances memory savings against representational capacity.

    Low-precision quantization: reducing the size of each entry

    After reducing the number of entries through reuse, the remaining KV cache can also be quantized. For example, KV states may be compressed from FP16 or INT8 to FP4, together with group-wise scaling factors.

    In theory, FP4 requires one quarter of the storage used by FP16. In practice, group scaling factors add overhead, so the actual compression ratio is slightly lower than the ideal ratio.

    Quantization also introduces risks. Attention retrieval can be sensitive to numerical errors in Key states. Common strategies include:

    • Applying more aggressive quantization to Value states;
    • Retaining slightly higher precision for Key states;
    • Keeping full-precision copies of important anchor tokens.

    Bit width should be selected based on evaluation rather than compression ratio alone. At minimum, testing should include:

    • Perplexity comparisons;
    • Long-context retrieval tests, such as locating specific information in a long document;
    • Regression tests for downstream tasks.

    Technical documentation sometimes reports a specific KV byte count for a model. Before using such figures for comparison, verify the model name, context length, precision configuration, and measurement methodology. Otherwise, the numbers may not be directly comparable.

    4. Can Knowledge Be Externalized? Decoupling Computation from Knowledge

    MoE primarily expands computational capacity. However, a large amount of factual knowledge is embedded in the model’s main parameters. Accessing that knowledge still requires the model to follow the full computation path, which may be inefficient.

    One alternative is to introduce an external memory module. Knowledge storage is separated from the main computation, and inference retrieves relevant memory entries through a lightweight index. This can expand knowledge capacity with lower activation costs.

    The approach is related to retrieval-augmented generation (RAG), but the integration point is different.

    Comparison dimension RAG External memory
    Integration point Input side; retrieved text is appended to the prompt Internal representation layer
    Impact on prefill length Retrieved results increase input token count Usually does not increase input token count
    Knowledge update process Update the document store Update the memory module
    Integration with attention Relatively loose More tightly integrated
    Interpretability Relatively strong; retrieved passages can be inspected directly Relatively weaker

    The engineering value of this design is that the main model can focus on reasoning and generalization, while long-tail knowledge is assigned to a memory module that can be updated independently.

    This can reduce the cycle in which adding knowledge requires more parameters, and more parameters require more compute.

    Important limitations remain:

    • Stored memories may become outdated;
    • Retrieval accuracy affects the final output;
    • The method used to integrate memory with attention affects stability.

    Public information is still insufficient to establish generally applicable latency and cost figures. Evaluation should therefore be based on measurements from the target workload.

    5. Model Selection and Deployment

    Metrics to consider during selection

    Parameter count alone cannot predict deployment cost. More useful metrics include:

    • Activated parameter count: Determines the amount of computation per token;
    • KV bytes per token: Determines how many long-running sessions can fit in available memory;
    • Prefill-to-decode latency ratio: Indicates the user experience for long prompts;
    • Quality stability at long context lengths: Shows whether the model remains usable after compression or architectural changes.

    A rough estimate for the cost of a single request is:

    [
    \text{Cost per request} \approx
    \frac{
    \text{Prefill tokens} \times \text{unit prefill cost}
    +
    \text{Decode tokens} \times \text{unit decode cost}
    }{
    \text{effective hardware throughput}
    }
    ]

    This formula is useful for comparing options. Actual costs must be measured on the target hardware using real throughput and latency.

    Match the inference stack to the architecture

    If a model supports cross-layer cache reuse or low-precision KV storage, the inference framework must provide corresponding support.

    For example, when using vLLM, relevant configuration options may include the following. Names and availability can change between versions, so consult the documentation for the version in use:

    • --kv-cache-dtype: Sets the storage precision of the KV cache, such as FP8;
    • --enable-prefix-caching: Reuses cache for identical prefixes, such as system prompts, which can be particularly useful for agent workloads with repeated prefixes;
    • --max-model-len: Limits the maximum context length and prevents a single request from consuming all available memory;
    • --gpu-memory-utilization: Controls the proportion of GPU memory reserved for use, leaving space for the KV cache.

    Cross-layer KV sharing typically depends on model-specific implementation. It cannot usually be enabled through a generic configuration flag alone. Confirm that the inference framework supports the specific model architecture.

    Long-lived session state can also be managed hierarchically:

    • Keep active sessions in GPU memory;
    • Move recently used sessions to host memory;
    • Move inactive sessions to object storage.

    For monitoring, track TTFT, GPU memory utilization, and prefix-cache hit rate together.

    Manage the context itself

    Even when an architecture supports million-token contexts, sensible context management can substantially reduce cost. Common techniques include:

    • Truncate overly long tool outputs and retain only content relevant to the current task;
    • Summarize historical conversations periodically;
    • Use retrieval to select only the information that needs to enter the context.

    These techniques do not depend on a particular model architecture and apply to most agent systems.

    6. Common Misconceptions

    The first misconception is to look only at parameter count. A model with more total parameters may not have more activated parameters or higher KV bytes per token, and the reverse can also be true.

    The second is to treat theoretical compression ratios as actual speedups. KV compression primarily reduces memory consumption. Its impact on latency depends on whether the bottleneck is computation or memory bandwidth.

    The third is to assume that million-token support guarantees consistent quality at one million tokens. Long-context retrieval performance typically declines as the context grows, so models should be tested on the specific long-document tasks they will handle.

    The fourth is to quantize without evaluating quality. Lower bit widths can cause significant degradation on some tasks. Optimizing only for compression while ignoring quality metrics can lead to production failures.

    Conclusion

    In the long-context era, competition is fundamentally about the cost of each unit of intelligence.

    Asymmetric computation, cache reuse and quantization, and knowledge decoupling reduce inference costs from three different angles: computation, storage, and capacity.

    For teams building AI agent applications, understanding these mechanisms and measuring them against real workloads is more valuable for model selection and deployment decisions than comparing leaderboard scores alone.