LoRA + Reinforcement Learning for a 27B Model: A 16.3-Point Gain on Terminal Tasks
This article looks at how to adapt a 27B open-weight model for coding and terminal agents by freezing the base weights and training a LoRA adapter with asynchronous GRPO in sandboxed environments. It explains why the bottleneck in agent-style evaluations has moved from knowledge to tool-use strategy, analyzes a base-vs-adapted case study on a hard code-repair subset, and details the training recipe, reward shaping, data mix, and adapter configuration. Published results show the Hard code-repair subset (51 tasks) improving from 39.2% to 64.7% (+25.5 points) and the terminal-task benchmark (v2.1) from 39.5% to 55.8% (+16.3 points), with an almost identical gain on 68 held-out tasks. The adapted model also uses fewer than half as many tool calls as the base model and generates about a quarter as many tokens with thinking mode off. The article closes with practical guidance on replicating the method, deployment caveats, and the approach's limitations.
1. Background: Agent ceilings have moved from knowledge to tool use
Over the past year, evaluation focus for code and terminal tasks has shifted. Early benchmarks asked whether a model could write a correct function. In agent form, the real bottleneck is whether the model can, within a limited number of steps, choose the right tool, supply the right arguments, and recover from erroneous output.
That shift produces three typical failure modes:
- Ineffective exploration loops: the model repeatedly runs similar searches, gains no new information, and never changes strategy.
- Context bloat: every step stuffs large command outputs back into the context, which slows reasoning and dilutes attention with noise.
- Step exhaustion: the task runs out of the agent framework’s maximum step budget without being completed, and the score is zero.
All three share one root cause: the model already has the knowledge to repair the code, but the policy layer fails. This is precisely why pouring more effort into large-scale pretraining or larger thinking budgets now yields little marginal return. What needs optimizing is “how to act in an environment.”
2. Core idea: freeze the base, train only a tool-calling policy
A publicly documented adaptation effort offers a cost-controlled answer: train LoRA adapters for a 27B-parameter open-weight base model, targeting software engineering and terminal tasks in coding agents. The goal is not broader general knowledge but reshaping the model’s tool-use habits.
Unlike retraining the base model, this route makes three deliberate trade-offs:
- The base weights stay untouched. Adapters are typically in the hundreds-of-megabytes range, so training, storage, and distribution costs are all far lower than full-parameter fine-tuning.
- Reinforcement learning instead of supervised fine-tuning. Supervised data teaches “what to output at this step”; RL optimizes the expected return of the whole trajectory, which fits multi-step settings with environment feedback naturally.
- Thinking mode is allowed to be off. The aim is to “compile” reasoning into the policy so the model emits effective actions directly without generating long chains of thought.
3. What changed in practice: from endless searching to an 8-step fix
The published report includes a paired case study on a hard code-repair benchmark (the Hard subset, 51 tasks). It is worth analyzing step by step:
Base model trajectory: repeatedly searches the codebase → guesses the cause → reruns tests → output is still similar → searches again… eventually hits the 100-step cap without passing.
Adapted trajectory: locates the target function → edits the code → runs the tests → fixes the last edge case using the assertion failure message → passes. The whole run converges within 8 tool calls.
The difference is not knowledge but three transferable behavioral traits:
| Behavioral dimension | Base model | Adapted model |
|---|---|---|
| Exploration strategy | Breadth-first, repeated sampling | Locate first, then act; near-binary convergence |
| Use of feedback | Ignores or restates failing output | Fixes the exact point based on assertion messages |
| Stopping condition | No stopping criterion | Stops as soon as tests pass, with no extra pointless actions |
4. Inside the training setup: async GRPO + LoRA + sandboxed environments
4.1 Algorithm: asynchronous group relative policy optimization
Training uses asynchronous GRPO-style group relative policy optimization. Compared with classic PPO, GRPO-style methods drop the separate value network and estimate advantages from the relative scores inside multiple sampled trajectories for the same prompt, which substantially reduces GPU memory needs and engineering complexity:
$A_i = \frac{r_i - \text{mean}(r_1..r_n)}{\text{std}(r_1..r_n)}$
“Async” is the engineering focus here. Agent rollouts must really execute commands and run tests, and a single trajectory can take tens of seconds. Synchronous training leaves GPUs idling while they wait for the environment. The async approach decouples sampling workers from training steps: rollouts keep producing while the trainer keeps consuming, which hides environment latency inside computation.
4.2 Environment and task orchestration
Training runs standardized tasks inside the agent framework, with a separate execution-environment layer supplying containerized sandboxes. That layer has to solve four problems:
- State isolation: each rollout owns its filesystem and process space so they cannot contaminate one another.
- Reproducible initialization: the initial repository state and test commands for a given task are fixed.
- Reliable scoring: automated tests or scoring scripts provide the objective signal, not model self-assessment.
- Timeouts and resource quotas: to prevent a single hung rollout from dragging down the whole batch.
4.3 Data mix
Public information shows the training data came from two sources:
- 750 Scale800-difficulty tasks: high difficulty, long chains, strong gradient signal.
- 300 TermGrade-style tasks: command execution and result judging, covering the terminal-side distribution.
1,050 tasks is a small budget for LoRA training on a 27B model, which points to a pragmatic conclusion: in agent RL, task quality and difficulty distribution matter far more than data volume.
4.4 Reward shaping: correctness first, efficiency second
The reward combines two terms, with a tool-efficiency weight of 0.1:
def compute_reward(rollout):# 1) Task correctness: main reward, range 0-1if rollout.all_tests_passed:r_task = 1.0elif rollout.partial_tests_passed:r_task = 0.5 # Partial pass gives a gradient instead of all zeroselse:r_task = 0.0# 2) Tool-call efficiency: auxiliary term, weight 0.1eff = max(0.0, 1.0 - rollout.tool_steps / rollout.step_budget)return r_task + 0.1 * eff
Several details in this design are worth borrowing:
- The efficiency weight is deliberately kept at 0.1. A higher weight teaches the shortcut of “giving up early,” trading accuracy for a low step count. At 0.1, saving one step compensates at most 0.1 while failure costs 1.0, so correctness always dominates.
- Partial passes also score. An all-or-nothing reward is extremely sparse over long trajectories and leaves the model unable to tell which step went wrong; a partial-pass signal markedly improves early convergence.
- Efficiency is normalized against the relative budget, which avoids scale mismatches caused by differing step caps across tasks.
5. Published results: better accuracy and lower cost
| Benchmark | Base model | Adapted model | Change |
|---|---|---|---|
| Hard code-repair subset (Hard 51) | 39.2% | 64.7% | +25.5 pts |
| Terminal-task benchmark (v2.1) | 39.5% | 55.8% | +16.3 pts |
| 68 terminal tasks not used for selection | 39.7% | 55.9% | +16.2 pts |
The three rows should be read together.
The first row shows the size of the capability gain. A 25.5-point jump on the hardest subset matches what RL optimization tends to deliver, since hard tasks are exactly the long-trajectory, policy-heavy cases.
The third row is the most important evidence. The evaluation set used for checkpoint selection is completely disjoint from these 68 held-out tasks, yet the gain (16.2 points) nearly matches the selection set (16.3 points). That largely rules out “we picked a lucky checkpoint on the benchmark” and indicates the improvement comes from generalizable policy changes, not sample memorization.
The efficiency gains are equally notable. On tasks both versions complete, the adapted model needs less than half the tool turns of the base model. And compared with a base model running at its maximum thinking budget with explicit reasoning, the adapted model reaches comparable accuracy with thinking mode off while generating roughly a quarter of the tokens.
For production, the implication is direct: agent cost is driven mainly by “steps × context length per step.” Halved turns plus a quarter of the tokens means throughput can improve several-fold at the same concurrency level, without an accuracy penalty.
6. Reusable engineering practices: reproducing this method
6.1 Adapter configuration
For LoRA-style adapters, the parameters that matter are not so much “how large a rank” as injection placement and training stability:
adapter_cfg = {# Full injection into attention and FFN; policy tasks are more FFN-sensitive"target_modules": ["q_proj", "k_proj", "v_proj", "o_proj","gate_proj", "up_proj", "down_proj"],"r": 16, # No need for a large rank; saturation usually starts around 32"lora_alpha": 32, # Recommendation: alpha = 2r"lora_dropout": 0.05, # Small data plus RL: moderate regularization"task_type": "CAUSAL_LM",}
Practical notes:
- Injecting into attention layers alone is often not enough. Tool-call formatting and stopping behavior live more in the feed-forward layers.
- Use a lower learning rate in the RL stage than in SFT. Once policy drift becomes too large, already-acquired general capabilities degrade quickly.
- Always keep a general-capability regression evaluation. The most common hidden cost of specialized adaptation is a drop in general conversation and code generation quality. This does not show up on the main benchmark, but it directly affects the live experience.
6.2 Training pipeline sketch
1. Load the base model + insert LoRA (base weights frozen, only adapter parameters optimized)2. Task sampling: stratified sampling by difficulty from the task pool3. Async rollout: N parallel trajectories, each really executing tools in its own sandbox4. Scoring: test pass rate + step efficiency -> scalar reward5. In-group normalization for advantages -> policy gradient update (with a KL constraint to prevent drift)6. Periodic evaluation: selection set + held-out set + general-capability regression7. Export adapter weights (keeping both full-precision and quantized versions)
6.3 Three easy traps
- Reward hacking: if the efficiency weight is too high or the termination condition is too loose, the model learns to skip verification and simply declare success. Anti-cheating checks on the scoring side are mandatory, for example verifying that tests were really executed and that output was really written.
- Mismatched train/inference configuration: using the full step budget during training and tightening the cap at deployment will directly break the policy. Both sides must align on tool set, output format, and budget.
- Unstable sandboxes: environment jitter gets learned as an “environment signal” and forms a wrong policy. Run health checks and mark failed retries before sampling.
7. Deployment and integration: the adapter is not a standalone model
One point must be clear: the artifact is an adapter, not a complete model. It cannot be loaded or run on its own and must be paired with the same base version. Typical distribution formats include:
- PEFT-style LoRA weights, loadable by high-throughput inference engines that support hot-swappable adapters;
- An adapter format loadable by standard deep learning frameworks, convenient for custom inference paths;
- A general quantized model format, so it can be loaded directly on lightweight inference runtimes (this usually requires merging the adapter into the base first, then quantizing).
Engineering recommendations:
- Pin the build. “Base version + adapter version” should be versioned as a single unit; after a base upgrade, the adapter must be re-validated.
- Multi-adapter routing. If specialized adapters for code, terminal, and documentation all exist, route by task type to the corresponding adapter to avoid cross-interference.
- An inference-side fallback. Keep the base model as a fallback so you can roll back quickly if offline regression shows capability degradation.
- Observability. Instrument “task success rate,” “average tool turns,” “P95 step count,” and “tokens per task.” This set of metrics reflects live health better than accuracy alone.
8. Limits and where this applies
Objectively speaking, this kind of solution has clear boundaries:
- It depends on a reliable automatic scoring environment. If task correctness cannot be judged automatically, there is no way to build the RL reward signal.
- In-distribution gains far exceed out-of-distribution ones. Training covers software engineering and terminal scenarios; transfer to long-document writing or multimodal tasks is uncertain.
- Turning thinking mode off is not universally optimal. For open-ended problems that need long-horizon planning and trade-offs among alternatives, explicit reasoning still has value. A sensible product strategy is to switch the thinking budget dynamically by task type, not to disable it globally.
- Evaluation data must be handled carefully. Data isolation between adaptation and evaluation has to be strict, or the numbers lose their reference value.
9. Summary
The real value of this work is not the 25.5-point gain itself but the cost-controlled technical path it validates: once the base model is capable enough, an agent’s main weakness lies in the policy layer, and that layer can be repaired efficiently with small-scale data + reinforcement learning + LoRA.
It yields four transferable conclusions: first, decide whether the problem is “knowledge” or “strategy” before choosing between more pretraining and more RL; second, in reward design correctness must outweigh efficiency, with auxiliary weights kept around 0.1; third, async sampling is the necessary engineering technique for hiding environment latency inside computation; fourth, evaluations must retain a held-out set, otherwise you cannot distinguish genuine generalization gains from checkpoint luck.
For teams building coding or operations agents in their own environments, this route offers a clear starting point: stand up a sandbox that can score automatically, prepare a difficulty-stratified task pool, and then start optimizing toward the concrete goal of “letting the model complete tasks in fewer steps.”
