Long Context LLMs: The Evolution of Million-Token Contexts and Engineering Practices
This article traces how LLM context windows expanded from a few thousand tokens to a million-token baseline, and why that shift required advances in attention architecture, KV cache management, and inference scheduling. It explains the cost of full attention, the role of sparse attention, and the supporting engineering techniques that make long contexts practical. It then covers how million-token contexts enable agentic coding and native multimodal workflows, how to evaluate these models on real tasks, and how to govern token consumption through budgeting, compression, caching, observability, and elastic infrastructure. Teams will find practical guidance for building observable, well-governed long-context applications within a fixed budget.
1. From Thousands to Millions: How Context Length Evolved
Over the past few years, the expansion of the context window has been the most visible line of progress in large language model capabilities. Around 2023, mainstream conversational models typically offered a native context of only a few thousand tokens—roughly a few thousand Chinese characters—so a single conversation would hit the limit quickly. A little over two years later, the baseline context of mainstream models had moved to around 200,000 tokens. After that, one million tokens gradually shifted from “an expensive option on a few flagship models” to “a baseline configuration that the industry broadly aligns on.”
This curve is not simply a matter of stacking parameters. It is the result of co-evolution across architecture, GPU memory management, and inference scheduling. Understanding this matters more than memorizing any specific number.
1.1 Why Long Context Was So Expensive Early On
The compute cost of standard full attention grows quadratically with sequence length. For a sequence of length n, the attention matrix is n×n, and both computation and memory usage scale with n². When n increases from 4K to 1M, the length grows by roughly 256×, while the quadratic term grows by roughly 65,000×. Running full attention directly is therefore infeasible from an engineering standpoint.
At the same time, the key-value cache (KV Cache) grows linearly with length. Every layer must store the key and value tensors for historical tokens, and for long sequences this memory can exceed the model weights themselves, becoming the main bottleneck for throughput and concurrency.
1.2 Why Sparse Attention Was the Turning Point
The rapid drop in long-context cost over the past two years has been driven in large part by architectural innovations such as sparse attention. The core idea is that not every token needs to interact with all historical tokens. Instead, you keep only a small number of high-value connections, using fixed patterns, local windows, learnable routing, or hierarchical summarization.
The following minimal example illustrates the computational difference between sparse and dense attention:
# Dense attention: every position interacts with every other, O(n^2) complexityscores = Q @ K.transpose(-1, -2) # [batch, heads, n, n]# Sparse attention (illustrative): keep only a local window + a few global anchorslocal = window_mask(n, w=1024) # local windowglobal_idx = select_anchors(K, k=64) # global anchorsscores = (Q @ K[:, global_idx].transpose(-1, -2) + local_scores(Q, K, local))
Sparsification delivers three benefits: attention computation drops significantly, the KV Cache can be pruned or compressed, and long sequences can be split into chunks and processed in parallel. The cost is higher implementation complexity, with careful handling needed for positional encoding extrapolation, long-range dependency recall, and training/inference consistency.
1.3 Supporting Engineering Techniques
Beyond the attention structure, deploying long context typically relies on a set of general engineering techniques: extrapolation and interpolation of positional encodings, KV Cache quantization and paged management, chunked prefill and streaming decoding, and request-level scheduling with priority queues. Together, these determine how long a context and how much concurrency a system can support under limited GPU memory.
2. Beyond Million-Token Context: The Focus Shifts to Agentic Coding
Once the context baseline reaches the million-token level across the industry, the competitive focus naturally shifts from “how much you can fit” to “whether you can use what you fit effectively.” Recently released multimodal large models commonly emphasize agentic coding capabilities, and this is no coincidence.
2.1 Long Context Really Solves Engineering Workflow Problems
The context for real software engineering tasks often spans multiple files, multiple commit histories, several interface documents, and logs. The traditional approach relies on retrieval and chunking, which easily loses structural information that crosses files. Million-token context allows “whole-repository” and “multi-round debugging” information to enter the model’s view at once, reducing the information loss caused by the retrieval pipeline.
2.2 The Value of Native Multimodality
Native multimodality means text, images, UI screenshots, charts, and other inputs are jointly modeled in the same representation space, rather than stitched together with bolt-on modules. For developers, this directly improves usability in scenarios such as writing pages from design mockups, locating issues from error screenshots, and generating project scaffolding from architecture diagrams.
2.3 Evaluate Capabilities Against the Task Itself
When evaluating these models, it is best to build evaluation sets around real tasks rather than looking only at leaderboard scores. Useful dimensions include:
- Correctness and regression rates for cross-file changes;
- Recall and citation accuracy for key information in long documents;
- Instruction retention across multiple rounds of tool calls;
- Localization accuracy with mixed image and text inputs.
3. Token Plans and Cost Governance: The Practical Constraint of Long Context
As contexts get longer, token consumption becomes the main cost driver. A “Token Plan” is essentially about planning and governing a token budget, not simply comparing unit prices. On the engineering side, you can start from these directions:
- Budget tiering: set separate quotas for the system prompt, retrieved snippets, conversation history, and tool outputs to avoid single-point expansion.
- Context compression: summarize, deduplicate, and structurally archive history, bringing only the necessary snippets into the current round.
- Cache reuse: apply prefix caching to stable system prompts and long-document prefixes to reduce repeated computation.
- Observability: use logging services and monitoring alerts to track the input/output token distribution of each request type and pinpoint abnormal consumption.
- Elastic capacity: use container platforms’ auto-scaling and message queues to smooth out load fluctuations caused by long-running tasks.
A simplified budget-control example:
budget = {"system": 2000, "retrieved": 30000, "history": 20000, "tools": 10000}def fit(messages, budget):kept, used = [], {}for m in reversed(messages): # keep messages starting from the most recentk = m["role"]if used.get(k, 0) + m["tokens"] <= budget.get(k, 0):kept.append(m); used[k] = used.get(k, 0) + m["tokens"]return list(reversed(kept))
4. Practical Recommendations
Overall, the spread of million-token context and agentic coding capabilities has pushed competition toward “how to deliver reliably within a budget.” The practical advice for teams is: first, build a small evaluation set from real business tasks and define context quotas and compression strategies; then, integrate long-context capabilities into existing logging, monitoring, and elastic infrastructure; finally, iterate continuously on three metrics—token cost, task success rate, and regression rate.
In related practice at Baidu AI Cloud, such needs are typically handled by combining general product categories such as model services, object storage, logging services, and monitoring alerts. Developers can use these to build an observable, governable long-context application pipeline.
