Scaling Post-Training for Trillion-Parameter Models: A Practical Guide

    This article explains how to scale post-training for trillion-parameter Mixture-of-Experts (MoE) models. It covers reinforcement learning infrastructure, long-context inference, training efficiency, sandbox security, scheduling, environment quality checks, evaluation methods, million-token contexts, long-horizon agents, high-throughput inference, and platform requirements. It also provides practical recommendations for turning model improvements into reliable business value.

    1. From Pre-training Scale to Post-training Scale

    Recent model iterations have generally followed a path of “pre-training as the foundation, post-training for targeted improvements.” As high-quality pre-training data becomes scarcer and the cost of each pre-training run continues to rise, simply increasing pre-training compute to gain capability is showing diminishing returns. In contrast, continuous investment in post-training to improve specific capabilities has become another important growth curve.

    In common industry practice, post-training usually includes two types of methods:

    • Supervised fine-tuning: Align model behavior with high-quality instruction data and preference data so the model learns “how to answer.”
    • Reinforcement learning: Introduce reward signals that can be automatically evaluated, allowing the model to learn “how to do” through large numbers of trials.

    This approach is especially feasible for trillion-parameter MoE models, where a trillion means 10^12. Because each forward pass only activates a subset of experts, inference cost is much lower than for a dense model of the same total parameter count. Code tasks are a good example: correctness can often be automatically determined through compilation, unit tests, and execution results, providing reinforcement learning with a natural and reliable reward signal.

    However, scaling post-training is not just about “adding GPUs.” It is fundamentally a systems engineering problem. Insufficient resources slow iteration. If sandbox isolation is weak or environment preparation is slow, the training process itself can expose security risks. Poor task quality can distort reward signals, causing the model to learn to “please the evaluator” rather than “solve the problem.”

    Therefore, teams that want to benefit from large-scale post-training need to refine every layer of the training stack. Only then can newly added reinforcement learning compute be reliably converted into capability improvements.

    2. Building the Foundation: Six Key Optimizations for Post-training Infrastructure

    1. Reinforcement Learning Framework: Making Generation and Training Truly Parallel

    The standard reinforcement learning loop is “generate - score - update,” with each step requiring the current policy model. For long-horizon tasks, a single generation may take tens of seconds or more. Synchronous execution can leave GPUs idle for long periods while waiting.

    Common optimization directions include:

    • Asynchronously decouple generation and training: The generation side continuously produces trajectories, while the training side consumes them continuously.
    • Improve generation-side throughput: For MoE models, focus on load balancing for expert routing.
    • Lightweight weight synchronization: Synchronize new weights to the generation side incrementally.
    • Handle long-tail timeouts: Set step and time budgets for generated trajectories. Partial trajectories can preserve intermediate state, then resume later or be rewarded based on partial completion.

    The following pseudocode illustrates this approach:

    1. # Pseudocode: trajectory scheduling and long-tail recovery in asynchronous RL
    2. def rollout_step(policy, tasks, concurrency, deadline_s):
    3. queue = list(tasks)
    4. results, partial = [], {}
    5. while queue or pending_batches():
    6. # Only fill free slots to avoid the slowest generation slowing down overall throughput
    7. while queue and free_slots() > 0:
    8. launch(queue.pop(0), budget=deadline_s, on_done=collect)
    9. sample_finished(timeout=0.1)
    10. for traj in ready_results():
    11. if traj.finished:
    12. # Complete trajectories go directly to reward computation and gradient updates
    13. results.append((traj, compute_reward(traj)))
    14. else:
    15. # Save intermediate state of partial trajectories for the next round
    16. partial[traj.task_id] = traj.checkpoint()
    17. return results, partial

    2. Long-Context Inference: Control Memory, Optimize Throughput, and Maintain Training-Inference Consistency

    When context length grows from tens of thousands of tokens to millions of tokens, the first bottleneck is often the KV cache, which stores key-value pairs for historical tokens in the attention mechanism. Memory usage grows roughly linearly with context length, and long tasks can easily trigger out-of-memory errors. Common mitigation techniques include:

    • Paged KV cache management to reduce fragmentation;
    • Prefix cache reuse so requests sharing the same context are computed only once;
    • Chunked prefill, which splits very long inputs into smaller chunks and schedules them together with decoding batches, preventing a single long request from blocking all others.

    At the same time, training-side and inference-side behavior must remain consistent. If long-context inference used during post-training differs from online inference, length extrapolation behavior may deviate, making trained capabilities hard to reproduce in production. Long-context capability evaluation during post-training is also essential; otherwise, the model may “hear” long context but fail to use it effectively.

    3. Training Efficiency: Reduce Idle Time and Recover Quickly from Failures

    Training trillion-parameter models may involve thousands of accelerators. Efficiency losses mainly come from three areas:

    • Communication and computation are difficult to overlap: This can be mitigated through pipeline parallelism, sequence parallelism, and communication-computation overlap.
    • Expert load imbalance: Hot experts can cause some devices to wait early.
    • Failures and interruptions: Frequent checkpointing adds storage and I/O overhead.

    In engineering practice, elastic fault-tolerant training and tiered checkpointing are often used together, such as combining in-memory checkpoints with persistent checkpoints. The goal is to compress failure recovery time to the minute level.

    4. Sandbox Infrastructure: Safely Executing Untrusted Code in Isolated Environments

    Code and agent tasks often require executing model-generated commands and code in real environments. This content is inherently untrusted. A sandbox platform should provide:

    • Isolation: Processes, file systems, and networks are isolated from one another;
    • Determinism: Repeated runs of the same task produce consistent results, so reward signals are reproducible;
    • Fast elasticity: When many tasks run concurrently, environments can be created and destroyed in seconds;
    • Environment snapshots: Images should include common runtimes and dependencies, with code repositories and test data mounted as needed;
    • Network allowlists: Tasks can only access necessary package sources and internal services.

    If a team builds its own sandbox, it must assume that model output is untrusted input. Real production credentials must not be injected into the sandbox. Use least-privilege accounts, prohibit access to sensitive internal services, and apply quotas and audits to high-frequency calls.

    5. Scheduling System: Avoid Idle Compute

    Large-scale joint training often includes training, evaluation, environment construction, and other tasks. Resource contention is unavoidable. A good scheduler should:

    • Queue tasks by priority and deadline;
    • Preserve intermediate state when preempting and requeueing tasks;
    • Mix long-running and short-running tasks and use backfilling to improve overall utilization.

    6. Environment Quality Checks: Governing the Source of Reward Signals

    “The reward is the objective.” If the environment is flawed, the model will learn the wrong behavior. Common quality problems include:

    • Tests themselves are flawed, causing correct implementations to fail;
    • Task descriptions do not match expected behavior;
    • Test answers leak into the context, allowing the model to score by copying;
    • Automated validation scripts contain bugs.

    To address this, many teams build shared environment quality-check platforms across multiple teams. These platforms perform tasks such as solvability verification, repeated-run consistency checks, and alignment reviews between tests and descriptions. The goal is to ensure reward signals are trustworthy from the source.

    These six optimizations are tightly coupled: the framework determines iteration speed, long-context support determines task limits, efficiency determines the number of trials, sandboxes define safety boundaries, scheduling determines resource utilization, and environment checks ensure the direction is correct. If any one link fails, additional reinforcement learning compute may be consumed through ineffective trial and error.

    3. How to Evaluate Models: Long-Horizon Tasks Are Changing Evaluation

    Traditional knowledge question answering and single-turn reasoning evaluations are difficult to use as indicators of real work performance. In recent years, evaluation has shifted toward whether an agent can complete a task. Typical benchmarks include:

    Evaluation dimension Typical format What it measures
    Terminal operation tasks Build, debug, and deploy tasks in resource-constrained real terminal environments, with dedicated tests for each problem System understanding, troubleshooting, command composition
    Long-horizon engineering tasks Multi-step execution, tool calls, and end-to-end problem solving across multiple engineering domains Task planning, state tracking, error recovery
    Domain knowledge tasks Research and reasoning tasks based on real-world materials Information integration, argument rigor, traceability
    Visual and 3D creation tasks Web interaction effects, 3D scene construction, and rendering Aesthetic judgment, spatial understanding, engineering implementation

    Evaluation methods themselves are also evolving. Several new consensus points have emerged:

    1. From “answering correctly” to “delivering”: Evaluation is no longer based on single-turn answers, but on whether the final artifact passes hidden tests or human acceptance.
    2. Resource constraints are closer to reality: Limiting time, compute, and available tools better reflects performance under real constraints.
    3. Dedicated tests prevent luck: Independent validation for each task avoids rough evaluation criteria allowing models to pass by chance.
    4. Multi-dimensional comparison: Public benchmarks show horizontal position, self-built benchmarks show vertical progress, and human evaluation shows real usability.

    The credibility of evaluation data is also critical:

    • Once public benchmarks are widely used, they face the risk of training data contamination, so “benchmark gaming” should be treated with caution;
    • Internal benchmarks should regularly introduce variants and retain a set of held-out problems that never participate in training;
    • Environment evaluations must consider fairness. Network fluctuations and dependency version differences can cause the same model to score differently at different times.

    When the gap between top models narrows to single-digit percentage points, engineering factors such as cost, stability, context length, and private deployment often matter more than benchmark rankings when choosing a model.

    4. Million-Token Context: From “Fitting It In” to “Using It Well”

    One million tokens is roughly equivalent to thousands of pages of documents or several core modules of a medium-sized code repository. Capacity is only the starting point. More important are three types of tasks:

    • Repository-level code understanding: Include cross-module call chains, configurations, and tests in one context so the model can identify downstream impacts before making changes, reducing the risk of “fixing one place and breaking three others.”
    • Long-document analysis: Research reports, prospectuses, and regulatory texts often span hundreds of pages. Models can compare data across chapters, build timelines, and locate contradictions.
    • Multi-turn long-horizon collaboration: Complete records of long conversations and tool calls can be preserved without losing key decisions due to context truncation.

    In practice, three common mistakes should be avoided:

    1. Equating context length with effective information utilization: Information in the middle of a long context may be ignored. Important information should be clearly marked, and the structure should place key content near the beginning and end.
    2. Treating “stuffing everything in” as the goal: Indiscriminately loading historical content amplifies noise and increases latency and cost. A layered compression strategy can be used, as illustrated below:
    1. # Illustration: layered context assembly
    2. context = (
    3. system_prompt() # 1. Task constraints and output specifications
    4. + retrieve(keywords, top_k=8) # 2. Retrieved key materials based on need
    5. + summarize(history, max_tokens=4000) # 3. Compressed summary of conversation history
    6. + latest_turns(n=3) # 4. Recent turns in original form to retain details
    7. + current_request() # 5. Place the current request at the end, close to the output position
    8. )
    1. Ignoring cost: Longer contexts increase memory usage and computation per request. Cache reuse, request batching, and tiered model routing should be used to control costs.

    5. Long-Horizon Agents: Stability Comes from Constraints, State, and Feedback

    Code generation, 3D creation, and financial research are essentially long-horizon tasks. A single request often goes through multiple stages: understanding, planning, execution, verification, and correction, potentially involving dozens of tool calls. The difficulty is not single-step decision-making, but:

    • Whether task state remains consistent across a long chain;
    • Whether errors can be located and rolled back;
    • Whether usable results can be delivered before the budget is exhausted.

    Public evaluation results indicate that a new generation of trillion-parameter models performs in code, agent, and knowledge benchmarks in the same range as the strongest closed-source models in the industry. In terminal task evaluations run in real terminal environments under resource constraints, these models typically perform noticeably better than the previous generation, with gaps to leading closed-source models kept within single-digit percentage points.

    Capability improvements are mainly reflected in four areas:

    1. Repository-level bug fixing: Locate root causes by considering dependencies and call chains, then run tests to verify changes.
    2. Building complete projects from scratch: Complete directory structure, front-end and back-end integration, and basic deployment.
    3. Attention to delivery quality: Web and game outputs should not only be functional but also refined in layout, animation, and visual style. They should also make use of external tools such as professional modeling and rendering.
    4. Maintaining consistency in long chains: After dozens of steps, the model still remembers the original constraints, can detect deviations, and correct them in time.

    In engineering practice, stable task completion usually depends on three “guardrails”:

    • Constraints up front: Clearly specify output requirements, acceptance criteria, and prohibited actions, such as “do not modify test files” or “keep interfaces backward compatible.”
    • Externalized state: Record progress using files, task lists, or other external artifacts rather than relying only on model memory.
    • Closed-loop verification: Run tests or rendering checks after every change and roll back on failure.
    1. # Illustration: agent execution loop with budget and verification loop
    2. def agent_loop(task, tools, budget):
    3. state = load_state(task) # Restore progress from an external state file
    4. while budget.steps_left() > 0:
    5. action = model.decide(state, tools) # Model decides the next action
    6. if action.type == "finish":
    7. return verify(task, state) # Run tests or rendering checks before delivery
    8. result = tools.run(action, timeout=budget.per_step_timeout)
    9. state = update(state, action, result)
    10. if not result.ok and budget.retries_left() > 0:
    11. state = rollback(state, action) # Roll back to the state before the change
    12. save_state(task, state) # Persist state to support resuming after interruption
    13. return report_incomplete(task, state) # Return partial results and explanation when budget runs out

    6. High-Speed Versions: Improving Throughput at the Same Intelligence Level

    Offering a high-speed version of the same model generation is now a common practice in inference services. The goal is not to reduce capability, but to increase output speed several times while maintaining the same intelligence level. Common industry techniques include:

    • Speculative decoding: A lightweight draft model predicts multiple tokens consecutively, and the main model verifies them in one pass, reducing autoregressive steps.
    • Kernel and memory optimization: Operator fusion, quantization such as FP8 or INT8, and paged caching.
    • Scheduling optimization: Continuous batching, request priority tiers, and separate deployment of prefill and decoding.

    Two metrics are often confused:

    • Time to first token (TTFT): Determines the perceived “waiting time” and is strongly related to input length.
    • Output speed (tokens per second): Determines the perceived “smoothness” and is especially important for long responses.

    High-speed versions are better suited to two types of scenarios:

    • Interactive scenarios: Real-time conversations and in-editor assistance.
    • Long-output scenarios: Long-form writing, code generation, and long-horizon agents. Every step of a long-horizon agent requires waiting for the model’s decision output, so faster output can directly shorten overall task duration.

    However, speed optimization is not without cost. Speculative decoding introduces additional computation, quantization may affect precision, and service providers must balance speed and quality. Consistency should also be verified through long-term stability tests. When selecting a model, latency requirements and budget should also be considered.

    7. Implementation Recommendations and Platform Support

    1. Tiered model selection: Use high-speed versions for routine question answering and simple rewriting. Use full-capability versions for complex reasoning and long-horizon tasks.
    2. Evaluate before deploying: Build a private evaluation set of 20 to 50 tasks based on real team workloads. Track pass rates, per-task latency, and token consumption rather than relying only on public leaderboards.
    3. Use sandboxes as a safeguard: Execute all model-generated code and commands in isolated environments. Never allow access to production credentials.
    4. Balance cost and observability: Establish logs, monitoring, and alerts for call volume, latency, and failure rates. Quickly locate anomalies and apply rate limiting when needed.

    From a platform perspective, hosting such model applications usually requires several general cloud capabilities:

    • Container platforms: Run agent sandboxes and support elastic scaling;
    • Object storage: Store training data, checkpoints, and model weights;
    • Message queues: Smooth traffic peaks and decouple asynchronous tasks;
    • Logging, monitoring, and alerting: Enable end-to-end tracing.

    Baidu AI Cloud can provide infrastructure capabilities covering training, inference, and agent execution. For specific products and specifications, refer to the official documentation.

    Conclusion

    The significance of a new generation of trillion-parameter models is not only a new record in parameter scale. More importantly, it indicates that industry competition is shifting from pre-training to scaled post-training, and from “single-turn question answering” to “long-horizon delivery.” For developers, the real barrier is no longer “whether the model can be called,” but whether they can design trustworthy evaluations around their own scenarios, build secure sandboxes, and manage costs effectively. Only by doing these three things well can progress in model capability be converted into real business value.