LLM Post-Training in Practice: Building Code and Long-Horizon Agent Capabilities
This article examines how post-training—supervised fine-tuning (SFT), preference alignment, and especially reinforcement learning (RL)—has become the main driver of LLM capability gains as parameter scaling hits diminishing returns. It covers the engineering challenges of scaling RL across hundreds of domains, why evaluation methodology matters more than leaderboard scores for code and long-horizon agents, the infrastructure upgrades required to run large-scale agents (RL training frameworks, long-context inference, sandboxes, scheduling, and environment quality checks), where inference-side "fast versions" come from, the role of a managed Harness as cloud infrastructure, the economics behind API pricing and caching, and practical recommendations for developers and enterprises.
1. Post-Training: The New Battleground for Capability
For the past few years, improvements in LLM capability relied largely on scaling parameter counts and piling up pretraining data. But once parameters reach the trillion scale and high-quality text starts to run dry, the diminishing returns become increasingly obvious. What truly separates models has gradually shifted from “how much data was fed in during pretraining” to “how many tasks were trained during post-training.”
Post-training typically covers several stages: supervised fine-tuning (SFT), preference alignment, and reinforcement learning (RL). Among these, RL is becoming the key technique for turning “general capability” into “usable capability,” because it can use task success or failure directly as a reward signal. The upgrade direction of a new generation of models generally reflects a few shared trends:
- Post-training compute rises sharply, with training resources tilting from pretraining toward the RL stage;
- RL is no longer confined to a handful of general benchmarks but expands across hundreds of downstream task domains;
- Capability goals shift from “answering single-turn questions correctly” to “completing long-horizon, multi-step real tasks.”
This shift means that both evaluation and training are moving their focus toward the process rather than a snapshot of the result. Whether a model can stay aligned with the goal and correct its own mistakes across dozens or even hundreds of interactions has become a core metric of its agentic capability.
2. Scaling RL Across Hundreds of Downstream Domains
Scaling RL to hundreds of domains sounds simple, but it is extremely difficult in engineering terms. The reasons are:
- Complex reward design. Definitions of “success” vary enormously across domains: code tasks look at whether test cases pass, data analysis tasks look at whether conclusions are sound, and tool-calling tasks look at whether the right function and parameters were chosen. Designing a reliable, automatically verifiable reward function for each domain is itself a massive undertaking.
- High environment diversity. Each domain often corresponds to a different execution environment, dependency set, and boundary conditions, so the training framework must simultaneously manage hundreds or thousands of heterogeneous sandboxes.
- Training stability. Multi-domain joint training is prone to a “seesaw effect”—one domain improves while another regresses. This calls for careful data mixing, curriculum learning, and gradient control strategies.
A pragmatic approach is to make reward signals as “verifiable” as possible. For tasks that can be judged automatically—code, math, structured output—use deterministic signals such as test pass rates or answer matching. For open-ended tasks, introduce rule-based scoring or model-based review, but stay alert to the risk that the reviewer model’s own biases get amplified.
3. Code and Long-Horizon Agents: Evaluation Methodology Matters More Than Scores
Code and long-horizon agent capabilities are the most closely watched directions in this round of upgrades. Understanding how they are evaluated is more valuable than memorizing any specific score.
Take terminal-based coding evaluation as an example. The industry increasingly prefers to test agents in “real, resource-constrained” environments: given a terminal environment resembling a real developer’s setup, the agent must read code, edit files, run commands, inspect errors, and fix them—on its own—until the task is done or it times out. This design involves several key considerations:
- Environment realism: being close to a real engineering scenario, so the model’s behavior under noise, dependency conflicts, and long logs is actually reflected;
- Resource constraints: limiting CPU, memory, time, or the number of tool calls forces the model to act efficiently rather than blindly trial-and-error;
- Process traceability: recording every action and its result makes it easy to pinpoint where the model got stuck.
“Long-horizon” evaluation goes a step further, examining whether the model can stay on track over tasks spanning dozens of steps or more. Getting a short task right does not mean a model can maintain a complex goal across many rounds that require mid-course strategy adjustments. Designing long-horizon evaluations typically requires:
- Clear, automatically judgeable final acceptance criteria;
- Multiple intermediate state changes, to prevent a model from passing by “one lucky step”;
- Hard limits on token budget or number of steps, simulating real-world engineering cost constraints.
It is worth emphasizing that any single leaderboard runs the risk of being optimized against directly. A genuine capability assessment should be built on the enterprise’s own real business data, constructing private evaluation sets tailored to the specific scenario.
4. Infrastructure Upgrades to Support Large-Scale Agents
To keep RL running stably across hundreds of domains and thousands of environments, model teams often need to overhaul the entire infrastructure systematically. These upgrades are equally instructive for engineering teams building agent applications.
1. RL training framework
Large-scale RL training must coordinate two pipelines at once: “rollout” (inference generation) and “training” (parameter updates). Common challenges include low GPU utilization during generation, memory fragmentation, and synchronization overhead between generation and training. Mature frameworks typically use asynchronous rollout, experience replay, and pipeline overlap to push generation and training forward in parallel as much as possible.
2. Long-context inference
Million-token context puts enormous pressure on inference systems. The complexity of attention computation grows quadratically with sequence length, and the memory footprint of the KV cache balloons sharply. Common engineering techniques to reduce this overhead include paged KV cache management, prefix cache reuse, and attention approximations such as chunking or sliding windows.
3. Sandbox infrastructure
To execute code and call tools, an agent must run in an isolated environment. A robust sandbox needs fast start/stop, resource limits, network isolation, and filesystem snapshot and rollback capabilities. Sandbox startup latency directly determines training sample throughput per unit of time.
4. Scheduling system
Orchestrating hundreds or thousands of heterogeneous environments is impossible without an efficient scheduling system. It must handle task queuing, resource preemption, failure retries, and priority scheduling, while managing the lifecycle of each rollout task with fine granularity.
5. Environment quality inspection platform
“Garbage in, garbage out.” If the environment itself is misconfigured, missing dependencies, or polluted with bad data, even the strongest model cannot learn correct behavior. A quality inspection platform is responsible for automatically validating a massive number of task environments, removing bad samples and correcting configurations—a key link in safeguarding training data quality.
5. Training and Inference Efficiency: Where “Fast Versions” Come From
It is worth noting that some models release a “fast version” with unchanged capability—output speed increases severalfold while the intelligence level stays the same. These optimizations usually come from the inference side rather than the model itself. Common general-purpose techniques include:
- Speculative decoding: a small model or draft mechanism predicts multiple tokens first, then the large model verifies them in batches, reducing the number of serial decoding steps;
- Weight quantization: using lower-precision representations such as INT8/FP8 to reduce memory usage and improve throughput;
- Batching and parallelism optimizations: improving GPU utilization through continuous batching, tensor parallelism, and similar methods;
- Operator and kernel optimization: custom acceleration for hot operators such as attention and normalization.
For developers, the value of a “fast version” lies in trading an acceptable extra cost for lower latency, which suits interactive and latency-sensitive scenarios. The standard version is better suited to tasks that demand the utmost quality per token.
6. Agents as Cloud Infrastructure: The Value of a Managed Harness
When an agent needs to run 24/7, handling long-horizon tasks that span days or even weeks, “model capability” is only one piece of the puzzle. What actually sustains long-horizon operation is a runtime framework known as the Harness. It packages capabilities such as tool invocation, state management, retry and recovery, concurrent scheduling, and observation logging into a single piece of infrastructure.
Offering the Harness as a cloud-hosted service has real value for enterprises and developers:
- No operations overhead: no need to build and maintain sandbox clusters, schedulers, and storage yourself;
- Elastic scaling: scale compute on demand when task volume fluctuates;
- Multi-agent collaboration: multiple agents divide the work and run in parallel, coordinating complex goals through message passing.
In these scenarios, cloud providers usually supply a set of general-purpose capabilities as a foundation—for example, a container platform to host sandboxes, object storage to save task artifacts and checkpoints, message queues to handle task distribution and event-driven flows, and logging plus monitoring and alerting services to provide observability. Taking Baidu AI Cloud as an example, its general cloud products for containers, storage, messaging, and monitoring can serve as the base components for building such an agent runtime.
A simplified main loop for a long-horizon agent looks like this (logic illustration only, not a specific product interface):
def run_agent_task(goal, harness, max_steps=200, budget_tokens=1_000_000):state = harness.init_state(goal) # Initialize state and contextfor step in range(max_steps):if state.token_used > budget_tokens: # Hard cost constraintreturn harness.graceful_stop(state, reason="budget_exceeded")action = model.decide(state) # Model decides the next actionresult = harness.execute(action) # Execute tools/code in the sandboxstate = harness.observe(state, result) # Record the result and update stateif harness.is_goal_satisfied(state): # Verifiable success checkreturn harness.finish(state, success=True)state = harness.maybe_checkpoint(state) # Checkpoint at key steps to enable recoveryreturn harness.graceful_stop(state, reason="max_steps_reached")
This illustration reflects several key points of long-horizon agent engineering: explicit step and token budget constraints, a verifiable completion check, and a checkpoint mechanism—the last of which lets long tasks resume after an interruption and is essential for 24/7 operation.
7. The Economics Behind API Pricing Models
Looking at how mainstream LLM APIs are priced reveals a few common characteristics. Understanding them helps with cost optimization:
- Input/output asymmetry: computing output tokens costs more than input tokens, so output pricing is usually significantly higher than input pricing;
- Caching tiers: input that hits the cache is priced far lower than input that misses. This is because the server can reuse an already-computed KV cache and skip the repeated forward computation.
For developers, cache hits are the key to cutting costs. Anything with strong repetition—system prompts, long documents, few-shot examples—should be placed toward the front of the context and kept stable, to maximize the reuse rate of the prefix cache.
# Pseudocode: improving cache hit rate via a stable prefixstable_prefix = system_prompt + long_doc + few_shots # Changes rarely, reused oftenmessages = [{"role": "system", "content": stable_prefix}, # Keep this unchanged{"role": "user", "content": user_query}, # Put the changing part at the end]
At the same time, a “fast version” usually costs several times the price of the standard version and suits latency-sensitive real-time interactions, whereas offline batch tasks can prioritize the standard version to control costs.
8. Practical Recommendations for Developers and Enterprises
To build strong code capabilities and long-horizon agent capabilities in your own business, the following practices are worth considering:
- Build evaluation first, optimize later: measure models with a private evaluation set that fits your own business, and avoid being misled by public leaderboards.
- Prioritize post-training and domain adaptation: for high-frequency, high-value scenarios, targeted reinforcement through SFT and RL is more cost-effective than blindly chasing general scores.
- Treat the agent as systems engineering: beyond the model, invest heavily in runtime capabilities such as sandboxes, scheduling, observability, and checkpoints.
- Make good use of caching and version tiers: improve cache hit rates via a stable prefix, and weigh the cost–latency tradeoff between the standard and fast versions by scenario.
- Focus on observability and safety: log and monitor every action of a long-horizon agent to surface problems early and control risk.
Post-training is pushing the competition in LLMs from “parameter scale” toward “task completion.” Whoever can more systematically invest compute into real, verifiable, and sustainable task environments is more likely to be the first to land in long-horizon scenarios such as code, financial research, and content creation.
