Long-Context and Agent Inference Cost Reduction: Architecture Breakdown

    This article breaks down the structural cost of long-context and AI Agent workloads on decoder-only models, covering prefill computation and KV cache overhead. It explains three architectural approaches used to reduce inference cost: asymmetric computation for prefill, cross-layer reuse with low-bit quantization for KV cache compression, and decoupling knowledge memory from the main computation path. It also includes capacity estimation and engineering recommendations on evaluation, precision regression, cache tiering, observability, and elastic scaling.

    1. Background: Two Structural Costs in the Agent Era

    As models move from single-turn question answering to long-horizon task execution, context length is no longer an optional parameter but a requirement. A complete software engineering task may involve hundreds of tool calls, hundreds of thousands of tokens of terminal output, and relevant fragments from an entire code repository. Deep research, GUI operation agents, and enterprise automation workflows also require the model to retain and reuse historical information across long interactions.

    Traditional decoder-only architectures expose two major costs under these workloads.

    The first is prefill computation. Assume the model has L layers and the prompt length is N. Every layer must process the full prompt, with a primary computational complexity of roughly O(N·L). As N grows from a few thousand to hundreds of thousands, time to first token increases significantly, and this computation cannot be amortized per token the way decoding can.

    The second is the KV cache. The conventional approach stores keys and values independently for each layer. Cache size grows linearly with context length, continuously occupying high-bandwidth GPU memory, and in multi-turn sessions it further introduces transfer overhead across host memory, solid-state storage, and network links. The longer the context, the more this “non-computational cost” becomes a throughput bottleneck.

    Therefore, a model built for long context and agents needs to compress four types of redundancy at once: the size of each individual KV entry, the number of historical positions that actually participate in attention, the KV duplicated across different layers, and the number of network layers that must be fully executed during prefill. A more recent industry design approach can compress the global KV cache resident in GPU memory to roughly 890 bytes per token and support million-token context lengths. Its implementation path is worth breaking down layer by layer.

    2. Approach 1: Asymmetric Computation to Reduce Prefill Overhead

    The core observation is that most tokens in a prompt only need to be “written into the context” and do not need to pass through the full network depth. What genuinely requires deep semantic modeling is usually a small number of key tokens and the final generation positions.

    A typical approach introduces a causal encoder-decoder structure so that computation is distributed asymmetrically: most prompt tokens pass mainly through the first half of the network during prefill, while only a few tokens traverse all layers. The direct result is that the number of activated parameters per token drops from about 16B during decode to 8B, and prefill computation is nearly halved.

    Schematically, the routing logic can be abstracted as:

    1. # Pseudocode: illustrative execution path for asymmetric prefill
    2. def prefill(tokens, shallow_layers, deep_layers, keep_ratio=0.05):
    3. h = embed(tokens)
    4. for layer in shallow_layers: # all tokens pass through
    5. h = layer(h)
    6. idx = select_salient_positions # scored by attention/indexer
    7. h_deep = deep_forward(h[idx], deep_layers) # only key tokens go deep
    8. return merge(h, h_deep, idx) # backfill deep representations at key positions

    Three engineering points need attention. First, the selection of key positions must share the same scoring basis as the downstream attention mechanism, avoiding quality regressions caused by selecting the wrong positions. Second, the backfill process must preserve causality and must not introduce future information leakage. Third, the split point between shallow and deep layers should be tuned against the task distribution: splitting too shallow weakens capability, while splitting too deep loses the cost benefit.

    3. Approach 2: Cross-Layer Reuse and Low-Bit Quantization to Compress the KV Cache

    KV cache compression generally advances along three orthogonal paths.

    Cross-layer reuse. If the keys and values stored in adjacent layers are highly similar, only one “primary KV” needs to be kept and shared by subsequent layers. At the same time, the indexer’s keys and Top-K selection results can also be reused across layers, avoiding repeated index computation and repeated caching at every layer. This reduces both memory usage and duplicate computation during indexing.

    Sparse selection. The indexer scores historical positions so that only the Top-K positions actually participate in attention, decoupling “storing all history” from “using all history.” The context can be very long, but the amount of history actually involved in computation at each step stays bounded.

    Low-bit storage. Representing the primary KV in 4 bits, combined with suitable scaling and outlier handling, can compress the size of a single entry to a very low level while keeping accuracy largely under control. With all three combined, the global KV cache drops from about 3514 bytes per token to about 890 bytes per token, roughly one quarter of the original.

    Capacity estimation can be simplified as:

    1. Memory usage ≈ context length × cache bytes per token × concurrent sessions
    2. Before: 1,000,000 × 3514 B ≈ 3.28 GB / session
    3. After: 1,000,000 × 890 B ≈ 0.83 GB / session

    For an agent platform, this means the number of concurrent long sessions a single machine can host increases several times, and transfer frequency between cache tiers (GPU memory, host memory, storage) drops accordingly.

    4. Approach 3: Decoupling Knowledge Memory from the Main Computation Path

    Long context does not equal large knowledge capacity. Packing massive factual content into the context raises both prefill cost and cache cost at the same time. A better approach separates knowledge memory from the main computation and expands knowledge capacity with lower activation overhead: the main path handles only reasoning and orchestration, factual retrieval is delegated to an external memory structure, and only a small number of relevant fragments are fetched on demand.

    This is consistent with retrieval-augmented ideas but places more emphasis on separating memory from computation at the architectural level, so that expanding knowledge does not linearly increase the activated parameters and cache usage per token.

    5. Synergy and Engineering Recommendations

    The three optimizations do not simply stack: asymmetric computation reduces prefill computation, cross-layer reuse and low-bit quantization compress the cache, and memory decoupling suppresses context growth. Together they improve both efficiency and capability for complex reasoning, software engineering, and long-horizon agent tasks.

    For implementation, pay attention to the following areas:

    • Evaluation metrics: report time to first token, per-token decode latency, peak GPU memory per session, and long-context task accuracy separately, rather than looking at a single metric.
    • Precision regression: both low-bit caching and sparse selection require a dedicated long-context regression set, with emphasis on scenarios where critical information sits in the middle of the context.
    • Cache tiering: build a multi-tier cache combining container platforms, object storage, and logging services to reduce repeated cross-node transfers.
    • Observability: track cache hit rate, index selection rate, and memory水位 through monitoring and alerting so capacity planning has a basis.
    • Elastic scaling: on a container platform, schedule by session length into separate pools, isolating long-context tasks from short interactions so they do not compete for resources.

    If an enterprise wants to reuse these ideas in its own workloads, it can start with small-scale validation on Baidu AI Cloud infrastructure: run inference services on a general-purpose container platform, persist session history in object storage, and use the monitoring and alerting system to quantify cost reduction, then gradually expand coverage of long-context and agent scenarios.