System-Level Ways to Reduce Long-Context Inference Cost

    Long-context inference is now a primary cost driver, not just a model capability metric. This article explains the two hard costs of decoder-only Transformers—prefill compute and KV cache—and a practical order for making prompt compute shallower, caches narrower and shared across layers, attended history shorter, and static knowledge separate from every forward pass.

    Long context has shifted from a model-capability metric to a primary cost source in the inference system. A complex software-engineering task often involves many tool calls, long terminal output, repository-scale code, and dialogue state that keeps accumulating. Deep retrieval, GUI operation, and enterprise process automation are similar: the model must answer the current question and keep usable memory across a long interaction history. A conventional decoder-only Transformer has two costs that are hard to reduce at the same time.

    The first is prefill compute. With L layers and a prompt of length N, if every layer fully processes the entire prompt, the dominant complexity is roughly O(NL). When N grows from tens of thousands of tokens to hundreds of thousands or a million, time to first token and batch throughput become bottlenecks before parameter count does. The second is the key-value cache. If every layer stores its own keys and values, the cache grows linearly with context. It fills high-bandwidth accelerator memory first, then spills to host memory, local disk, and cross-machine transfer. In multi-turn sessions, the expensive part is often not generating a few dozen more tokens, but repeatedly moving and attention-scanning the whole history.

    A long-context system can therefore compress four things at once: bytes per cache entry, how many historical positions actually enter attention, state stored redundantly across layers, and how much network depth must run in full during prefill. A claimed context window of a million tokens only describes the addressable range. The density of the global cache that stays resident in accelerator memory is what determines concurrent sessions and unit cost.

    Separate prefill from token-by-token decode

    During decode, every new token still passes through the full backbone. Activated parameter volume and memory-access paths are hard to cut further. Prefill is different: many prompt tokens exist only to provide context for later attention, and they do not all need the same depth of transform at every layer. An asymmetric causal encoder–decoder structure uses that asymmetry. The prompt side mainly follows the front half of the network, or a shallower encoder path, and reduces each prompt token’s activation scale to roughly half the decode activation scale, so prefill compute is nearly halved. Decode still uses full depth, so generation quality is preserved.

    In engineering, three paths must stay distinct, or the “half” exists only in a paper formula.

    1. Compute path. Shallow encoding must still obey the causal mask. Later prompt tokens must not leak into earlier ones. Position encoding, layer normalization, and residual alignment must join cleanly at the boundary between the encoder segment and the decoder segment.
    2. Cache path. Keys and values produced by shallow layers must be reusable by deeper layers. Otherwise the matrix multiplies that were saved are cancelled by writing the cache again.
    3. Serving path. In continuous batching, prefill and decode are often colocated. The scheduler should price a request by prompt compute, not by token count. Otherwise a long prompt starves short decode requests.

    A schematic cost split is:

    prefill_cost ≈ N L_prompt C_layer
    decode_cost ≈ T L_full (C_layer + attn_over_cache)

    Here L_prompt is smaller than L_full, and T is the length of newly generated tokens. When N is much larger than T, lowering L_prompt pays more than further compressing decode activations. Software-engineering agents are usually this shape: reading a repository, logs, and tool results is long, while the patch or conclusion to write is relatively short.

    Shrink KV cache width, length, and layer count together

    Low-precision quantization only shrinks the width of each entry. Sparse attention only shrinks how much history participates in compute. Cross-layer sharing only removes duplicated storage across layers. The three are orthogonal and should be designed together.

    On width, the main cache can be stored in low-bit floating point or fixed point, for example a main-memory format on the order of 4 bits, with higher-precision local state or periodic inspection. The bit width itself is not the point. Scale factors, group granularity, and outlier channels are. Code symbols, numbers, and a few keywords are more sensitive to quantization error and need configurable retained precision, not one global cutoff.

    On length, not every historical position deserves to enter every attention step. An indexer first does cheap recall with a low-cost key representation, then takes Top-K into the main attention. Global state can stay very long, while the effective length of one attention step is bounded. If the selection is recomputed at every layer, index cost eats the gain, so reusing the main cache, index keys, and selected positions across layers is necessary. Reuse assumes nearby layers have similar representations. If a few layers shift semantically, local reselection should be allowed instead of forcing the whole network to share one set of indices.

    On layer count, repeated cache comes from keeping a full history at every layer. Cross-layer reuse pushes the globally resident part into a small number of shared slots, and each layer keeps only a delta or a short window. Whether the compression ratio reaches several times, or approaches an order of magnitude, depends on sharing granularity, precision, and recompute frequency. It must be measured on real session traces. Theoretical byte counts are not a substitute for load tests.

    A capacity-planning ledger is:

    bytes_per_token ≈ shared_global + per_layer_delta + index_overhead

    The goal is for shared_global to grow sublinearly with layer count, and for index_overhead not to explode linearly with N. Multi-turn serving also has a host-side cost. Cold history evicted to memory or object storage needs prefix hashes and chunk checksums so the whole segment is not retransmitted every time.

    Knowledge capacity does not all have to be activated every step

    The traditional way to make a model “know more” is to widen the backbone or add experts. Activated parameters and communication then rise on every forward pass. A better split pulls relatively static knowledge memory out of backbone compute: the backbone handles reasoning and composition, and external or sparse memory holds retrievable facts and patterns. Mixture-of-experts already does conditional compute. A further memory module should extend capacity at low activation cost and use a gate to decide when to read.

    This matters especially for agents. Repository conventions, internal API notes, and troubleshooting guides change quickly and are a poor fit for dense weights frozen in one training run. Stable reasoning can stay in the backbone; volatile knowledge can sit in an updatable memory or retrieval layer. Updating memory should not force a recompute of the entire KV cache. Ideally, memory reads are decoupled from the context cache. Otherwise a knowledge update becomes a full prefill.

    Precision, latency, and failure modes

    Compression introduces error, and evaluation cannot look only at average scores. At least four task types should be watched together: locating information in long documents, state consistency after multi-hop tool calls, whether a code patch still compiles, and whether information at the tail of a very long context is still used. The common failure is not a drop in fluency. It is silent forgetting: the model still produces a fluent answer, but ignores a constraint from two hundred thousand tokens earlier, or the output of a failed test.

    Low-bit KV cache needs a fallback. When index confidence is low, or when numbers and code identifiers are dense, raise precision or enlarge K for those blocks. Cross-layer reuse needs a version. If layer structure or position encoding changes, the old cache must be invalidated. It cannot be continued by length alone. Asymmetric prefill should monitor distribution shift between the first token and later tokens, so an encoder segment that is too shallow does not leave decode under-conditioned.

    Serving metrics should be exposed separately: prefill latency per token, decode latency per token, resident accelerator memory per session, cache hit rate, eviction bandwidth, and recompute ratio. Only with those numbers split apart can you tell whether an optimization hit compute, bandwidth, or scheduling. The value of a million-token window is fewer truncations. If cache density does not fall, concurrency is stuck on accelerator memory, and the window metric has no business meaning.

    A practical order for rollout

    Do not change structure, precision, and sparsity at the same time. A workable order is: first, session-level cache accounting and prefix reuse, to see how much prefill is repeated; then a low-bit main cache with a high-precision fallback; then indexing and Top-K, with selection results shared across layers; and only then an evaluation of asymmetric encoder depth and external memory. Each step should replay the same long traces and record a quality-regression ceiling. For code and agent tasks, the replay set should include failed retries, very long logs, and multi-file context, not only short question-answer pairs.

    In a cloud deployment, run the inference service on a container platform, put cold cache and traces in object storage, use a message queue to absorb bursts of tool results, and use logs plus monitoring alerts for accelerator memory, recompute, and tail latency. These are general capabilities and do not depend on any one model’s proprietary names. Capacity planning should use bytes per token times concurrent context, not parameter count as a proxy for accelerator memory.

    Conclusion

    The cost of long context and agents comes from treating historical state too uniformly in both compute and storage. Making prompt-side compute shallower, narrowing the cache and sharing it across layers, attending fewer positions, and pulling knowledge capacity out of every activation all point the same way. Each one still has to be accepted on trace-level metrics. Window length, activated parameters, and cache bytes are means. The engineering goals are to remember constraints reliably, avoid useless recompute, and raise concurrency under a given accelerator-memory budget. Iterating in the order above lets a team turn long context from an unaffordable overhead into a plannable system resource without giving up correctness on the tasks that matter.