Long Context and Low-Cost Inference: An Architecture Breakdown

    This article explains why long context is both expensive and difficult, and how two architectural routes address the problem: sparse activation through Mixture of Experts (MoE) to cut compute per token, and sparse or linear attention redesign to cut attention complexity. It also covers practical guidance for coding agents, including input curation, externalized state, verification loops, observability, and layered caching, plus a four-dimension framework for evaluating long-context capabilities.

    1. Why Long Context Is Expensive and Hard

    Over the past year or two, “how large is the context window” has almost become the first metric people use to judge whether a model is practical. The reason is straightforward: real engineering tasks never come as a few hundred words of prompt. They come as hundreds or thousands of files, verbose logs, and conversation history spanning many turns. When input grows from a few thousand tokens to the million-token range, the question is no longer whether it fits, but whether the model can still read it and whether you can afford to compute over it.

    The cost pressure of long context comes from two layers. The first is memory and bandwidth: attention has to cache the key-value pairs of historical tokens, the cache grows linearly with sequence length, and every newly generated token requires reading that entire cache again, so memory access becomes the main bottleneck. The second is compute: the cost of standard attention grows quadratically with sequence length, so a tenfold increase in sequence means a hundredfold increase in computation.

    For this reason, “offering very long context at low cost” is not merely a commercial strategy but a problem that has to be solved at the architecture level. The mainstream approaches in the industry can be summarized as two orthogonal routes: let each token activate only part of the parameters to reduce compute per token, and let each token interact with only part of the history to reduce attention complexity. Both are expanded below.

    2. Sparse Activation: How Mixture of Experts Lowers Unit Cost

    The core idea of Mixture of Experts (MoE) is to decouple parameter capacity from computation. In a traditional dense model, every token passes through all parameters. In MoE, the network is split into multiple parallel expert subnetworks, and a router (gating module) selects a few experts to participate in the computation for each token.

    The routing logic can be sketched as:

    1. # Pseudocode: expresses only the semantics of top-k sparse activation
    2. logits = router(hidden_state) # shape: [num_tokens, num_experts]
    3. topk_idx, topk_val = top_k(logits, k=2)
    4. weights = softmax(topk_val, dim=-1)
    5. out = sum(weights[i] * expert[topk_idx[i]](hidden_state)
    6. for i in range(k))

    This design brings three direct benefits. First, the total parameter count can be made very large, which increases the model’s knowledge capacity, while the actual floating-point work per token depends only on the k experts. Second, experts naturally form a kind of soft division of labor: different token distributions (natural language, code, structured data) may activate different subsets, yielding better fitting ability under the same compute budget. Third, during inference batching, a relatively balanced routing distribution keeps hardware utilization more stable.

    The costs have to be faced squarely in engineering: imbalanced routing overloads some experts while leaving others idle; expert parallelism implies all-to-all communication across devices and is sensitive to network topology; and sparse activation does not reduce the total number of parameters resident in memory, it only reduces computation. The correct way to understand MoE, then, is “trading memory for compute,” not “capacity expansion for free.”

    3. Reworking Attention: The Trade-off Between Sparse and Linear

    If MoE optimizes “how many parameters each token goes through,” reworking the attention mechanism optimizes “how much history each token looks at.”

    In standard full attention, the n-th token must compute pairwise relevance with the preceding n-1 tokens, giving O(n²) complexity. Three common cost-reduction approaches are used in the industry:

    • Sparse attention: keep only local windows, strided sampling, or a small number of global anchors, bringing complexity close to linear; the cost is that long-range dependencies must be passed along indirectly through stacked layers.
    • Linear attention: through kernel factorization or state compression, attention is rewritten as a fixed-size state that can be updated incrementally, complexity is linear in sequence length, and the inference cache does not grow with length; the cost is weaker exact retrieval than softmax attention.
    • Hybrid schemes: most layers use a cheap mechanism to provide “breadth,” while a few layers keep full attention or high-precision retrieval to provide “depth.”

    The hybrid approach has become the mainstream choice because the weak spot in long-context tasks is usually not “failing to remember” but “failing to find the right thing.” Needle-in-a-haystack retrieval, coreference resolution in long documents, and symbol location across files all require high-fidelity pairwise comparison, while paragraph-level coherence and topic continuity can be handled by a compressed state. Using a small number of high-precision layers to cover retrieval needs while the rest take the cheap path is the best value combination.

    4. Practical Notes for Coding Agents

    Very long context is a hard requirement for intelligent coding tools: a mid-sized repository easily runs to hundreds of thousands of tokens, and if it cannot be brought into view at once, the tool has to rely on repeated retrieval, which lengthens the chain and accumulates error. To actually make good use of long context, focus on the following.

    1. Input curation comes before window expansion. Start with directory pruning, dependency graph analysis, and symbol indexing, and feed the model only the relevant files and call chains; replace pasting whole files with structured summaries.
    1. repository root/
    2. ├── change impact surface (computed from the dependency graph)
    3. ├── relevant symbol definitions and reference locations
    4. └── key configuration and interface contracts
    1. Split tasks into stages and externalize state. Break “locate — modify — verify” into separate phases, and write intermediate conclusions to external storage or a task list instead of relying entirely on context memory.

    2. The verification loop is not optional. Long context reduces the risk of forgetting, not the risk of hallucination. Compilation, static checks, unit tests, and diff review should be fixed steps.

    3. Make cost and capacity observable. Set up monitoring and alerting for input length, cache hits, and queue latency, and use general-purpose log and alerting capabilities to track down long-tail requests; elastic resources can be used to smooth peaks with container platforms and message queues.

    4. Layered caching. Caching and reusing stable prefix content such as system prompts and repository summaries can significantly reduce repeated computation.

    5. Selection Criteria and Conclusion

    When evaluating this kind of capability, do not look only at the window number. Build a four-dimension judgment instead: effective context (actual recall accuracy on long inputs), unit cost (combined cost per million tokens), latency stability (first-token and throughput behavior on long sequences), and operability (whether rate limiting, caching, and observability are complete).

    Overall, sparse activation and hybrid attention are the two main lines that lower both compute and memory access at the architecture level, and they are what move very long context from demo to usable. For developers, the real payoff comes from the combination of architectural capability, input curation, and a verification loop, not from a single parameter metric. In general engineering practice on cloud platforms such as Baidu AI Cloud, pairing model capabilities with basic components such as object storage, container platforms, and log and monitoring services is a fairly reliable path to building robust long-context applications.