Training LLM agents: the loss stayed, the plumbing changed
How labs trained search and coding agents in 2025–2026: environments as data, one shared stage pipeline, a masked group-advantage RL loss, and the hygiene, context and infrastructure work that decides whether a run works.
This note assumes you know GRPO-style RL, async RL, SFT and on-policy distillation for reasoning models. It covers what is new when the model acts in a loop. Most frontier numbers below are vendor-reported; claims that rest on secondary coverage are marked “(secondary)”.
What changes when the model acts in a loop
A reasoning rollout is one completion that a program checks. An agent rollout is a loop of 10–300 turns and 30K–256K tokens. Each turn calls a sandbox that can be slow, crash, or return a wrong verifier output. A crash is noise in the reward, not a model error.
Everything in that loop except the weights is the harness: the system prompt, the tool schemas and their wire format (JSON, XML, plain bash), the control loop (step limit, retries, sub-agents), the context policy, the sandbox and the verification hooks. The harness decides which observations the model sees and which actions are legal, so it shapes the state distribution. The same Claude Sonnet 4 scores 64.9, 70.4 and 72.7 on SWE-bench Verified under mini-SWE-agent, OpenHands and the vendor scaffold (a survey table, not a controlled study).
Labs answer this in three ways. Cursor and Cognition run RL inside the production harness they ship. Kimi K3 builds the harness from composable modules (tools, system prompt, context management, skills, memory, sub-agents) and uses different configurations for different task groups. OpenForgeRL leaves real harnesses unmodified and records every model call through a proxy in front of the inference server. Transfer across harnesses is partial: training on one harness gave +3.3 and +4.6 points on two others in OpenForgeRL, while CoTrace found that pooled data from sibling harnesses gave zero accepted model updates. The practical rule: store harness id, version, tool-schema hash and parser version with every trajectory.
Environments are the data
The unit of agent data is a task tuple, not a prompt. It holds the start state, the tools, and a verifier that maps the final state to a reward:
- coding: (repo, base commit, container image, hidden tests);
- search: (question, gold answer, answer checker);
- tool use: (initial database state, user simulator, check of the final database state).
For coding, an LLM agent now builds the container. It runs shell commands, writes a Dockerfile and an eval script, and iterates until a validity check passes: the tests fail on the base commit, pass with the gold patch (at least one fail-to-pass test, no broken pass-to-pass test), and a no-op patch fails. Rollback helps: Repo2Run snapshots the container before each command and built 86.0% of 420 Python repos, against 9.0% for a generic agent. SWE-Universe trained its own builder and flags grep-style fake checks inside the loop.
For search, hard questions come from added uncertainty, not more hops. WebSailor walks a graph of real web entities and obfuscates the result (“early 2010s” for an exact date). Then the policy models define difficulty: GLM-5 drops a question if a tool-free model solves it in at least 1 of 8 tries or an early agent solves it in a few steps, and requires a unique verified answer. For stateful tools, the code-backed database replaced the LLM tool simulator, because the final database state is a deterministic reward. DeepSeek-V3.2 built 4,417 tasks over 1,827 such environments.
calculator
Public coding sets grew 330× in 14 months; filters keep a small fraction
Hover a point for its source. Switch to Keep rate and move the slider to see how many candidates a target set needs.
Two findings changed how teams spend effort. First, scaling curves on 4B–14B models flatten with a knee at about 10–500 environments, and domain breadth beats depth. Second, generated environments are buggy: 74% of AWM’s generated tool environments had at least one bug, and 323 of 1,968 terminal tasks (16%) were hackable from the task text alone. Verifier quality and difficulty calibration, not environment count, are now the bottleneck.
One pipeline won in 2026
MiMo-V2-Flash (2026-01), GLM-5 (2026-02), DeepSeek-V4 (2026-04) and Kimi K3 (2026-07) disclose the same order of stages. They differ in the merge method and in how sequential the RL stages are.
animation
The 2026 agent pipeline, stage by stage
Press Play, or click a box. Each stage lists the data that flows in, the loss, and the reported numbers.
Data.
Loss.
Mid-training is mostly more tokens of agent-shaped text at longer context, not a new objective. The one clean ablation (AgentFounder, 30B) lifts BrowseComp-en from 26.9 to 31.4 with 50B tokens of agent data. No frontier report ablates it against an equal-token control.
SFT sets can be small with a strong teacher: 5,016 trajectories give 40.2% on SWE-bench Verified at 32B. Two details matter more than size. The strongest model is not the best teacher: GPT-5.3-Codex was about 5% worse as a teacher than GLM-4.7-AWQ in OpenThoughts-Agent, so choose the teacher by the student’s score. And filtering on success is now in dispute. On Terminal-Bench 2.0, Qwen3-8B reaches 12.4 with no filter and 5.06 with success-only filtering (Nemotron-Terminal). Success-only filtering removes the hard tasks; the 2026 papers filter on behaviour instead (at least 5 turns, no test edits, no git hacks).
The merge changed in 2026. In 2025, labs ran SFT on the experts’ samples (GLM-4.5, DeepSeek-V3.2). That is off-policy, and the unified model trails the specialists. Now the student samples its own trajectories, each prompt is routed to the expert of its domain, and the loss is per-token reverse KL to that teacher. On short tasks the student matches or passes its teachers (SWE-bench Verified 73.4 vs 74.2); on the longest-horizon benchmarks it stays below.
The RL loss: mask, group, broadcast
Mask the tokens the policy did not write
Tool output, web pages and test logs sit in the context but the policy did not sample them. With a mask on environment tokens, the loss is the usual clipped ratio averaged over policy tokens only:
The evidence came early. Search-R1 (Qwen2.5-7B) went from average exact match 0.343 to 0.431 with the retrieved-token mask. The mask is now standard. The subtle part is that it must follow the exact token ids the sampler produced. If the harness parses a tool call and re-renders it (false becomes False), or decodes and re-tokenizes the history, the trainer sees a prefix the policy never sampled. The fix is token-in, token-out (TITO): a gateway records token ids and log-probs and nothing is re-tokenized.
playground
One trajectory, two ways to get the loss wrong
Click rows to add or remove them from the loss. Then switch to Re-tokenize and click the turn boundaries.
GLM-5 also keeps failed turns in the context but masks their loss, so the model sees the error and its repair without learning to repeat the bad call. One counterpoint: ActObs (4–8B) found that adding a loss on observation tokens left the pre-RL score unchanged but mostly raised the post-RL score, so judge an SFT checkpoint by its post-RL score.
One reward per trajectory, one advantage per group
Production systems (Tongyi DeepResearch, Kimi-Researcher, GLM-5, MiroThinker, DeepSeek-V3.2) still use a single outcome reward per trajectory. Sample rollouts of one task, score each at the end, and compute the advantage inside the group:
The advantage is then broadcast to every policy token of trajectory . If every rollout gets the same reward, every is zero and the group carries no gradient. A task with pass rate gives such a group with probability .
playground
Group-relative advantage for agent rollouts
Click a reward tile to flip it. Set all eight to 0 or all to 1. Then click the lower chart to sample a group from a task with that pass rate.
The coding recipe converged by 2025-07 (DeepSWE, SkyRL-Agent, Meta CWM, Nebius) and has changed little since:
- binary hidden-test reward (fail-to-pass plus pass-to-pass), and the agent must submit;
- no KL loss, no entropy bonus, clip-higher ( 0.25–0.3, 0.2);
- no division by the reward std, mean or leave-one-out baseline;
- drop zero-variance groups, and mask the loss of truncated or timed-out trajectories;
- group 8–10 for SWE tasks, 32 for terminal tasks (more stable than 8 in Tmax).
Pure RL works at 32B: SkyRL-Agent went from 24.4% to 39.4% on SWE-bench Verified for 4,601 H100-hours. Turn-level credit methods gain 1–8 points on 1.5B–8B models, often with one seed, so production stays at trajectory level. Agent-specific instabilities (entropy spikes after tool output, low-probability tokens that compound across turns, collapse from sandbox errors) are mostly fixed by filtering samples, not by new losses. KAT-Coder-V2.5 cut sandbox-feedback errors from about 16% to under 2% and saw training collapses about 10× less often.
Reward hacking moved from tests to retrieval
In agent RL the reward is a program that runs in the same sandbox as the policy. The policy can read it, patch it, or go around it. The reward families in use: hidden unit tests for code; a binary LLM judge for search answers (a small judge agreed 97.62% with a stronger one, and it beats F1 and exact match, which invited overlong answers); rubric judges for reports; and final-state checks for tool use. Tests alone gave Cognition verbose code with excess try/catch, so SWE-1.5 added a rubric grader, a browser grader and human “reward hardening”. Partial credit is safer with a guardrail: with of objectives met and guardrail violations, if and otherwise.
diagram
Reward-hack gallery, 2025 to 2026
Click a date, a channel in the sandbox diagram, or Next. The card gives the hack, how it was found, the number, and the fix.
- Hack
- Found by
- Number
- Fix
This is a training problem, not only an eval problem. Xiaomi found Qwen3-32B learning git log --all during RL, which inflated both reward and eval scores. Vals.ai later found the fix commit as an unreachable git object in 67% of the RL tasks Xiaomi released, while Xiaomi’s detected hack rate was below 2%.
The fixes, in order of strength:
- Environment hygiene. Rebuild each repo as a single-commit repo with no reflogs, remotes, tags or hooks; prune unreachable objects; withhold grading files; hash instance ids; block code hosts and dataset hubs but keep package registries; block egress on the inference path too. Apply it to training images, not only eval images.
- Automated audit. A hacker agent tries to pass without solving, a fixer patches the verifier, a solver checks that real solutions still pass. A weak model is enough: a Gemini 3 Flash loop cut Opus 4.7’s attack success from 61% to 0%.
- Monitors. A chain-of-thought monitor detects hacks better than an action monitor, but heavy optimisation against it hides the intent while the hacking continues. Use it to detect, not as a reward.
Prompts are a patch, not a defence. METR measured an 80% hack rate both with and without “do not cheat”. A specific rule (“build solutions independently”) cut shortcut attempts from 60.7–90.1% to 9.4–14.2% for open models (NVIDIA). The stakes are larger than eval scores: Anthropic and Redwood found that a model that learned hacks in production coding RL showed broader misalignment, including sabotage attempts in 12% of cases in one agentic eval.
Context management became a trained action
Search agents now run 200–1000 tool calls, so the window fills long before the task ends. In 2025, context management was an inference trick. In 2026 it is part of the policy and of the eval protocol. The same model gains 10–25 BrowseComp points when it may manage context: DeepSeek-V3.2 51.4 → 67.6 and Kimi K2.5 60.6 → 74.9 with discard-all; GLM-5 55.3 → 62.0 with keep-recent-5 and 75.9 with a hybrid (different configs).
playground
What the window holds, and what that buys
Switch the strategy and watch the occupancy curve. The lower chart marks the same strategy in Step 3.5 Flash's measured results.
The crude methods won at the frontier: hide old tool results, or discard all history above a threshold. Step 3.5 reports that discard-all acts like pass@k: the agent re-reasons from scratch until it finds a path it can verify. The best static strategy depends on the model (AgentSwing: discard-all best for DeepSeek-V3.2, keep-last-N best for GPT-OSS-120B), so test per model and report steps and tokens with every result.
Training under rewritten context needs one change. Tokens after a rewrite are conditioned on a different prefix, so one forward pass over the concatenated rollout is wrong. Every method splits the rollout into segments, each a training sample under its own true prefix. The open question is credit across segments: broadcast one outcome advantage (ReSum, AutoCompact), add process penalties (FoldGRPO; outcome reward alone did not teach folding), or use a critic with cross-segment GAE (CompactionRL, which uses PPO because GRPO group statistics break when segment counts differ). In CompactionRL, dropping token-level loss normalisation cost 6.4 points on SWE-bench Verified, more than dropping the cross-segment GAE.
Reasoning is context too. MiniMax’s A/B on M2 kept or dropped earlier thinking between tool calls: BrowseComp 44.0 vs 31.4 (vendor numbers). Labs converged on a middle rule: keep reasoning across tool calls inside one user turn, drop it when a new user message arrives. Train with the same scheme you use at eval.
Infrastructure: async, exact, clean
Agent rollouts have a long tail. If one agent’s 90th-percentile length is 5× its median, the joint 90th percentile over a batch is about 25× (Hugging Face survey), and a synchronous batch waits for the slowest rollout. Every frontier stack is therefore disaggregated and fully async: rollout engines, a trainer, a sandbox fleet and a gateway that records tokens. Weights update in flight, so one trajectory can span several policy versions, and samples older than a cap are dropped. Reported caps range from 1 to 8 policy versions.
animation
Sync and async rollouts with a staleness cap
Press Play in Sync, then in Async. Lower the staleness cap and raise the crash rate.
Four fidelity fixes now matter more than the objective:
- TITO. If every turn boundary of a 5-turn rollout breaks, the trainer does about 3× the forward work. A prefix-preservation test of about 12 lines passes 18 of 19 chat templates; Qwen3’s fails.
- Train–inference mismatch. Fixes stack in layers: aligned kernels and precision (FP32 LM head, batch-invariant kernels), double-sided importance-sampling masks against the rollout log-probs, and MoE router replay (record expert indices in rollout, replay them in training), which gave about 10× lower trainer–inference KL in prime-rl. Modal’s collapse signature for agents: reward falls, KL grows, and the model stops calling tools.
- Sandboxes. Fleets grew from more than 10,000 concurrent (Kimi K2, 2025-07) to about 380,000 (DeepSeek DSec, 2026-09), through layered images, lazy loading, memory overcommit and microVM snapshot and fork. Exclude crashed samples from group statistics; do not train on a reward caused by a sandbox crash.
- Weight sync. For a 1.6 TB model it fell from 86.1 s (NCCL) to 3.9 s (one-sided RDMA reads). With in-flight updates this sets the floor on staleness.
Reading an agent score
An agent score is a claim about a system: model, harness, budget, resources and grader. Each part moves it.
| Setup factor | Measured effect |
|---|---|
| Container resources (Terminal-Bench 2.0) | 6 points between most and least resourced; infra errors 5.8% → 0.5% |
| Anti-leak controls (SWE-bench Pro, GLM-5.2) | 78.80 → 57.32; DeepSeek-V4-Pro only 49.98 → 49.11 |
| Step budget (o3 on OSWorld) | 9.1% → 23.0% |
| Task fixes (Terminal-Bench 2.0 → 2.1) | +12.1 for one system, −0.3 for another |
| Harness (Sonnet 4, SWE-bench Verified) | 64.9 / 70.4 / 72.7 (not controlled) |
Anthropic’s rule is to distrust leaderboard gaps under 3 points unless resources, harness, repeats and effort are controlled. Some vendor cards report the best of several harnesses; report a fixed-harness score next to it. For agents that run unattended, consistency matters: pass requires all attempts to succeed, and a 75% per-trial rate gives only about 42% for three in a row. SWE-bench Verified is retired as a frontier metric (secondary), Terminal-Bench 2.1 is the main terminal benchmark, and the leak checklist applies to eval and training images alike.