Engineering Practices for Sparse Attention and Reinforcement Learning of AI Agents
This article examines four engineering approaches that recent open-source large language models use to reconcile growing model capability with rising compute costs: sparse Mixture-of-Experts architectures that decouple total parameters from per-token compute, attention optimizations including Multi-head Latent Attention and per-head orthogonalization, sparse attention for reducing quadratic long-sequence costs, and fully asynchronous reinforcement learning frameworks for agent training. It also covers training data staging, how to interpret benchmark results, and practical adoption guidance.
1. Background: Growing Capability vs. Rising Compute Costs
The capability of large language models grows mainly through three levers: more parameters, more training data, and longer context. All three push up training and inference costs. More parameters increase memory and communication pressure. Longer context makes attention computation grow at nearly quadratic cost. The key engineering question, therefore, is how to find a balance between parameter scale and compute cost.
A recent wave of open-source LLMs offers several clear paths: use sparsely activated architectures to expand total parameters without proportionally increasing per-inference cost; use structured attention compression to reduce memory footprint; use sparse attention to cut computation on long sequences; and use asynchronous training frameworks to improve reinforcement learning efficiency for agent tasks. The following sections cover these four layers in turn.
2. Sparse Mixture of Experts: Separating Total and Activated Parameters
Mixture of Experts (MoE) splits the feed-forward network into multiple “expert” subnetworks, and each input token is routed to only a few of them. Total parameter count is determined by all experts, while a single forward pass only uses the selected subset.
Using figures from the source material as an example: the model has roughly 744B total parameters with about 40B activated per inference, 256 experts, and 80 layers. Compared with the previous generation, total parameters grew from about 355B to 744B, while activated parameters rose only from about 32B to 40B. The activation ratio dropped from roughly 9% to about 5.4%. In other words, model capacity more than doubled, while per-token compute increased by only about a quarter.
The core routing logic can be illustrated with the following schematic code (for understanding the principle only, not any specific implementation):
def moe_forward(x, router, experts, top_k=8):# The router scores every expert for each tokenscores = router(x) # [num_experts]top_idx = topk_indices(scores, top_k) # Select only the top_k highest-scoring expertsweights = softmax(scores[top_idx]) # Normalize to obtain combination weightsout = 0for i, w in zip(top_idx, weights):out += w * experts[i](x) # Only selected experts participate in computationreturn out
The main engineering challenge of MoE is load balancing. If routing persistently favors a few experts, some become overloaded while others sit idle. Training typically adds auxiliary losses or bias-adjustment mechanisms to distribute tokens more evenly across experts.
3. Optimizing the Attention Mechanism
3.1 Multi-head Latent Attention and KV Cache Compression
In autoregressive generation, the keys and values of every historical token must be cached. This KV cache grows linearly with context length and is often the dominant source of memory usage in long-context inference. Multi-head Latent Attention (MLA) projects keys and values into a low-dimensional latent vector first; only this compressed representation is cached, and it is reconstructed when needed. This significantly shrinks the per-token cache footprint and improves throughput in long-text scenarios.
3.2 Head-Level Orthogonalization
During training, the team observed a problem: when the optimizer used matrix-based orthogonalized updates, MLA training lagged behind the simpler Grouped-Query Attention (GQA) scheme.
The issue lay in the granularity of orthogonalization. The original approach orthogonalized the entire projection matrix as a whole, treating the weights of different attention heads as a single unit, so the scales and directions of different heads interfered with each other. The improved approach splits the projection matrix by attention head and orthogonalizes each head independently. Each head’s update then happens within its own subspace, and the magnitude of each update is more controllable.
Schematic code:
def per_head_orthogonalize(W, num_heads):# W: [d_model, num_heads * head_dim]head_dim = W.shape[1] // num_headsblocks = []for h in range(num_heads):Wh = W[:, h * head_dim:(h + 1) * head_dim]blocks.append(orthogonalize(Wh)) # Orthogonalize each head independentlyreturn concat(blocks, axis=1)
The value of this change is that it shows the optimizer and the attention architecture need to be designed together. Swapping the optimizer alone, or changing the attention structure alone, does not necessarily yield gains.
3.3 Multi-Token Prediction
Conventional language model training predicts only the next token. Multi-token prediction trains the model to predict tokens at multiple future positions simultaneously. This has two benefits: each position provides richer supervision signals during training, and at inference time the extra prediction heads can be used for draft generation, accelerating decoding when combined with a verification step.
4. Sparse Attention: Reducing Compute on Long Sequences
In standard attention, every query computes similarity against all keys, so computation grows quadratically with sequence length. Sparse attention selects only a subset of the most relevant keys for each query.
A common approach adds a lightweight indexing module that quickly picks the top-scoring keys for each query, then runs exact attention over that subset. Complexity can drop from quadratic to near-linear (proportional to sequence length times the number of keys selected per query).
The source material provides one comparison: after continued training on roughly 20B tokens, the sparse-attention version approached the effect achieved by another scheme trained on about 943.7B tokens. This suggests sparse attention can not only save compute but also transfer the capabilities of an existing model through a small amount of adaptation training. This figure comes from the source material; actual results still need to be validated on your own tasks.
5. Pre-training Data and Training Stages
According to the source material, the model’s pre-training data grew from about 23T tokens in the previous generation to about 28.5T tokens, of which roughly 27T went to the pre-training stage and about 1.5T to a mid-training stage.
Mid-training usually refers to a transitional phase between general pre-training and post-training. Its data tends to favor high-quality corpora, long text, and data related to target capabilities, strengthening specific abilities before formal alignment. Listing this phase separately indicates that data composition and training-stage design have become part of model capability design itself.
6. Fully Asynchronous Reinforcement Learning for Agents
6.1 The Bottleneck of Synchronous Training
Reinforcement learning training broadly consists of two steps: generating trajectories (rollouts) with the current policy, then updating the policy with those trajectories. In agent scenarios, a single trajectory may involve multiple tool calls and environment feedback, with highly variable latency. Synchronous training must wait for the slowest trajectory in a batch to finish, leaving substantial compute idle.
6.2 The Fully Asynchronous Architecture
A fully asynchronous architecture decouples generation from training. The generation side continuously produces trajectories and writes them into a queue; the training side samples from the queue to update parameters, and the updated parameters are then synced back to the generation side. Because trajectories may come from slightly older policy versions, training requires off-policy correction—for example, using importance sampling ratios to clip the magnitude of policy updates.
# Generation side: continuously produce trajectoriesdef rollout_worker(policy_getter, env, buffer):while True:policy = policy_getter() # Fetch the latest or a recent parameter versiontraj = run_agent_episode(policy, env)buffer.put(traj)# Training side: sample from the buffer and updatedef trainer(buffer, policy, optimizer):while True:batch = buffer.sample_batch()loss = ppo_like_loss(policy, batch) # Includes importance sampling correctionoptimizer.step(loss)publish_weights(policy) # Publish new parameters to the generation side
6.3 Infrastructure Problems to Solve
To run this architecture stably, the infrastructure must address several categories of problems:
- High-throughput inference: the generation side must batch-process large numbers of concurrent agent sessions.
- Weight synchronization: latency and bandwidth for transferring parameters from the training side to the generation side must be controlled.
- Fault tolerance: a single environment or tool-call failure must not bring down the entire training job.
- Data versioning: record which policy version produced each trajectory, to support off-policy correction and debugging.
The source material notes that the team built its own RL infrastructure for this purpose. For most teams, it is feasible to assemble these modules from general-purpose components first and replace them gradually as bottlenecks emerge.
7. How to Read Benchmark Results
The source material states that the model scored 50 on a third-party composite evaluation index, ranking first among open-source models, and that on a public human-preference comparison platform it ranked first among open-source models in both text and coding categories, placing it overall in the same tier as several leading closed-source models.
Three caveats apply when reading such data: composite indices are weighted aggregates of subtasks, and rankings shift with different weightings; evaluation settings (prompts, sampling parameters, tool configurations) significantly affect scores; and human-preference evaluations reflect conversational experience, which is not the same as task completion rates in engineering work. When selecting a model, it is advisable to reproduce comparisons under identical conditions using real samples from your own business.
8. Practical Recommendations
- Identify the bottleneck first: if long-context memory is insufficient, prioritize KV cache compression; if long-sequence computation is slow, then consider sparse attention.
- Validate architecture and optimizer together: after changing the attention structure, check whether the optimizer’s granularity and hyperparameters still match.
- Bring MoE load-balancing metrics into monitoring, and watch the distribution of expert utilization.
- For agent reinforcement learning, first eliminate idle resources between generation and training, then optimize individual algorithms.
- Evaluate every technical change against a fixed benchmark suite and baseline, so evaluation noise is not mistaken for improvement.
What these practices share is treating model architecture, training methodology, and infrastructure as an integrated design problem, rather than tuning each in isolation.
