Architectural Design of Million-Token Context LLMs and Agent Engineering Practices
As large language models shift from knowledge-based question answering to complex task execution, their architecture and engineering requirements must evolve. This article explores the architectural design of million-token context models, focusing on attention mechanisms, sparse activation, and memory optimization. It also delves into agent engineering practices, covering execution loops, evaluation dimensions, visual feedback mechanisms, and distributed deployment on heterogeneous clusters.
1. Shifting from “Answering” to “Completing Tasks”
In recent years, the primary evaluation criteria for large language models (LLMs) have focused on knowledge question-answering and static reasoning. As application scenarios expand from basic conversation to code development, office automation, and enterprise workflow processing, the industry’s focus has shifted: Can the model maintain state across multiple steps? Can it correctly invoke external tools? Can it continuously execute and correct errors in real-world environments?
These capabilities are typically referred to as Agent Capability. The core is not the amount of knowledge in a single response, but the quality of the “plan-execute-observe-correct” loop. Therefore, understanding an execution-oriented model requires examining three levels: how the model architecture supports long-sequence processing, how training shapes behavioral patterns, and how engineering deployment ensures cost efficiency and stability.
2. Complexity Trade-offs in Attention Mechanisms
The computation of standard self-attention is proportional to the square of the sequence length n, with the main overhead being O(n²·d), where d is the hidden dimension. When a sequence scales from a few thousand tokens to a million, this overhead quickly exceeds acceptable limits.
The industry commonly adopts two solutions:
- Sparse Attention: Each position only attends to a subset of historical tokens, such as a local window plus a few global anchors. This reduces computation but loses some long-range dependencies, requiring structural compensation.
- Linear Attention: Through kernel approximation or state recursion, the computation is reduced to O(n·d²), which is more friendly to long sequences, but usually weaker than full attention on precise retrieval tasks.
In practical systems, these two are often combined in a hybrid form. A common practice is to interleave them by layers: most layers use linear or sparse attention to process long-range information, while a few layers retain full attention for precise alignment. Below is a schematic structure for layer scheduling:
# Schematic: Layer scheduling configuration for mixed attention (not a specific implementation)layer_plan = [{"type": "linear", "state_dim": 128},{"type": "linear", "state_dim": 128},{"type": "linear", "state_dim": 128},{"type": "full", "heads": 8}, # Retain full attention every few layers]num_layers = 64layers = [layer_plan[i % len(layer_plan)] for i in range(num_layers)]
During design, three factors must be balanced: the ratio of full-attention layers determines precise retrieval capability, the state dimension of linear layers determines long-term memory capacity, and the interleaving method affects training stability. These parameters should be determined through ablation studies rather than empirical guessing.
3. Sparse Activation: Total vs. Activated Parameters
The “total parameters” and “activated parameters” of large models are two different concepts. When using the Mixture of Experts (MoE) structure, the model contains numerous expert sub-networks, but each token only passes through a few experts selected by a router. Therefore, the computation for a single inference is determined by the activated parameters, while the model capacity is determined by the total parameters.
The basic logic of the router is as follows:
# Schematic: top-k expert routingdef route(hidden, router_weight, k=2):scores = hidden @ router_weight # Scores for each expertprobs = softmax(scores)topk_idx = argsort(probs)[-k:] # Select the top k experts with the highest scoresweights = probs[topk_idx] / probs[topk_idx].sum()return topk_idx, weights
In engineering, three issues require attention. First is load balancing: if a large number of tokens concentrate on a few experts, it creates computational hotspots, which usually require auxiliary loss or capacity constraints to mitigate. Second is communication overhead: when experts are distributed across different devices, tokens need to be dispatched across devices, and communication bandwidth can become a bottleneck. Third is inference latency: sparse activation reduces computation but increases the complexity of routing and scheduling; the actual acceleration effect must be confirmed through end-to-end measurement.
4. VRAM Estimation for Million-Token Context
The longer the context window, the larger the VRAM occupied by the KV cache. In autoregressive inference, the VRAM usage of the KV cache can be approximated as:
VRAM ≈ 2 × Number of attention layers × Number of KV heads × Head dimension × Sequence length × Bytes per element × Batch size
Assume a full attention configuration: 64 layers, 8 KV heads, head dimension 128, sequence length 1 million, using fp16 (2 bytes per element), and batch size 1. Plugging into the formula, the KV cache is about 262 GB, far exceeding the VRAM of a single GPU.
If 16 of these layers retain full attention and the rest use a fixed-size state representation, the KV cache drops to about 65 GB. While still requiring multi-GPU partitioning, it is within a manageable range. This shows that the significance of a hybrid structure for long-context deployment lies primarily in VRAM optimization, not just computation speed.
Common techniques in actual deployment include KV cache quantization, paged management to reduce fragmentation, dynamic VRAM allocation based on sequence length, and splitting the cache across multiple GPUs by layer or by head.
5. Agent-Oriented Training and the Execution Loop
The key capability of an agent-oriented model is forming a stable loop between tool invocation and environmental feedback. A typical execution loop looks like this:
# Schematic: Agent execution loopdef run_agent(task, model, tools, max_steps=50):history = [{"role": "user", "content": task}]for step in range(max_steps):action = model.generate(history) # Plan the next actionif action.type == "final_answer":return action.contentif action.type == "tool_call":# Tool parameters need validation to prevent privilege escalation or injectionvalidate(action.args, tools[action.name].schema)result = tools[action.name].run(**action.args)history.append({"role": "tool", "content": result})raise RuntimeError("Max steps exceeded, task not completed")
There are three critical components in this loop that must be strictly managed:
- Parameter Validation: Tool invocation parameters must conform to predefined structures, and permission scopes must be checked before execution.
- Error Recovery: Error messages returned by tools must be read by the model and used to revise the plan, rather than simply aborting the process.
- Termination Conditions: Maximum steps, timeouts, and cost limits must be set to prevent ineffective loops from continuously consuming resources.
During training, a large number of multi-step task samples are typically included, covering code repair, file processing, form filling, and multi-tool collaboration. The training objective is not only the correctness of the final result but also the reasonableness of intermediate steps.
6. Evaluation Dimensions for Agent Capabilities
A single knowledge QA score cannot reflect execution capability; evaluation should be broken down into multiple dimensions:
- Multi-step Task Success Rate: The proportion of complete tasks successfully finished in a given environment.
- Tool Invocation Accuracy: Whether parameter formats, tool selection, and invocation order are correct.
- Long-term Consistency: Whether the goal remains consistent throughout an execution process of a dozen or more steps.
- Error Self-healing Ability: The ability to locate the cause and adjust the strategy after encountering a failure.
- Cost and Latency: The number of tokens consumed, invocation count, and time spent per completed task.
Evaluation design should also be mindful of data contamination. If the content of test tasks appears in the training corpus, scores will be artificially inflated. It is recommended to use a private task set and update it regularly.
7. Engineering Implementation of Visual Self-Check Feedback
For tasks with visual output characteristics, such as front-end pages or 3D modeling, the model can leverage the rendered results for self-checking, forming a “generate-render-observe-correct” loop:
# Schematic: Visual self-check loopdef visual_refine(spec, generator, renderer, critic, max_rounds=3):artifact = generator(spec)for _ in range(max_rounds):image = renderer(artifact) # Render the artifact as an imagereport = critic(image, spec) # Compare the image with the specif report.passed:breakartifact = generator(spec, feedback=report.issues)return artifact
The key to this mechanism lies in the quality of the feedback signal. Evaluation criteria should be quantifiable, such as whether the layout overflows, whether color contrast meets standards, and whether the 3D model geometry is closed. Overly vague feedback leads to unclear correction directions, ironically increasing the number of rounds.
8. Distributed Deployment on Heterogeneous Clusters
The deployment of large models does not rely on a single hardware architecture. Running large models on clusters composed of various accelerator cards requires addressing the following issues:
- Parallel Strategy Selection: Tensor parallelism suits scenarios with heavy single-layer computation, pipeline parallelism suits deep models, and expert parallelism suits MoE structures. Actual solutions are usually a combination of the three.
- Operator Adaptation: Differences exist in matrix operation libraries, fused operators, and precision support across different hardware. Critical operators need to be rewritten or tuned for the target hardware.
- Communication Topology: There is a significant bandwidth gap between intra-machine high-speed interconnects and inter-machine networks. High-frequency communication should be kept within high-bandwidth links whenever possible.
- Numerical Precision Verification: The same model might have minor output deviations on different hardware. Verification through fixed random seeds and layer-by-layer comparison is necessary.
In million-token context scenarios, additional consideration must be given to hierarchical VRAM management, offloading cold data to main memory or lower-tier storage.
9. Recommendations for Engineering Implementation
When selecting and deploying models within an enterprise, the following sequence can be followed:
- Define Task Types: Distinguish between knowledge QA, code generation, workflow automation, and multimodal processing. Different tasks have varying requirements for context length and tool capabilities.
- Establish Private Evaluation Sets: Use real business tasks to measure success rates, costs, and failure modes, rather than relying solely on public leaderboards.
- Control Execution Permissions: Agents should only be granted the minimal set of tools required to complete a task, and write operations should require manual confirmation or audit logging.
- Build an Observability System: Log the inputs, tool invocations, returned results, and time consumption for each step to facilitate error localization and cost optimization.
- Design Fallback Plans: When model outputs are unstable or costs exceed limits, be able to switch to rule-based systems or smaller models.
10. Conclusion
The value of execution-oriented large models lies in their comprehensive ability for long-term planning, tool invocation, and environmental feedback. At the architectural level, mixed attention and sparse activation provide adjustable trade-offs between computational efficiency and VRAM usage. At the engineering level, VRAM management for long contexts, safety constraints in the agent execution loop, visual feedback loops, and parallel adaptation on heterogeneous clusters constitute the main challenges of implementation.
For developers and enterprises, the key is to evaluate models using metrics close to real-world business scenarios, and to establish clear boundaries regarding permissions, costs, and observability. Only then can model capabilities be reliably transformed into productivity.
