Architecture for Cutting LLM Inference Costs in Long-Context Agents

    This article explains why inference costs rise sharply for long-context agent workloads, focusing on prefill compute and KV cache memory. It introduces a cost model for comparing architectures and covers three design directions: asymmetric prefill, KV cache compression and reuse, and separating knowledge memory from backbone computation. It also outlines serving-system practices, the metrics to track, and the trade-offs of each approach.

    1. Returning to the General Engineering Problem

    A recent public technical report describes a class of large model optimizations for long-context and agent workloads. The report states that it can reduce the effective compute of the prefill stage to nearly half without significantly sacrificing capability. It also claims to reduce the global KV cache from the order of thousands of bytes per token to the order of hundreds of bytes per token, and to support context windows of one million tokens.

    This article does not focus on a single product or repeat the report’s product names and launch claims. Instead, it looks at the general engineering question behind these results. As models move from question-answering systems to agents that keep executing tasks, why does inference cost get out of control, and how can architecture reduce that cost systematically?

    Typical agent workloads have three traits:

    • Long context. A software engineering task may include a code repository summary, a dependency tree, terminal logs, test failure stack traces, and historical tool outputs. The prompt can easily grow from a few thousand tokens to several hundred thousand tokens.
    • Many turns. Planning, retrieval, execution, observation, and re-planning form a loop. Historical state must stay accessible to later steps.
    • Sensitivity to latency and cost. Users experience the wait for each turn. The platform sees GPU HBM, host memory, SSDs, and internal network bandwidth occupied for long periods.

    For this reason, leaderboard scores alone are not enough to evaluate these architectures. Two more direct metrics matter: the prefill compute cost per token, and the resident memory cost per historical token.

    2. Cost Model: Prefill and KV Cache Follow Separate Curves

    Let L be the number of Transformer layers and N the prompt length. For now, treat the hidden dimension and attention structure as constants. In prefill, every layer processes the full sequence, so the dominant term is roughly O(N·L). As context grows, time to first token grows approximately linearly with N. Without sparse or block-wise attention optimizations, attention also adds a term close to O(N²).

    Decode processes only one new token per step, but it reads the historical KV cache at every step. The bottleneck therefore shifts from compute to memory capacity and memory bandwidth.

    A simple estimate shows the pressure on the KV cache. Suppose each token requires B bytes of global KV storage, the context length is N, and the number of concurrent sessions is C. The resident GPU memory is approximately:

    1. def kv_hbm_bytes(bytes_per_token, context_tokens, sessions):
    2. return bytes_per_token * context_tokens * sessions
    3. # Order-of-magnitude example: not a product commitment, for capacity planning only
    4. for bpt in (3500, 900, 450):
    5. gib = kv_hbm_bytes(bpt, 1_000_000, 32) / (1024 ** 3)
    6. print(bpt, "B/token ->", round(gib, 1), "GiB")

    The value of this example lies in the scaling trend, not the exact figures. When N approaches one million and C reaches several dozen, a few thousand bytes per token can quickly fill HBM. Cutting per-token overhead to a quarter of its original size has the same effect as increasing either the number of concurrent sessions or the maximum context length several times over. Combining this with paged caching, prefix reuse, and tiered offloading to disk can increase the gains further.

    3. Optimization 1: Prefill Does Not Need to Run the Full Backbone

    Traditional decoder-only inference applies the same computation to every prompt token at every layer. A more aggressive approach separates understanding a long prompt from generating the next token. During prefill, most tokens pass only through the first part of the network or a lightweight branch to build representations. During decoding, the full model runs to maintain generation quality.

    MoE models activate only some experts for each token, so the activated parameter count is much smaller than the total parameter count. If the prefill path also reduces the average activated size from the tens of billions to single-digit billions of parameters, both time to first token and prefill compute drop significantly.

    This approach has two pitfalls:

    • Pruning the network. Treating a half-depth network as simple pruning can lose long-range dependencies in the deeper layers. A safer design lets shallow layers handle reusable context state. Deeper layers then supply semantics during decoding and when key segments are recomputed.
    • Scheduling. Asymmetric execution changes kernel scheduling. Prefill batch sizes, expert routing hit rates, and memory read/write patterns all shift. The design must also account for elastic scaling on the container platform, queue-based peak shaving, and request tiering. Otherwise, per-GPU efficiency gains can be offset by scheduling jitter.

    4. Optimization 2: Compress Each KV Entry and Reduce the Number of Entries

    KV cache optimization works on two levels: the size of each entry, and the number of entries that matter.

    For entry size, common methods include low-rank projection to compress the KV dimension, low-bit quantization of the main KV, and more compact representations for index or routing information. When reducing FP16 or BF16 to FP8 or even FP4, byte count is not the only factor. Teams also need to evaluate dequantization overhead, the effect of numerical error on long-context retrieval, and whether critical layers should keep higher precision. A common hybrid strategy stores the main KV at low precision, keeps sensitive layers or heads at high precision, and encodes indexes separately in a compact form.

    For entry count, the goal is to reduce repeated storage of the same history across layers and to reduce the number of positions that take part in attention. Cross-layer reuse lets adjacent layers share backbone KV and keep only small incremental parts. Cross-head sharing and low-rank decomposition reduce redundancy between heads. Top-K selection based on a lightweight index lets decoding skip most of the history. The system first locates candidate blocks, then runs exact attention on them.

    The core idea is to separate globally accessible history from the history read at each step. The system keeps long memory available at the logical level, but moves only the data that each step needs.

    5. Optimization 3: Decouple Knowledge Memory from Backbone Computation

    A long context window does not mean all knowledge should sit inside it. A more practical layering works as follows. Current task state stays in the KV and prefix caches. Stable domain knowledge lives in external memory or retrieval indexes. General reasoning capability stays in the backbone parameters. This lets decoding reach a larger knowledge base at lower activation cost, and it avoids encoding every fact into the attention history.

    In practice, memory falls into three categories:

    • Short-term session state. This state needs strong consistency and low latency, so it suits resident HBM.
    • Medium-term task artifacts. Examples include code snippets, test reports, and summaries of tool outputs. These suit host memory or local SSDs with indexes that can be invalidated.
    • Long-term knowledge. Examples include enterprise documents, API conventions, and fault libraries. These suit retrieval services backed by object storage, with versioned management.

    General-purpose cloud platforms such as Baidu AI Cloud offer object storage, log services, message queues, monitoring and alerting, and container platforms. These services can handle artifact retention, asynchronous event flow, task queuing, and capacity observation. The architecture should stay interface-neutral, so the memory layer is not tied to a single proprietary interface.

    6. System Implementation: Memory, Scheduling, and Observability Are All Essential

    Architectural gains are realized through the serving system. Build the system in the following order:

    • Capacity budgeting. Estimate HBM as peak concurrency × average context length × KV bytes per token × a safety factor. Then reserve space for prefix caching, temporary activations, communication buffers, and fragmentation.
    • Paging and prefix caching. Manage the KV cache in blocks. Reuse shared prefixes, such as system prompts, repository descriptions, and tool schemas, across sessions. Prefix cache hit rate should be a first-class metric.
    • Tiered storage. Keep hot history in HBM, warm history in host memory, and cold history in encoded form on disk. Swap-in and swap-out policies should account for agent steps, so the system does not reclaim critical state before a tool call returns.
    • Request tiering. Route latency-sensitive interactive requests separately from throughput-oriented batch jobs. Send long prefill tasks to a dedicated queue so they do not block short requests.
    • Quality guardrails. Build separate regression sets for low-bit quantization, Top-K retrieval, and cross-layer reuse. Monitor long-range reference accuracy, tool parameter correctness, and consistency of goals across turns.

    A practical capacity dashboard should include at least: KV bytes per token, prefix hit rate, prefill and decode time share, HBM watermark, page swap count, Top-K candidate hit rate, and success rate for long-context tasks. Every optimization that goes live should report both the cost reduction and whether capability has regressed.

    7. Limitations and Conclusion

    These architectures involve trade-offs. Asymmetric prefill adds implementation complexity and may change how models are fine-tuned and distilled. Low-bit KV quantization is more sensitive to extreme long-range retrieval. Top-K attention can miss relevant candidates. Decoupling external memory moves the pressure to retrieval quality, permission isolation, and data freshness. In privacy-regulated settings, teams also need to define which history may be written to disk, which may be reused across sessions, and which must be destroyed when a session ends.