Architecture Design and Tool-Calling Optimization for a Trillion-Parameter Agent Model

    This article explores the architecture design and tool-calling optimization of a trillion-parameter agent model. It details structural choices, including the Mixture of Experts (MoE) architecture and Multi-head Latent Attention (MLA) mechanism, and provides a method for estimating inference costs across different deployment scales. Additionally, it outlines a systematic approach to synthesizing agent training data and introduces an evaluation framework to diagnose model performance across varying task complexities in tool calling.

    1. Background: From Answering Questions to Executing Tasks

    Early large language models primarily focused on text generation. Agent scenarios, however, impose higher requirements on models: they must understand user goals, select appropriate tools, initiate calls with correct parameter formats, and plan the next actions based on returned results. These capabilities are commonly referred to as function calling and multi-step decision planning.

    Achieving these capabilities requires addressing three key aspects. First, model structure, which must balance parameter scale and inference cost. Second, training data, where tool-calling trajectories need to cover a sufficient variety of interfaces, scenarios, and exception cases. Third, evaluation, which must diagnose the model’s performance in single-step calls, ambiguous instructions, and multi-turn collaboration. The following sections elaborate on these three dimensions.

    2. Model Architecture Design

    2.1 Parameter Scale and Expert Count

    The model adopts a Mixture of Experts (MoE) architecture. The total parameter count is approximately 1 trillion, representing a 49% increase compared to the 671 billion of a similar baseline. This growth primarily stems from the number of experts, which increased from 256 to 384 per layer, a 1.5x growth.

    The direct benefit of increasing expert count is that the model can learn a finer division of capabilities. Different experts can focus more on patterns such as code, math, multilingual processing, or formatted output. However, more experts also bring increased VRAM usage and routing communication pressure, making inference scheduling strategies crucial.

    2.2 Attention Structure Reduction

    The model retains the Multi-head Latent Attention (MLA) mechanism, which reduces the Key-Value cache size through low-rank compression. Compared to the baseline, the number of attention heads is reduced from 128 to 64.

    Halving the number of heads brings two changes. First, attention computation decreases almost linearly with the head count, reducing computational costs in long-sequence scenarios. Second, parameters related to attention projection are reduced, which is one reason activated parameters dropped from approximately 37 billion to 32 billion. It is worth noting that fewer heads weaken the model’s ability to simultaneously attend to multiple relationships within the same layer; thus, the expressive power must be compensated through expert count and training data.

    2.3 Dense and Sparse Layer Distribution

    Most MoE models retain dense feed-forward networks in the initial layers to stabilize the extraction of foundational features. This model only retains the first layer as a dense layer, while all other layers utilize sparse expert routing. This approach allows more layers to participate in expert division but imposes higher requirements on routing stability.

    2.4 Training Data and Optimizer

    Training data volume increased from approximately 14.8 trillion tokens to 15.5 trillion tokens, a 4.7% increase. The growth in data volume is significantly smaller than the growth in parameters, indicating that this iteration focuses on structural expansion and data quality rather than simply stacking data.

    Regarding the optimizer, the model utilizes a matrix orthogonalization-based optimizer and incorporates an attention score clipping mechanism. The clipping limits abnormal growth in attention logits, thereby suppressing the numerical instability issues common in large-scale training. Such practices have become mature experiences in ultra-large model training.

    3. Inference Cost Estimation

    3.1 Estimating Computation Using Activated Parameters

    The inference computation of an MoE model is primarily determined by activated parameters rather than total parameters. The table below outlines the key metrics for the two configurations.

    Metric Baseline Configuration This Model Change
    Total Parameters 671B 1T ~+49%
    Activated Parameters 37B 32B ~-13.5%
    Total / Activated Parameters ~18x ~31x Sparsity significantly increased
    Experts per Layer 256 384 1.5x
    Attention Heads 128 64 Halved

    The increased sparsity means each token utilizes only a small fraction of the parameters. The computational cost per inference is therefore close to that of a smaller dense model, while the model’s knowledge capacity still stems from all parameters.

    3.2 Cost Differences Across Deployment Scales

    Inference cost is closely related to deployment scale and can be categorized into three scenarios:

    • Large-scale clusters (128+ GPUs): Experts can be distributed across multiple GPUs, with fewer experts per GPU, allowing batching to be fully utilized. With appropriate scheduling strategies, the cost per token can approach that of the baseline.
    • Small-scale deployments (~16 GPUs): All expert weights must fit into limited VRAM. After the increase in total parameters, weight usage rises synchronously, and cross-GPU communication from expert partitioning also increases. If the service goal is low latency (i.e., a short Time Per Output Token, or TPOT), batching cannot sufficiently amortize the overhead, resulting in a significantly higher unit cost compared to large-scale deployments.
    • Medium-scale deployments: This requires continuous tuning among GPU count, batch size, and latency targets. A common practice is to determine the acceptable concurrency based on the latency target first, and then reverse-calculate the required number of GPUs.

    For actual selection, it is recommended to perform capacity estimation using target traffic and latency metrics first, and then confirm the results with load testing using real traffic.

    4. Agent-Oriented Data Synthesis System

    4.1 Four Design Goals

    Agent training data must meet four goals:

    1. Diversity: Cover different domains, interface types, parameter structures, and user expressions.
    2. Scalable: Capable of batch generation programmatically, without relying on manual writing of individual entries.
    3. Realistic: Interface parameter constraints, return formats, and error messages should closely resemble real systems.
    4. Interactive: Trajectories should include multi-turn calls, feedback, and corrections, rather than single Q&A.

    These four goals jointly determine the quality, quantity, and variety of trajectories. Lacking any one of them may cause the model to deviate in real-world environments.

    4.2 Hierarchical Virtual API Pool

    When constructing the API pool, a common practice is to organize it hierarchically by domain. First, divide into major domains, then sub-divide into sub-domains, and finally define specific function signatures, parameter types, value constraints, and example calls at the leaf nodes. The domain structure can reference real industry classifications, such as finance, legal, healthcare, and e-commerce, with each sub-domain containing several functional modules.

    The code below demonstrates how to flatten a hierarchical structure into a flat API list for subsequent sampling:

    1. def build_api_pool(tree: dict) -> list[dict]:
    2. """Flatten the hierarchical domain tree into a flat API spec list."""
    3. pool = []
    4. def walk(path: list[str], node):
    5. # Leaf nodes are API spec lists
    6. if isinstance(node, list):
    7. for spec in node:
    8. pool.append({"domain": "/".join(path), **spec})
    9. return
    10. for key, child in node.items():
    11. walk(path + [key], child)
    12. walk([], tree)
    13. return pool

    In actual construction, an LLM can generate candidate signatures based on interface documentation, followed by filtering through rules and manual spot-checking. This approach both broadens coverage and controls the entry of erroneous interfaces into the training set.

    4.3 Trajectory Generation and Validation

    When generating trajectories, one model typically acts as the user, another as the agent, and a simulator returns tool results. After a trajectory is completed, it must undergo programmatic validation to prevent erroneous samples from polluting the training data.

    The following code shows the basic validation logic, checking whether the tool name exists and whether all required parameters are present:

    1. def validate_trajectory(traj: dict, schema_index: dict) -> tuple[bool, str]:
    2. for step in traj["steps"]:
    3. if step["type"] != "tool_call":
    4. continue
    5. spec = schema_index.get(step["name"])
    6. if spec is None:
    7. return False, f"Unknown tool: {step['name']}"
    8. missing = [p for p in spec.get("required", []) if p not in step["arguments"]]
    9. if missing:
    10. return False, f"Missing required parameters: {missing}"
    11. return True, "Passed"

    Building on this, parameter type checks, return result consistency checks, and diversity statistics can be added to progressively improve trajectory quality.

    5. Tool-Calling Evaluation Framework

    A good evaluation framework needs to pinpoint where problems occur. A common approach divides tasks by difficulty into three categories:

    Category Evaluation Focus Typical Scenarios
    Basic Call (Normal) Whether a single call is correct and parameters are complete Single retrieval, simple calculation
    Ambiguous Instruction (Special) Whether the right tool is selected and parameters reasonably inferred when instructions are unclear User provides only a vague request
    Multi-step Collaboration (Agent) Multi-step planning, task decomposition, result integration, and long-conversation state management Complex cross-tool tasks

    These three categories form a complete gradient from static calls to multi-turn collaboration. Basic calls reflect the model’s format adherence ability, ambiguous instructions reflect inference and clarification abilities, and multi-step collaboration reflects planning and state management abilities. Evaluation results should be reported separately by category to avoid masking shortcomings with a single total score.

    6. Engineering Practice Recommendations

    1. Clarify target scenarios before deciding structural scale: If the deployment environment is a small-scale cluster, prioritize evaluating latency and VRAM budgets rather than just looking at parameter count.
    2. Balance quantity and quality in data synthesis: As interface coverage expands, validation rules and spot-checking processes must be upgraded synchronously.
    3. Split evaluations by capability level and retain failure samples: Failure samples are often more instructive for the next round of data construction than total scores.
    4. Conduct replay tests with real traffic before launch: Observe metrics like tool-call error rate, missing parameter rate, and average number of turns before deciding to scale up deployment.