Reducing Inference Costs for Long-Context LLMs: Technical Approaches Explained

    This article explains the main technical approaches for lowering inference costs in long-context large language model serving. It covers why prefill computation and the KV cache drive costs, how to estimate KV cache size, four ways to reduce cache costs, how to decouple knowledge capacity from the backbone network, and how to evaluate an inference optimization.

    1. Background: Long Context Makes Inference Cost a Bottleneck

    LLM applications are moving from single-turn question answering to long-running workflows. A complex software engineering task may involve hundreds of tool calls, large volumes of terminal output, and an entire code repository. Research assistants, graphical user interface agents, and enterprise process automation also need models to keep interaction history over time. As input grows longer, the compute and memory pressure during inference increases, and serving costs rise with it.

    Traditional decoder-only Transformers face two main cost sources in these scenarios:

    1. Prefill computation: When the model processes a prompt, every layer computes over the full prompt. The attention cost grows roughly quadratically with prompt length, and the total cost is also proportional to the number of layers.
    2. KV cache: To avoid recomputing history during generation, each layer stores the keys and values of past tokens. The longer the context, the more GPU memory the cache consumes. In multi-turn sessions, the cache also adds overhead in host memory, solid-state drives, and network transfers.

    Cost reduction can be grouped into four directions: reducing the effective compute during prefill, shrinking the size of each cache entry, reducing the number of historical positions that participate in attention, and reducing duplicated caching across layers.

    2. Prefill: Giving Prompts a Shorter Compute Path

    During prefill, the entire prompt is known in advance, so it can be processed in parallel in one pass. The compute cost therefore depends mainly on the network depth and the number of parameters each token passes through.

    A common approach splits the network into a front segment and a back segment, so that most prompt tokens pass only through the front segment. The front segment encodes the context, and the back segment performs the decoding used for generation. As a result, the average number of active parameters per prompt token during prefill is lower than during generation. The benefit of this asymmetric design depends on the ratio of prompt length to generated length. The longer the prompt and the shorter the output, the greater the savings.

    Implementation requires attention to the following points:

    • The split point should be determined through quality evaluation. Splitting too early may weaken the model’s context representation.
    • The generation phase still needs the full network, so the improvement in end-to-end latency mainly shows up in time to first token (TTFT).
    • The inference framework must support switching execution paths by stage. Otherwise, the benefit is hard to realize.

    3. Estimating KV Cache Capacity

    Understanding cache usage is a prerequisite for optimization. For standard multi-head attention or grouped-query attention, the cache size per token can be estimated with the following formula:

    Bytes per token = 2 × number of layers × number of KV heads × head dimension × bytes per element

    The factor 2 accounts for storing keys and values separately. The example below uses assumed parameters to illustrate the calculation:

    1. def kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_elem):
    2. # The factor 2 accounts for storing K and V separately
    3. return 2 * layers * kv_heads * head_dim * bytes_per_elem
    4. # Assumed configuration: 64 layers, 8 KV heads, head dimension 128, BF16 (2 bytes)
    5. per_token = kv_bytes_per_token(64, 8, 128, 2)
    6. context_len = 1_000_000
    7. total_gib = per_token * context_len / 1024**3
    8. print(f"Per token: {per_token} bytes, 1M tokens: {total_gib:.1f} GiB")

    In this assumed configuration, each token uses about 262,144 bytes (256 KiB), and the cache for a one-million-token context is about 244 GiB. A single GPU can rarely hold a cache of this size, so cache compression and tiered management become central problems in long-context serving.

    4. Four Ways to Reduce Cache Costs

    4.1 Compressing Individual Cache Entries

    Lower-precision storage reduces the bytes per element, for example by quantizing the cache from BF16 to FP8 or FP4. After compression, validate the accuracy changes on long-text retrieval and reasoning tasks, and confirm that the dequantization overhead does not cancel out the savings.

    4.2 Reducing the Historical Positions Involved in Attention

    Sparse attention lets each query access only a small set of key positions. For example, an indexer can select the Top-K historical positions for each query. This lowers the compute cost, but the indexing itself requires computation and caching, so its cost must be included in the overall budget.

    4.3 Sharing Cache and Indexes Across Layers

    Attention patterns in adjacent layers are often similar. Several layers can share one main cache, or share the same set of Top-K selection results, which reduces duplicate storage and repeated indexing. Coarser sharing saves more memory but has a larger impact on the model’s expressive capacity, so evaluation is needed to determine the appropriate boundaries.

    4.4 Tiered Storage and On-Demand Loading

    Hot data stays in GPU memory, warm data moves to host memory, and cold data goes to solid-state drives or remote storage. The scheduling policy should consider each session’s access frequency and prefetching mechanisms, so that cache hits do not introduce excessive latency.

    5. Decoupling Knowledge Capacity from Backbone Computation

    Large amounts of knowledge can be stored in an independent memory module, and the backbone network reads from it only when needed. This allows knowledge capacity to grow without a linear increase in activations per inference. Common forms include retrieval-augmented generation (RAG), external vector indexes, and parametric memory. In engineering practice, the key factors to assess are retrieval latency, recall quality, and the cost of updating knowledge.

    6. How to Evaluate an Inference Optimization

    Evaluation should cover three dimensions: performance, resources, and quality. All three are essential.

    • Performance metrics: time to first token (TTFT), time per output token (TPOT), and throughput per unit of time.
    • Resource metrics: peak GPU memory, cache hit rate, and read and write bandwidth for host memory and storage.
    • Quality metrics: accuracy on long-context retrieval, unit test pass rates on code tasks, and consistency in multi-turn conversations.

    The evaluation process can be structured as follows:

    1. def evaluate(model, workloads, baseline=None):
    2. report = {}
    3. for name, w in workloads.items():
    4. result = run_benchmark(model, w) # Returns ttft, tpot, peak_mem, and accuracy
    5. report[name] = result
    6. if baseline:
    7. report[name]["delta_accuracy"] = (
    8. result["accuracy"] - baseline[name]["accuracy"]
    9. )
    10. return report

    Test workloads should be as close to real business usage as possible. They should cover prompts of different lengths, different input-to-output ratios, and long sessions with multiple rounds of tool calls. Relying on a single synthetic test can overstate the benefits.

    7. Practical Recommendations

    1. Measure before optimizing. Record the distribution of prompt lengths, cache usage, and time spent in each stage to find the real bottleneck.
    2. Introduce changes one at a time. Adjust only one setting per round so that quality changes can be attributed correctly.
    3. Build a regression set. Fix the key business cases and use them as an acceptance gate for every model or configuration change.
    4. Account for the full pipeline cost. Compressing the cache may add indexing and scheduling overhead, so the end-to-end cost must be included in the calculation.

    All numbers in this article are examples. Actual gains must be confirmed through benchmarking on your own hardware, inference framework, and workloads.