Qwen K3.1 Pro Deep Dive: Long-Horizon Agents and Trillion-Parameter Post-Training
This article examines the shift from single-turn question answering to long-horizon agent execution, using Qwen K3.1 Pro as the technical context. It explains why end-to-end success rates drop quickly as task length grows, breaks down the capability layers of long-horizon agents, and reviews the key engineering areas behind large-scale post-training: reinforcement learning frameworks, sandbox environments, task scheduling, environment quality checks, numerical consistency between training and inference, code and long-context capabilities, evaluation design, inference optimization, and platform-level implementation. It is intended for engineers and researchers who want to understand how to turn additional compute into stable capability gains in long-horizon agent systems.
Introduction: From Answering to Executing
For a long time, large language model evaluation has focused on single-turn question answering and knowledge coverage. Real-world needs, however, are changing. Users increasingly expect a model to do more than explain an error message: they want it to locate and fix an issue directly inside a real code repository. Similarly, instead of merely proposing a research framework, users expect the model to start from data sources, complete a long analytical chain, and produce a report with citations. These tasks often require dozens or even hundreds of steps. Each step may introduce an error, and those errors can accumulate and amplify. As a result, end-to-end success rates decline rapidly as the number of steps increases. For this reason, a key metric for evaluating models is shifting from single-turn correctness to long-horizon task success.
Note: Any third-party models, evaluations, or tools mentioned below are provided only as technical background or comparison. They do not imply any partnership, evaluation, or adaptation relationship with this platform or Baidu AI Cloud. Code snippets are included only to illustrate engineering ideas.
1. The Core Problem: Capability Boundaries of Long-Horizon Agents
1.1 Breaking Down Capability Layers
The capabilities of long-horizon agents can be divided into four interdependent layers:
- Base knowledge: language, code, and domain common sense. This determines whether the model knows something.
- Mid-level reasoning: planning, decomposition, localization, and induction. This determines whether the model can think through a problem.
- Upper-level execution: tool invocation, parameter construction, result parsing, and error recovery. This determines whether the model can act.
- Outermost verification: testing, replay, and result comparison. This determines whether the model did the work correctly.
Take “fixing a defect in a real code repository” as an example. A typical workflow includes:
- Understanding the user’s description;
- Searching the code repository for relevant modules;
- Reading the code and forming hypotheses;
- Modifying the implementation;
- Writing or supplementing verification cases;
- Running tests and iterating on fixes;
- Submitting the result.
A failure at any stage can cause the task to fail, and the model may not notice the failure by itself. This is why external verification is needed as a safety net.
1.2 Why End-to-End Success Decays Quickly
We can use a simplified model to describe this. Suppose the probability of successfully advancing at each step is p, and the task requires n steps. Then the end-to-end success rate is approximately:
P(success) ≈ p^np = 0.95, n = 20 -> P ≈ 0.36p = 0.99, n = 20 -> P ≈ 0.82p = 0.99, n = 100 -> P ≈ 0.37
This means that even if per-step accuracy reaches 95%, a 20-step task has only about a 30% end-to-end success rate. In real tasks, errors can be detected and retried, and some failures may force the model to change its strategy. Therefore, real-world success rates may be higher than this simple estimate. Still, the general trend holds.
This leads to three main engineering directions:
- Reduce the number of required steps: stronger planning and more accurate tool selection can shorten the execution chain.
- Improve per-step reliability: stronger knowledge and code capabilities can reduce the probability of making a mistake at each step.
- Strengthen verification and rollback: the model should check progress during execution and correct deviations promptly.
These three directions correspond to different focuses of post-training and also explain why evaluation systems need to be designed in layers.
1.3 Common Long-Horizon Failure Modes
From engineering practice, failures in long-horizon tasks can usually be grouped into the following categories:
- Planning errors: misunderstanding the goal or decomposing the task poorly, leading to directional mistakes.
- State loss: missing key constraints when the context becomes long, or forgetting early information too soon.
- Action errors: incorrect tool parameter formats, misuse of paths or APIs, or missing retry logic when calls fail.
- Environment mismatch: inconsistent dependency versions, missing permissions, restricted network access, or insufficient resource quotas.
- Missing verification: declaring completion without checking, or treating “the process ran” as “the result is correct.”
These failures are not isolated model problems. Improvements must be coordinated across training, inference, and infrastructure.
2. Large-Scale Post-Training: Turning Compute into Stable Returns
2.1 Why Post-Training Is Key to Capability Improvement
Pre-training gives a model broad knowledge and a language foundation. Post-training determines whether the model can consistently produce high-quality results on specific tasks. The current mainstream approach combines supervised fine-tuning with reinforcement learning: the former provides cold-start behavioral formats, while the latter continuously improves multi-step decision-making under verifiable reward signals.
As reinforcement learning training scales up, several core tensions become apparent:
- Joint multi-domain training conflicts: tasks such as code generation, long-document analysis, and structured generation have very different input distributions and reward scales. Poor data mixing can create a situation where improving one domain harms another.
- Long-tail length of long-tail tasks: trajectories for long-horizon tasks can easily reach dozens of steps. The sampling cycle is much longer than for single-turn question answering, and poor pipeline design can waste compute.
- Numerical inconsistency between training and inference: the same model may produce slightly different forward results under different parallelization strategies. When amplified, this can make training unstable.
- Reward hacking: the model may find shortcuts in the evaluation instead of truly solving the problem, for example by only modifying test files so that tests appear to pass.
Therefore, large-scale joint training requires coordination across training frameworks, long-context inference, sandbox environments, task scheduling, and data quality platforms. Only when the entire technical stack is robust can newly added reinforcement learning compute be converted into stable capability gains.
2.2 Core Design of a Reinforcement Learning Framework
A reinforcement learning framework for long-horizon agents should at least address four things:
- Unified action space: normalize heterogeneous operations such as tool calls, file edits, and command execution into samplable action sequences.
- Trajectory-level and step-level rewards: evaluate not only whether the final result is correct, but also provide process signals for intermediate steps.
- Decoupled training and inference: the inference engine handles high-throughput sampling, while the training framework handles parameter updates. The two operate asynchronously.
- Fault tolerance and recoverability: a single task failure should not interrupt the entire training run.
The diagram below shows a typical closed loop of training, sampling, environment execution, and feedback:
┌──────────────┐ parameter sync ┌──────────────┐│ Training │ ─────────────────▶ │ Inference ││ framework │ │ engine ││ updates │ │ generation │└──────┬───────┘ └──────┬───────┘│ gradient update │ generate actions│ ▼│ ┌─────────────────┐└─────────────────────────│ sandbox runtime│trajectories and │ code / command │rewards │ files / tests │└───────┬─────────┘│ results and test outputs▼┌─────────────────┐│ environment ││ quality check ││ filtering │└─────────────────┘
Below is a simplified training loop example:
def rl_training_loop(policy, prompts, env_factory, cfg):"""Simplified RL training loop for long-horizon agents.policy: policy model to be trainedprompts: tasks sampled from a mixed multi-domain poolenv_factory: factory function that creates sandbox environmentscfg: training hyperparameters"""for step in range(cfg.total_steps):# 1. Sample multiple trajectories to form groups for the same taskbatch_trajectories = []for task in prompts.sample(batch_size=cfg.batch_size):for _ in range(cfg.group_size):traj = rollout(policy, task, env_factory, max_steps=cfg.max_steps)batch_trajectories.append(traj)# 2. Compute rewards, including outcome rewards and process rewardsrewards = [compute_reward(t) for t in batch_trajectories]# 3. Estimate group-relative advantages, the core idea of group-relative policy optimizationadvantages = group_normalize(batch_trajectories, rewards)# 4. Update parameters with reference model constraints and clippingloss = policy_loss(policy, batch_trajectories, advantages)policy.update(loss)# 5. Periodically synchronize parameters to the inference engineif step % cfg.sync_interval == 0:sync_weights(policy, inference_engine)# 6. Log metrics and monitor rewards, entropy, and task pass rateslog_metrics(step, rewards, advantages)
Several design details deserve attention:
- Group-relative advantages: sample multiple trajectories for the same task and estimate advantages using relative scores within the group. This reduces dependence on an additional reward model.
- Truncation and length penalties: prevent the model from farming rewards through infinite retries and avoid meaningless output length growth.
- Entropy monitoring: a continuous drop in entropy often means the policy has converged too early and lost exploration ability.
3. Key Infrastructure for Large-Scale Joint Training
3.1 Sandbox Execution Environments: A Shared Foundation for Training and Inference
Whether for action sampling during training or tool execution in production, a sandbox is the safety boundary through which agents interact with the external world. A qualified sandbox should at least provide:
- Strong isolation: process, filesystem, network, and resource quotas must be isolated from one another to prevent interference between tasks.
- Fast startup and shutdown: containers should be created and destroyed in seconds to support high-concurrency execution.
- State snapshots and rollback: support saving intermediate states and rolling back after failures, reducing the sunk cost of long-horizon tasks.
- A complete runtime: common compilers, dependency managers, and test frameworks should be preinstalled so environments are reproducible.
Below is an example sandbox configuration:
sandbox:isolation: container # container-level isolationcpu_limit: 4memory_limit_gb: 8disk_limit_gb: 20network: allowlist # allow only whitelisted domains; deny external access by defaultfilesystem: read_only_root # read-only root filesystemwritable_paths:- /workspace # only the workspace directory is writabletimeout_seconds: 600 # timeout for a single executionsnapshot: enabled # enable snapshot and rollbackmax_concurrent: 1 # each sandbox runs one task at a time
3.2 Long-Context Inference and Training Efficiency
Long-context scenarios introduce two major issues:
- Prefill overhead: attention computation grows quadratically with sequence length.
- KV cache usage: key-value cache grows linearly with context length.
Common engineering approaches include chunked prefill, prefix cache reuse, and KV cache quantization. On the training side, a balance between throughput and memory is usually achieved through parallelization strategies, activation recomputation, and gradient accumulation.
Checkpointing is also critical for long-running training. A large-scale training job may run for weeks. The frequency, consistency, and recovery speed of checkpoints directly determine how much work is lost after a failure.
3.3 Task Scheduling and Resource Orchestration
Large-scale joint training is essentially a scheduling problem involving a massive number of tasks. It needs to solve the following issues:
- Priorities and quotas: guarantee resources for core domain tasks while preventing long-tail tasks from being starved for too long.
- Elastic scaling: dynamically adjust the number of inference and sandbox instances based on queue length.
- Fault isolation: an exception in a single environment should not affect the entire training batch.
def dispatch(tasks, scheduler, quota):"""Simplified scheduler for multi-domain tasks.scheduler: scheduling component that maintains priority queuesquota: resource quota for each domain"""running = []while tasks.pending() or running:# Reclaim slots used by finished tasksrunning = [t for t in running if not t.finished()]# Fill slots according to quota and protect high-priority domainsfor domain in scheduler.prioritized_domains():while quota.available(domain) > 0 and tasks.has_pending(domain):task = tasks.pop(domain)running.append(scheduler.submit(task, domain))quota.consume(domain)scheduler.wait_any(running, timeout=5)return scheduler.collect_results(running)
3.4 Environment Quality Checks: Quality Control for Training Data
The quality ceiling of reinforcement learning depends heavily on the reliability of environments and rewards. For this reason, an independent quality-control process is needed to validate tasks automatically:
- Whether a task is solvable and whether the description is ambiguous.
- Whether tests are stable and free from random failures.
- Whether scoring can be fooled by simple patterns.
A common practice is to “filter, trial-run, and remove” the task pool before sampling. A baseline policy can be used for trial runs, and tasks that are too easy or too difficult can be removed to avoid wasting compute. Reward signals judged to be noisy can also be down-weighted or filtered out.
4. Numerical Consistency Between Training and Inference
During post-training, the model needs to switch frequently between the training framework and the inference engine. These two systems usually adopt different parallelization strategies. Different floating-point operation orders can cause numerical differences. In importance sampling, this difference can appear in the ratio of sampling probabilities.
# Compute the importance-sampling ratio and filter abnormal samplesratio = torch.exp(log_prob_train - log_prob_rollout)# A ratio far from 1 usually indicates inconsistency between training and inferencekeep_mask = (ratio >= 0.8) & (ratio <= 1.2)loss = -(ratio * advantage).clamp(max=clip_high).mean()loss = loss[keep_mask].mean() # down-weight or remove abnormal samples
If left unchecked, the ratio for some samples can deviate significantly from 1, increasing gradient variance and even causing training to diverge. A mainstream practice is therefore to set upper and lower bounds for the ratio and filter out abnormal samples. It is also common to periodically compare the output probability distributions from both sides to detect numerical drift early.
5. Capability Applications: Code, Creative Generation, and Long-Document Analysis
5.1 Code Capability: From Local Fixes to End-to-End Delivery
Code is one of the domains where long-horizon capability can be most objectively verified, and it is also one of the areas where post-training investments often produce direct returns. In practical use, code capability appears at multiple levels:
- Single-point repair: locating an issue in a real code repository, understanding the context, and making the fix.
- Test-driven development: writing tests first and implementation second, embedding verification into the development process.
- Project-level construction: building a complete project from scratch, including directory structure, dependency management, and build scripts.
- Visual and interaction quality: generating frontend pages or game prototypes with good visual style and interaction experience.
- Tool collaboration: invoking external specialized tools when needed for rendering, modeling, or packaging.
At the tool-calling level, stable structured output is key. The example below shows how to validate the tool-call parameters returned by a model:
import jsondef parse_tool_call(raw_output, schema):"""Parse and validate tool-call parameters generated by the model."""try:call = json.loads(raw_output)except json.JSONDecodeError:return None, "Output is not valid JSON and needs to be regenerated"missing = [k for k in schema.get("required", []) if k not in call]if missing:return None, f"Missing required fields: {missing}"for key, rule in schema.get("properties", {}).items():if key in call and not isinstance(call[key], rule["type"]):return None, f"Field {key} has incorrect type; expected {rule['type']}"return call, None
Combined with a “feedback on failure” prompting strategy, the model can often produce a compliant call after one or several retries.
5.2 Long Context: Long Memory Is Not the Same as Long Context
Expanding the context window from hundreds of thousands of tokens to millions does not mean the model naturally has “long memory.” A more precise description is that the model can process very long inputs, but whether it can use them effectively depends on the position and relevance of information within the long sequence.
Three common challenges often appear in practice:
- Middle information omission: key information in the middle of a long context is easy to overlook.
- Broken multi-hop reasoning: synthesizing evidence across multiple locations can lose intermediate conclusions.
- Context contamination: noise in retrieval results can interfere with judgment.
Common approaches include structured segmentation, summary compression, and external memory. One way to think about it is to treat long context as a “workbench,” while persistent memory and retrieval systems serve as an “archive.”
def compress_context(history, keep_recent=8, summary_budget=2000):"""Simplified context compression.Keep the most recent turns and summarize the rest."""recent = history[-keep_recent:]older = history[:-keep_recent]if not older:return historysummary = summarize(older, max_tokens=summary_budget)return [{"role": "system", "content": f"Summary of earlier history:\n{summary}"},*recent,]
5.3 Domain Applications: 3D Creation and Financial Research
- 3D creation: the model needs to understand modeling semantics, generate scripted descriptions, and invoke specialized engines for rendering. This requires strong multi-turn iteration and spatial consistency.
- Financial research: this involves cross-document comparison across many reports, announcements, and research materials. Data must be traceable, calculations must be reproducible, and conclusions must be supported by citations.
Both scenarios share a common feature: a single-turn output is far from enough to complete the task. The model must progressively approach the goal through a “generate, verify, correct” loop.
6. Evaluation: Proving That Long-Horizon Capability Has Really Improved
6.1 Evaluation Design Principles
A credible evaluation should satisfy the following principles:
- Realistic environments: run in resource-constrained real environments, not idealized conditions.
- Strict verification: every task should have a corresponding automated test rather than relying only on text similarity.
- Process metrics: not only whether the final result passes, but also steps, time, tool-call counts, and failure reasons.
- Contamination prevention: keep private test sets that are not publicly disclosed and rotate tasks regularly.
6.2 Layered Evaluation Framework
┌──────────────────────────────────────────────┐│ Business Acceptance Layer ││ Sampling of real business tasks, manual ││ review, and tracking of online metrics │├──────────────────────────────────────────────┤│ General Benchmark Layer ││ Code, agent, and knowledge benchmarks; ││ comparison against industry levels │├──────────────────────────────────────────────┤│ Specialized Capability Layer ││ Long-horizon execution, tool calling, ││ long-context understanding, format ││ compliance │├──────────────────────────────────────────────┤│ Regression Test Layer ││ Run after every model update to prevent ││ capability regression │└──────────────────────────────────────────────┘
6.3 Recommended Core Metrics
- Task pass rate: the proportion of tasks that complete end to end and pass verification.
- First-pass rate: the pass rate without any retries or human intervention.
- Average steps: the average number of operations needed to complete a task, reflecting planning efficiency.
- Token efficiency: the total number of tokens consumed to complete a task.
- Human intervention rate: the proportion of tasks that require human takeover.
7. Inference Service Optimization: Rebalancing Capability and Speed
7.1 Standard Inference Services
Standard inference services usually prioritize quality and stability. However, in long-horizon tasks, a single request may take several minutes. To improve the experience, engineering teams can take the following measures:
- Streaming output: return content incrementally as an event stream to reduce perceived latency.
- Priority scheduling: prioritize interactive requests over batch tasks.
- Result caching: reuse intermediate results for repeated tasks.
7.2 High-Speed Inference Services
The goal of high-speed inference services is to improve output speed while maintaining roughly the same level of intelligence. Common technical approaches include:
- Decoding acceleration: speculative decoding and multi-token parallel generation.
- Batch optimization: continuous batching to improve throughput.
- Network optimization: reduce cross-node communication overhead.
- Specialized hardware: choose hardware suitable for the memory-access-intensive nature of the decoding phase.
It is important to emphasize that speed optimization should not come at the expense of reasoning quality. Before a high-speed version is released, quality-alignment evaluations should be conducted against the standard version.
7.3 Capacity Planning for Long-Context Services
Memory pressure in long-context scenarios mainly comes from the KV cache. Capacity can be estimated with the following formula:
KV Cache ≈ 2 × layers × KV heads × head dimension × sequence length × bytes per parameter × concurrency
For example, with 60 layers, 8 KV heads, a head dimension of 128, and FP16 precision, a single 1 million-token context requires approximately 245 GB of memory. In real systems, planning should combine quantization, paging management, and offloading strategies.
8. Platform-Level Implementation: Building Scalable Agent Infrastructure
For enterprises that want to build agent capabilities in-house, they can start from the following layers:
- Compute layer: an elastic resource pool based on a container platform, supporting mixed scheduling of training and inference.
- Storage layer: object storage for training data and model files, with support for large-scale parallel reads.
- Messaging layer: message queues to decouple long-horizon tasks from execution units and enable asynchronous processing.
- Observability layer: logging, monitoring, and alerting systems covering training metrics, service latency, and task failure rates.
- Security layer: key management, network isolation, and access control to preserve the security boundary of sandbox execution.
On Baidu AI Cloud, these capabilities can be implemented through combinations of general cloud products such as container platforms, object storage, log services, and monitoring/alerting systems. Together, they form a complete path from data preparation to model training and agent serving.
9. Frequently Asked Questions and Best Practices
Q1: If long-horizon task success rates remain low, should we optimize the model first or improve infrastructure first?
It is best to begin with attribution analysis. Look at the distribution of failed tasks. If many failures are concentrated in non-model factors such as “environment unavailable,” “tool call errors,” or “timeouts,” prioritize fixing infrastructure. If failures are mainly concentrated in planning and reasoning, increase investment in post-training.
Q2: How can we prevent a model from appearing to complete a task when it actually did not?
The key is verification. All critical outputs must be validated through automated tests or manual review, and validation results should be treated as a necessary condition for task completion, not as an after-the-fact check.
Q3: How should multi-domain joint training be balanced?
Set data ratios according to capability goals for each domain, and monitor training curves for each domain separately. When one domain degrades significantly, adjust sampling weights or introduce curriculum learning strategies in time.
10. Summary
The core of large-scale post-training is not simply adding more compute. It is making every unit of new compute translate reliably into capability gains. This requires a closed loop across training frameworks, sandbox environments, scheduling systems, and data quality platforms. It also requires an evaluation system that accurately reflects long-horizon task performance.
For developers, understanding the capability boundaries and failure modes of long-horizon agents is more valuable than chasing a single metric. Only by continuously refining the “generate, verify, correct” loop in engineering practice can model capability be turned into reliable productivity.
