Sparse Large Models for AI Agents: Evaluation, Training, and Deployment Considerations
This article explains how to evaluate agent capabilities, estimate the compute and memory costs of sparse MoE models and long-context inference, and design post-training data, environments, and rewards for reliable multi-step tool use. It covers task completion, tool-call success, error recovery, expert load balancing, KV-cache optimization, and hybrid attention trade-offs.
1. Background and Evaluation Metrics
Large language models were traditionally evaluated mainly on knowledge-based question answering and difficult reasoning problems. Once models are connected to code repositories, terminals, office systems, and web browsers, the evaluation question changes: can the model call tools during multi-step tasks, handle intermediate failures, and deliver the final result? These capabilities are commonly referred to as agent capabilities.
Changes in the training objective directly affect evaluation results. Improvements in general knowledge depend mainly on the scale and quality of pretraining data, while multi-step execution depends more on task trajectories, environment interaction, and verifiable rewards during post-training. As a result, the same model may show limited gains on knowledge benchmarks but significant improvements in tool use and automation tasks. This divergence usually indicates a shift in training priorities rather than a simultaneous improvement in every capability.
Agent performance can be evaluated using the following four metrics:
- Task completion rate: The percentage of tasks that are delivered end to end and pass the acceptance criteria.
- Tool-call success rate: The percentage of calls with correct parameters that complete successfully out of all tool calls.
- Error recovery rate: The percentage of tasks the model completes after a tool error or environmental failure.
- Average number of steps: The average number of interaction turns required to complete similar tasks. The number of steps directly affects token usage, latency, and cost.
These metrics can only be compared fairly when the task set, environment version, and acceptance scripts are fixed. Once the environment changes, the results are no longer directly comparable.
2. Sparse Architectures and Long-Context Costs
2.1 Total Parameters and Active Parameters
In a dense model, all parameters participate in computation for every generated token. A mixture-of-experts (MoE) architecture divides the feed-forward layers into multiple expert subnetworks. A router selects only a small number of experts for each token. This allows the model to have a large total parameter count while keeping the number of active parameters per token relatively small.
Under a commonly used estimate, the forward-pass cost for one token is approximately 2N FLOPs, where N is the number of active parameters and attention computation is excluded. Consider a configuration with 200 billion total parameters and 15 billion active parameters. Its per-token compute is approximately:
3 × 10¹⁰ FLOPs
This is close to that of a dense model with a similar active parameter count. However, weight storage must be planned according to the total parameter count. With BF16 weights, at two bytes per parameter, the weights alone require approximately 400 GB of GPU memory.
Compute cost is determined by active parameters, while memory capacity and weight-distribution cost are determined by total parameters. These two dimensions must be accounted for separately.
The core routing logic can be represented by the following simplified pseudocode. Functions such as topk_indices and softmax are assumed to have been implemented, so this code is not directly executable:
def moe_forward(x, router, experts, top_k=2, capacity=None):scores = router(x) # Score for each expertidx = topk_indices(scores, top_k) # Select the top-k expertsweights = softmax(scores[idx]) # Normalize the weightsout = 0for i, w in zip(idx, weights):if capacity is not None and expert_load[i] >= capacity:continue # Simplified: drop or reroute the tokenout += w * experts[i](x) # Compute only the selected expertsreturn out
2.2 MoE Load Balancing
If a large number of tokens are routed to only a few experts, the devices hosting those experts become bottlenecks while other devices remain underutilized. This reduces overall throughput and can increase tail latency.
Common approaches include an auxiliary load-balancing loss, per-expert capacity limits, and dropping or rerouting tokens that exceed capacity. The capacity can be calculated as follows:
Capacity per expert = capacity factor × (tokens per batch × top_k ÷ number of experts)
For example, assume a batch contains 4,096 tokens, top_k is 2, and there are 64 experts. The average load per expert is:
4,096 × 2 ÷ 64 = 128 tokens
If the capacity factor is 1.25, the maximum capacity per expert is:
128 × 1.25 = 160 tokens
Tokens beyond this limit are either dropped or routed to another expert.
A capacity factor that is too small causes more tokens to be dropped and reduces model quality. A factor that is too large fails to adequately address load imbalance. The weight of the auxiliary loss also requires careful tuning: a weight that is too large can interfere with the primary training objective, while a weight that is too small may not prevent expert concentration.
At a minimum, monitor the following metrics:
- Expert utilization: The distribution of tokens processed by each expert, including whether the maximum-to-average load ratio remains within an acceptable range.
- Capacity drop rate: The percentage of tokens that are not processed because an expert exceeds its capacity.
- Auxiliary-loss weight: Quality and balancing metrics under different weight settings.
- Rerouting hit rate: The percentage of rerouted tokens that successfully find an available expert.
2.3 How Does Hybrid Attention Reduce Long-Context Costs?
The computational cost of standard self-attention grows quadratically with sequence length n, and the attention score matrix has a size of n². Direct computation becomes impractical when the context reaches millions of tokens.
The KV cache is another major bottleneck during inference. Its memory usage can be estimated with the following formula:
KV-cache bytes ≈ 2 × number of layers × number of KV heads × head dimension × sequence length × bytes per element
The factor of 2 represents the two cached tensors, K and V. Assume a model has 60 layers, 8 KV heads, a head dimension of 128, and uses BF16 values. The KV cache for a single request with a 128K-token context is approximately 32 GB.
This figure includes only the KV cache. It excludes model weights, activations, additional memory required by batching and concurrency, and memory reserved by the framework or lost to fragmentation.
Hybrid attention uses linear attention or sliding-window and other sparse-attention mechanisms in most layers, while retaining standard global attention in only a small number of layers. The two types of layers have different memory characteristics:
- The state size of linear attention is fixed and does not grow with sequence length.
- The cache of sparse attention is limited by the window size.
- Standard attention layers preserve global dependencies and are the primary source of precise long-range retrieval.
The following table shows a simplified linear estimate under hypothetical conditions. The model has 60 layers, with one standard-attention layer retained every four layers. KV cache for the other layers is assumed to be zero. The state used by the linear-attention layers is not included, so the actual benefit must be measured in practice.
| Sequence Length | Concurrency | All Standard Attention (Estimated) | One Standard-Attention Layer Every Four Layers (Estimated) |
|---|---|---|---|
| 32K | 1 | 8.1 GB | 2.0 GB |
| 128K | 1 | 32.2 GB | 8.1 GB |
| 128K | 8 | 257.7 GB | 64.4 GB |
| 256K | 1 | 64.4 GB | 16.1 GB |
Selecting the proportion of standard-attention layers requires balancing two factors. First is the memory benefit: fewer standard-attention layers mean a smaller KV cache. Second is precise retrieval capability: too few standard-attention layers can reduce performance on tasks that require locating information over long distances.
This ratio should be determined using the team’s own long-context evaluation set rather than copied directly from another system.
3. Agent Post-Training: Data, Environments, and Rewards
Multi-step execution capabilities are acquired primarily through post-training. The key factors are the structure of the data and the design of the reward.
Task trajectory data is the foundation. A trajectory includes the user instruction, each action taken by the model, the tool response, and the final state. Training data should include failure and recovery examples, such as retries and alternative paths after tool timeouts, malformed responses, or insufficient permissions. A dataset containing only successful examples leaves the model without enough experience to handle exceptions.
Environment interaction is used to generate and validate trajectories.代
