Agent LLM Architecture Design and Systems Engineering: A Practical Implementation Guide
This guide explains the engineering logic behind agent-capable large language models from three perspectives: architecture, deployment, and evaluation. It covers sparse activation with Mixture of Experts, hybrid attention and KV cache memory budgeting for long contexts, distributed deployment strategies, and an evaluation framework for execution-oriented tasks. All figures are illustrative values for order-of-magnitude estimation; production projects must re-measure on their own hardware, model versions, and workloads.
1. Problem Statement and Scope
Over the past two years, LLM evaluation has focused largely on knowledge Q&A and reasoning benchmarks. Once models are integrated into business systems, a different set of capabilities determines real-world effectiveness: understanding a goal, decomposing it into steps, calling external tools, reading execution results, correcting the plan, and finally delivering verifiable output. These are commonly referred to as agent capabilities.
Models designed for execution-oriented tasks differ from general conversational models in training data, inference structure, and evaluation methodology. This article reviews the engineering logic across three layers—architecture, deployment, and evaluation—to help readers assess cost and risk when selecting or building models.
All numbers in this article are illustrative values used to demonstrate orders of magnitude and calculation methods. They contain no measured performance data. Real projects must re-measure using their own hardware, model versions, and business workloads.
2. Sparse Activation: Trading Parameter Capacity for Compute Efficiency
2.1 Total Parameters vs. Activated Parameters
Model scale is usually described in two ways. Total parameters represent the full volume of model weights, determining knowledge capacity and the capability ceiling. Activated parameters are those actually involved in computing a single token’s forward pass, which directly determine the compute cost and latency of each inference step.
The Mixture of Experts (MoE) architecture splits the feed-forward network into multiple expert subnetworks, with a router selecting only a few experts per token. The model thus retains large parameter capacity while keeping per-step compute under control.
Suppose a model has 300B total parameters and activates 20B per token—an activation ratio of about 6.7% (20 ÷ 300). If compute is roughly proportional to activated parameters, the per-token forward cost is approximately that of a 20B dense model. The 6.7% figure is only an order-of-magnitude illustration. Actual cost also includes routing, cross-device communication, and memory reads.
2.2 Routing and Load Balancing
If the router dispatches most tokens to a few experts, some compute units sit idle while others are overloaded. Two common approaches address this: auxiliary losses, which add a load-balancing penalty term to the training objective; and auxiliary-loss-free bias adjustment, which dynamically adjusts a bias term in the routing scores based on each expert’s recent load during training or inference. The bias affects only expert selection, not the weighting coefficients of selected experts.
Below is a simplified top-k routing illustration:
function topk_route(hidden, router_weight, k, eps=1e-9):# hidden: hidden vector per token, shape [tokens, d_model]# router_weight: routing matrix, shape [d_model, num_experts]# k: number of experts selected per token, typically 2 to 8,# determined by the model architecturelogits = matmul(hidden, router_weight)# subtract the row max before softmax to avoid exponential overflowlogits = logits - max(logits, axis=-1)probs = softmax(logits, axis=-1)top_idx, top_probs = topk(probs, k, axis=-1)# renormalize the weights of selected experts; eps prevents division by zerotop_probs = top_probs / (sum(top_probs, axis=-1) + eps)return top_idx, top_probs
Before going live, record the token count for each expert at each layer and compute the ratio of maximum to average load. A persistently high ratio indicates the routing needs adjustment.
2.3 The Right Way to Estimate Cost
Looking only at parameter scale or unit price easily leads to wrong conclusions. Two models with the same unit price can differ greatly in actual cost if one has higher communication overhead. Use the table below to record every comparison, fixing hardware, precision, batch size, and sequence length.
| Metric | Measurement Method | Why It Matters |
|---|---|---|
| Compute | GPU-seconds per million output tokens, with fixed hardware and precision | The base quantity driving compute cost |
| Memory | Peak of weights, KV cache, and activations, with fixed batch and sequence length | Determines concurrent capacity per GPU |
| Communication | Bytes transferred across devices per token, counted by layer and direction | Determines MoE scalability across GPUs |
| Concurrent throughput | Output tokens per second within an agreed latency ceiling | Determines output capacity per unit time |
| Cost per million tokens | Hardware hourly price × elapsed time ÷ output tokens | Combines the above into a final comparison metric |
3. Hybrid Attention and Long-Context Memory
3.1 The Bottleneck of Standard Attention
Standard self-attention has compute cost proportional to the square of sequence length, while the KV cache grows linearly with sequence length. At hundreds of thousands or millions of tokens, both become bottlenecks simultaneously.
3.2 Combining Linear and Sparse Attention
Linear attention reduces computational complexity to approximately linear in sequence length, but has weaker expressiveness for precise retrieval tasks. Sparse attention computes relationships only between selected positions, preserving local precision.
A common hybrid scheme: most layers use linear or sliding-window attention to handle the bulk of long-range context, while a few layers retain global attention for precisely locating critical passages.
Applicable boundaries must be confirmed through evaluation. The following cases require focused validation: tasks relying on precise cross-paragraph references, such as contract clause comparison; tasks requiring verbatim reproduction of distant content; and cases where key information sits at both ends of the window. In these scenarios, compare retrieval accuracy before and after reducing the number of global attention layers, rather than looking only at average perplexity.
3.3 KV Cache Memory Estimation
The KV cache is one of the main memory costs of long-context inference. Consider this example configuration: 64 layers, 8 KV heads, head dimension of 128, stored in 16-bit precision (2 bytes per value).
- KV cache size per token: 2 (K and V separately) × 64 (layers) × 8 (KV heads) × 128 (head dimension) × 2 bytes = 262,144 bytes, roughly 256 KiB.
- At 1,000,000 tokens, the KV cache alone requires about 262 GB (using 1 GB = 10⁹ bytes; about 244 GiB). This does not yet include model weights, intermediate activations, or runtime fragmentation.
Concurrent requests scale the KV cache proportionally. Memory usage on one GPU can be roughly expressed as: model weights + concurrency × per-request KV cache + activation peak + reserved headroom. Therefore, fitting a single long-context request does not mean concurrent requests of the same length will fit.
3.4 Memory Optimization Checklist
- Grouped-Query Attention (GQA) or Multi-Query Attention (MQA): Multiple query heads share the same set of KV heads, directly reducing cache size. This change usually must be decided during training and cannot be freely modified at inference time.
- KV cache quantization: Compressing the cache from 16-bit to 8-bit (e.g., FP8 or INT8) can roughly halve cache size. Precision loss must be evaluated separately on retrieval and long-text tasks, not just on general benchmarks.
- Paged management: Split the KV cache into fixed-size pages allocated on demand, reducing memory fragmentation caused by varying sequence lengths.
- Offloading to host memory or SSD: Moving cold data off the GPU expands the supportable context but increases access latency—suitable for offline tasks insensitive to time-to-first-token.
- Business-side compression: Summarize conversation history and place stable knowledge in a retrieval store rather than stuffing everything into the prompt. Window length is a capability ceiling; it does not mean every call should fill the window.
- Concurrency and batch control: Set maximum concurrency and maximum sequence length according to the memory budget. Requests exceeding the budget should be queued or rejected to avoid out-of-memory failures mid-run.
Estimation boundary: the figures above cover only the KV cache. Before launch, add weights, activations, communication buffers, and framework overhead to the budget, and measure peak memory on the target hardware.
4. Key Steps in Distributed Deployment
4.1 Parallelism Strategies
- Tensor Parallelism (TP): Splits a single layer’s matrices across multiple GPUs within the same node. Communication is frequent, so TP is usually confined to nodes with high-speed interconnects.
- Expert Parallelism (EP): Places different experts on different devices. Each token is sent to the devices hosting its selected experts, and results are gathered back—an All-to-All communication pattern.
- Pipeline Parallelism (PP): Splits the model by layers, suitable for cross-node deployment, but introduces pipeline bubbles that require micro-batch scheduling to reduce idle time.
- Data Parallelism (DP): Distributes requests across multiple replicas to scale throughput; it does not reduce per-replica memory usage.
The partitioning scheme should be determined first by the memory budget, then by communication overhead. Prefer TP and EP within a node; prefer PP and DP across nodes.
4.2 Communication Topology and Bandwidth Estimation
Take one All-to-All in an MoE layer as an example: each token is sent to k experts, with each hidden vector computed in 16-bit precision. Assuming a hidden dimension of 8192 and k = 8, the one-way data volume per token per layer is approximately:
8192 × 2 bytes × 8 = 131,072 bytes, roughly 128 KiB.
This happens once for sending and once for receiving, at every layer. Actual data volume also depends on deduplication, compression, and how evenly experts are distributed. Compare the estimate against interconnect bandwidth to judge whether communication will become a bottleneck. Before deployment, use collective communication benchmarking tools to measure actual bandwidth and latency on the target topology, rather than relying on vendor-specified values.
4.3 Memory and Throughput Stress Testing
Stress testing proceeds in three steps.
- Single-request baseline: Fix one input length and one output length; record time-to-first-token, per-output-token latency, and peak memory.
- Concurrency sweep: Gradually increase concurrency; record throughput and tail latency (p95, p99) to find the maximum concurrency that meets the latency ceiling.
- Long-tail scenarios: Use the longest real inputs, longest outputs, and most complex tool-call chains to confirm the system does not crash or accumulate timeouts under extreme conditions.
Stress test data should be preserved and archived together with the model version, framework version, driver version, and configuration to enable regression comparison.
4.4 Failure Recovery and Rollback
- Health checks: Periodically check memory, queue length, and error rate for each inference instance; promptly remove abnormal instances from service.
- Request retries: Automatically retry only idempotent requests. Tool calls involving write operations must not be blindly retried—query the execution status first.
- Checkpoints and session recovery: Intermediate state of long tasks (plans, completed steps, tool results) should be persisted so that after a process restart, execution can resume from the most recent step.
- Version rollback: Models, prompts, and tool descriptions should all be versioned. When a new version shows quality or cost anomalies, it should be possible to switch back to the previous version quickly.
4.5 Launch Checklist
- The memory budget includes weights, KV cache, activations, and runtime overhead, and has been measured on the target hardware.
- Maximum concurrency and maximum sequence length are capped, with a clear rejection or queuing policy for requests exceeding limits.
- Communication bandwidth has been measured on the target topology and compared against estimates.
- The stress test report includes tail latency, throughput, and peak memory, archived alongside the model version.
- Health checks, alerting, and automatic instance removal rules are configured and have been rehearsed once.
- Rollback steps are documented and switchover time has been verified.
- Logs do not record raw user input, keys, tokens, or personally identifiable information. Logs must be redacted before being written to disk, with a defined retention period.
- Tool calls follow least privilege; high-risk actions such as writes, fund transfers, permission changes, or external sends require human confirmation.
- Model-generated code or commands run in a sandbox and never touch production environments directly.
5. Evaluation and Implementation Framework for Execution-Oriented Tasks
5.1 Core Metrics
- Task success rate: Whether the task ultimately meets its acceptance criteria. Acceptance criteria should be written before the task starts and determined by automatically verifiable conditions or human review.
- Tool-call correctness: Whether the right tool was selected, whether parameters are complete and correctly typed, and whether returned results are used properly.
- Step count and recovery rate: How many steps a task takes on average; whether the agent can self-correct and complete the task after tool errors or abnormal intermediate results.
- Cost and latency: Input and output tokens per task, number of tool calls, and median and p95 end-to-end latency.
- Safety incident rate: Occurrences of unauthorized calls, sensitive information leakage, and unconfirmed high-risk operations.
Metrics can pull against each other—for example, reducing step count may lower success rate—so they should be observed together.
5.2 Steps to Establish a Baseline
- Collect task samples: Extract a batch of tasks from real business scenarios, covering common paths, edge cases, and failure cases. Samples must be stripped of sensitive data or used in a controlled environment.
- Define acceptance criteria: Write success conditions for each task type, using automatically judgeable rules wherever possible.
- Fix the environment: Record model version, prompt version, tool version, and random seed to ensure consistent evaluation conditions.
- Run and record: Run the baseline version on the samples and save complete execution traces, including each step’s plan, calls, and returned results.
- Manual spot-checks: Review a sample of automatically judged results to estimate the error rate of automatic scoring.
- Produce a baseline report: Record metric values with confidence ranges as the reference for future comparisons.
5.3 Regression Sets and Change Gates
A regression set is a fixed group of tasks selected from baseline samples, covering historically observed failure cases. Every change to the model, prompts, tools, or routing strategy must be re-run against the regression set.
Suggested change-gate rules: success rate must not fall below baseline, safety incident rate must not increase, and cost and latency growth must stay within pre-agreed bounds. If any condition fails, the change does not enter the launch pipeline.
Evaluation samples become outdated as the business evolves. Teams should regularly add new samples and retire those that no longer represent real scenarios.
The architectures and long-context costs discussed in this article can be used directly for project estimation. Actual figures must be based on measurements with the target hardware and real workloads.
