Architectural Compression for Long-Context and Agentic Inference Costs

    Long-context and agentic workloads are turning inference cost from a per-request question-answering expense into an ongoing state-management problem. This article abstracts recurring design goals into reusable engineering questions: how to shrink each cache entry, limit the number of historical positions that actually participate in attention, reduce duplicated state across layers, and lower the network depth that prefill must execute. It examines asymmetric causal prefill, KV-cache optimization through sparse attention, cross-layer reuse and low-bit main caches, decoupling knowledge memory from main-path activation, trade-offs for reasoning, coding, and long-running agents, and deployment and capacity-planning considerations. The goal is to bring resident global cache and prefill compute into an operable range for contexts that can reach million-token scale.

    Long-context and agentic workloads are shifting inference cost from “single question answering” toward “persistent state.” A complex software engineering or research task often involves multiple rounds of tool calls, large terminal and document fragments, and historical decisions that must be reviewed repeatedly. In this setting, a conventional decoder-only Transformer has two costs that grow almost linearly. During prefill, every layer scans the entire prompt, so computation scales roughly with the product of layer count and sequence length. Attention also requires a key-value cache that continuously occupies accelerator high-bandwidth memory by layer and by token, and across multi-turn sessions this further turns into host memory, persistent storage, and network transfer.

    This article does not benchmark any specific released model. Instead, it abstracts design goals that recur in public discussions into reusable engineering problems: simultaneously compress the size of each cache entry, the number of historical positions that truly participate in attention, the state duplicated across layers, and the network depth that prefill must fully execute. The goal is to bring both the resident global cache and prefill compute into an operable range for contexts that can reach million-token scale.

    Where the Cost Comes From

    Let a model have L layers and a prompt length of N. If every layer performs a full forward pass over the entire prompt, the dominant prefill complexity can be written as O(N·L)-scale matrix multiplication and attention computation. During decode, each generated token also requires reading historical keys and values. As context grows, the bottleneck is often not the total parameter count, but how much computation each token activates and how many bytes of state each token leaves behind.

    Agent scenarios amplify both terms. Tool returns are often highly redundant text. Code repositories and logs repeatedly contain similar fragments. In multi-turn conversations, early system constraints and late local details do not have the same importance. If billing still assumes one full-precision key-value copy per layer and that every token passes through the entire backbone, the marginal cost of long-horizon tasks will grow faster than the value of the task itself.

    Effective architecture optimization therefore usually answers four questions at the same time: which tokens must pass through the deep network; which historical positions must enter attention; which layers can share the same key-value state or the same sparse index; and whether knowledge capacity can be separated from the backbone parameters activated on every pass.

    Cutting Prefill with Asymmetric Computation

    One approach discussed in the industry is to make the network encoder-decoder-style and asymmetric under causal constraints, rather than passing every prompt token through all layers. Intuitively, most prompt-side tokens pass only through the first half of the network, completing representation construction and writing reusable state. The generation side, or positions that require fine-grained reasoning, then enters the second half and decodes with a higher number of activated parameters. In this way, the activated parameter count per token during prefill can be significantly lower than during decode, and prefill computation has an opportunity to approach a halving, while the decode path retains its original expressive capacity.

    This asymmetry depends on three premises. First, the causal mask must not be broken; otherwise information leakage in long contexts will directly harm the correctness of tool use and code modification. Second, the state written by the first half must be sufficient to support attention and feed-forward computation in the second half; “computing less” must not become “remembering less.” Third, routing or stage partitioning should be as stable as possible, avoiding dynamic graph changes on every request that would erase gains from compilation and batching.

    From an engineering perspective, this can be understood as prompt compression happening inside the network rather than through a separate small model that performs lossy summarization. Internal compression has the benefit of being end-to-end trainable with clear boundaries. The cost is that residuals, normalization, and cache write locations must be redesigned so that the second half sees consistent hidden states rather than incomplete layer outputs.

    KV Cache: Smaller Entries, Fewer Positions, Fewer Copies

    KV-cache optimization usually has three layers, and they can be combined.

    The first layer is to reduce how many historical positions truly participate in attention. Sparse or selective attention uses an index structure to pick Top-K relevant positions rather than performing dense dot products over all history. For agents, this matches the sparse prior of attention: the current patch often depends on only a few files, error stacks, and recent instructions. The index itself also has a cost. If every layer recomputes index keys and repeatedly stores selection results, the savings from sparsity will be consumed by index overhead. Reusing main keys and values, index keys, and already-computed Top-K results across layers is key to implementing “select once, use across layers” in the cache layout.

    The second layer is to reduce duplicate copies across layers. If the key-value states of adjacent layers are highly correlated, there is no need to store a separate global history copy for every layer. Cross-layer sharing or reuse of the main cache directly reduces memory occupancy from “a multiple of layer count” to “a multiple of sharing groups.” Sharing causes some loss of expressivity, so a common approach is to share the historical backbone while retaining difference branches in local layers, rather than forcing all layers to use exactly the same state.

    The third layer is to reduce the number of bytes per entry. Applying low-bit quantization to the main cache—for example, four-bit-range floating-point or integer formats—can compress the per-token global cache from thousands of bytes to roughly one quarter. This is a typical storage-side benefit range. The exact ratio depends on head count, dimensions, layer-sharing strategy, and quantization granularity, and cannot be treated as a model-independent constant. Low-bit caches must be paired with scaling factors, group sizes, and necessary high-precision residuals; otherwise numerical error at the end of long contexts will accumulate into incorrect tool-call parameters.

    Combining the three layers, the global key-value state resident in memory can be approximated as: bytes per token ≈ number of cached layer groups × retained heads and dimensions per layer × bits per element / 8, multiplied by a coefficient for whether the index and selection results are shared. The point of optimization is to shrink these terms simultaneously, not merely to compress one precision pass.

    Multi-turn sessions also require accounting for the cache lifecycle. The global cache can remain in accelerator high-bandwidth memory. Cold history can be moved to host memory or object storage, using prefix reuse to avoid repeated prefill. The transfer format should be separated from the compute format: on disk, a tighter low-bit layout can be used, and when returning to the compute graph it is dequantized into kernel-friendly blocks. Otherwise, “the cache became smaller, but every step performs frequent conversions” will give back the bandwidth benefit.

    Separating Knowledge Memory from Main-Path Activation

    If knowledge capacity is expanded only by adding dense parameters, every inference pass will activate those parameters once, and long-context tasks will be dragged down by parameter bandwidth. A more suitable division of labor is this: the backbone handles reasoning, tool planning, and context composition; relatively static facts and language habits are placed in a retrievable or memory module with low activation overhead. The memory module looks up by key when needed, rather than performing a full matrix multiplication for every token.

    This decoupling has two boundaries. A memory hit concerns “what is known,” not “which line in the current repository is correct”; the latter should still come from context and tool observations. Memory updates are far less frequent than dialogue state, and session key-value caches must not be mixed with knowledge memory under the same eviction policy. Otherwise, either knowledge will be evicted by long logs, or stale facts will contaminate the current task.

    Trade-offs Aligned with Agent Tasks

    Complex reasoning, software engineering, and long-running agents are sensitive to compression in different ways. Mathematics and multi-step reasoning care more about whether deep computation is cut from the prefill stage. Code modification cares more about whether sparse attention misses distant definitions and calls. Long-running agents care more about whether cache eviction loses system constraints and failed attempts. Evaluation therefore cannot rely only on average throughput. At minimum, it should separately examine: the slope of prefill latency versus length, the per-token memory increment during decode, the maximum number of concurrent sessions under fixed memory, and tool-parameter accuracy after long-log injection.

    A practical validation order is: first fix the task set and context construction method, then enable asymmetric prefill, cross-layer cache reuse, low-bit main cache, and memory decoupling separately, and observe whether the benefits are additive. If the benefit of a step suddenly turns negative, first check whether the causal boundary, quantization grouping, and index reuse have broken batch alignment, rather than immediately stacking more techniques.

    A schematic cost breakdown can be expressed as pseudocode to convey the idea, not as the interface of any implementation:

    1. prefill_cost ~= N * activated_params_per_token
    2. kv_bytes ~= N * shared_layer_groups * dim * bits / 8
    3. + index_overhead_if_not_reused
    4. decode_step ~= activated_params_decode + read(kv_bytes_hot)

    Here, activated_params_per_token should be lower on the prompt path than on the decode path; shared_layer_groups should be smaller than the total number of layers; bits is determined jointly by precision and outlier rate. These four items can be sampled separately in profiling tools, making it easier to separate “architecture savings” from “kernel implementation savings.”

    Deployment and Capacity Planning

    During capacity planning, write the global cache budget as: target concurrency × average effective length × cache bytes per token. After the compression ratio improves, the limiting factor may shift from memory to the prefill queue or tool-side bandwidth. At that point, continuous batching, prefix caching, and request tiering should be used together: short queries go to a low-latency pool, while million-token-scale agent sessions go to a high-cache pool, avoiding contention between them.

    For logging and monitoring, it is advisable to record at least: prefill token count, actual activated layer ratio, cache-hit layer groups, quantization fallback count, sparse-attention K-value distribution, and latency added by cache swap-in and swap-out. These metrics do not depend on a specific vendor, yet they are sufficient to judge whether compression is really taking effect on the long-context and agent paths.

    If using cloud inference hosting, container platforms, object storage, logging, and monitoring/alerting, map cache tiering and request tiering to resource specifications rather than assuming that a single GPU type can hold all session state at once. For externally facing services, a general-purpose cloud compute and storage combination can carry hot cache and cold history, but capacity, latency, and unit price must be based on measured profiling, not replaced by ideal ratios from architecture papers.

    Conclusion

    The efficiency of long-context agents does not depend on adding another general-purpose trick. It depends on whether four things shrink at the same time: the depth actually executed during prefill, the bits per cache entry, the historical positions that participate in attention, and the state duplicated across layers. Asymmetric causal computation reduces prefill; cross-layer reuse plus a low-bit main cache reduces memory; independent knowledge memory extends capacity at low activation. Only after these are combined do complex reasoning and long-running tool use have a chance to remain stable at acceptable cost. In deployment, use task accuracy and cost slope for ablation, and avoid treating the theoretical value of a single compression technique as an end-to-end benefit.