ReTool
Code source and cost
- The complete implementation comes from
datawhalechina/agentic-rl-lab/experiments/retool. This page was checked against commit8630864; the source links and commands below refer to that revision.- 20-step verification run: ¥31.66 in total (¥22.89 for training across 4.34M prefilling / 1.66M train / 1.77M sample tokens, plus ¥4.16 and ¥4.61 for Base and Step 20 AIME25 evaluations).
- 200-step training run: ¥224.44 (48.67M prefilling / 15.97M train / 15.84M sample tokens); each AIME25 evaluation (30 problems × 12 samples) costs roughly ¥4–5. All numbers are measured reference runs rather than fixed pricing.
- See the SwanLab run for training curves. Because this example spans multiple modules, this page covers the key code and full training loop while the source repository remains the runnable reference.


Introduction
ReTool uses reinforcement learning to teach a model during mathematical reasoning to decide:
- when to write Python code for computation;
- what code to execute for calculation, verification, or enumeration;
- how to continue reasoning or fix code based on stdout/stderr feedback;
- when to stop calling the interpreter and produce the final
\boxed{}answer.
A ReTool trajectory alternates between reasoning and code execution across multiple turns:
assistant reasoning
→ code_interpreter(code)
→ tool observation (stdout / stderr)
→ more assistant reasoning or code revision
→ ...
→ \boxed{<final answer>}This reproduction uses Qwen/Qwen3.5-4B, PyTRIO, and a local Python subprocess sandbox, preserving the two core elements of ReTool: code-interlaced rollout and outcome-only reward. The key boundary is:
Only the model's LoRA weights are trained. The local Python sandbox and its returned output are a fixed environment—they stay in context but do not enter the loss.
Compared with the full paper pipeline, this reproduction makes three deliberate simplifications:
- Native Qwen
<tool_call>protocol: no new special tokens or custom chat-template modifications; - Skip cold-start SFT and run RL directly on the base model: in a smoke test,
Qwen/Qwen3.5-4Balready reached an 87.5% tool-call rate and 85.4% valid-call rate with mixed within-group rewards, providing a healthy GRPO signal without SFT; - Built-in PPO-clip update: uses PyTRIO's
ppoloss with clip thresholds0.8 / 1.28(matching the clip-higher setting in the official recipe).

Configuration
Both the 20-step verification run and the 200-step training run share the same configuration except for --max-steps and --save-every:
| Item | Configuration |
|---|---|
| Base model | Qwen/Qwen3.5-4B |
| Training method | PyTRIO LoRA, rank 32 |
| Training data | BytedTsinghua-SIA/DAPO-Math-17k |
| Batch per step | 8 questions × group 8 = 64 trajectories |
| Turn limits | max_code_calls=4, max_assistant_turns=6 |
| Token budgets | trajectory ≤ 8,192 · assistant turn ≤ 1,024 · tool response ≤ 512 |
| Rollout sampling | temperature=1.0, top_p=1.0 |
| Code sandbox | Local subprocess · 30s timeout · 8 workers |
| Optimizer | Adam, lr 4e-5, β (0.9, 0.95) |
| Reward | Last \boxed{} in final 300 chars + math_verify, +1 / -1 |
| Advantage | GRPO group-centered; observation tokens masked to 0 |
| Loss | ppo, clip 0.8 / 1.28 |
| Checkpoints | Every 50 steps for 200-step run (every 5 steps for 20-step check) |
| Random seed | 42 |
Main differences from the official recipe: the official setup uses full-parameter Qwen2.5-32B, train_batch_size=512, n_resp_per_prompt=16, 16k context, and max_turns=8. This example scales down proportionally with LoRA and follows the paper's pure outcome-only reward without the turn-based penalty shaping present in the released recipe code.
Project layout
experiments/retool/
├── prepare_data.py # Download and clean DAPO-Math-17k into train/dev JSONL
├── data.py # Read and cycle local JSONL records
├── protocol.py # code_interpreter tool schema, prompt, and token-level continuation
├── sandbox.py # Local Python subprocess sandbox, throttling, and sanitization
├── reward.py # \boxed{} extraction and math_verify equivalence check
├── rollout.py # Multi-turn code-interlaced rollout state machine and group advantages
├── train.py # Datum construction, dynamic micro-batch packing, and PPO update
├── eval.py # AIME25 evaluation (supports retool and text-only modes)
├── analysis.py # Aggregate checkpoint JSONL outputs and plot summary chart
└── start.md # Quick-start command sheetUse the complete source directory to run the example. The sections below focus on the core algorithm logic.
Environment and data
Only a networked CPU machine is needed locally to run the code sandbox and training orchestration. Sampling, LoRA forward/backward passes, and optimizer updates run remotely on PyTRIO.
git clone https://github.com/datawhalechina/agentic-rl-lab.git
cd agentic-rl-lab
git checkout 8630864d9f007cb871b096b23d7a2242b2260be4
uv sync
trio login
swanlab loginDownload and clean BytedTsinghua-SIA/DAPO-Math-17k:
uv run python experiments/retool/prepare_data.pyThis creates:
experiments/retool/datasets/
├── train.jsonl # Training split (question + answer)
└── dev.jsonl # 50 dev problems (smoke tests only, excluded from training)Each training record contains only the cleaned math problem and reference answer:
{
"id": "40f50547-...",
"question": "The points $P,$ $Q,$ and $R$ are represented by ...",
"answer": "3",
"data_source": "math_dapo"
}prepare_data.py strips the outer "Answer: $Answer" prompt wrapper shipped with DAPO-Math-17k so it does not conflict with the \boxed{} protocol.
Core logic
1. Tool protocol and token-in token-out continuation
protocol.py registers code_interpreter as the single native function tool and fixes enable_thinking=False (Qwen3 thinking mode discourages code generation):
CODE_TOOL = {
"type": "function",
"function": {
"name": "code_interpreter",
"description": "...", # Emphasizes print() output and stateless execution
"parameters": {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "The Python code to be executed.",
}
},
"required": ["code"],
},
},
}
rendered = tokenizer.apply_chat_template(
messages,
tools=[CODE_TOOL],
tokenize=True,
add_generation_prompt=add_generation_prompt,
enable_thinking=False,
)The system prompt specifies resource and protocol rules: keep executions short and low-memory, avoid file I/O, print values with print(), and never invoke the tool and output the final answer in the same turn.
Multi-turn continuation is strictly token-in token-out: build_next_prompt() appends the exact sampled completion_tokens plus only the incremental closing and tool-observation tokens, avoiding decode/re-encode drift.
Because the Qwen3.5 chat template strips assistant text and can split messages containing
</think>,build_next_prompt()computes the incremental closing and observation tokens using placeholder assistant content to locate boundaries reliably.
2. Multi-turn trajectory branching and concurrent execution
rollout.py drives the multi-turn state machine:
First turn: 1 shared prompt per question × num_samples=8 → 8 branches
Later turns: independent prompts × num_samples=1 via concurrent sample_async
Code calls: all pending calls in a round run concurrently via execute_pending_async()Each trajectory stays strictly sequential internally (assistant generation → parse <tool_call> → sandbox execution → append observation → next turn) and terminates once the model produces a final answer or hits max_code_calls, max_assistant_turns, or the 8,192-token budget.
3. Local Python sandbox and output sanitization
sandbox.py replaces a cloud sandbox with isolated local subprocesses—every call starts a fresh stateless Python process:
process = subprocess.Popen(
[self.python, "-B", "-c", bootstrap],
stdout=stdout_file,
stderr=stderr_file,
env=env,
start_new_session=True,
)Four safeguards keep training stable:
- Cross-loop throttling:
threading.BoundedSemaphore(8)limits concurrent workers across per-step event loops; - Timeout and process-group cleanup: a 30s wall-clock timeout kills the whole process group via
os.killpg(..., SIGKILL), backed byRLIMIT_CPUinside the bootstrap snippet; - Bounded output and BLAS limits: stdout/stderr write to anonymous temporary files and only the tail is read (4,096 chars, later capped to 512 tokens during rollout), while BLAS thread env vars are pinned to 1;
- Raw stderr + template-token sanitization: tracebacks are returned unmodified to encourage self-correction, while
sanitize_tool_content()rewrites special markers (<|im_start|>,<|im_end|>,<tool_response>,</tool_response>) so code output cannot corrupt observation framing.
4. Pure outcome reward
reward.py scores only the final answer and gives no bonus for invoking code:
| Final outcome | Reward |
|---|---|
Valid \boxed{} in final 300 chars and mathematically equivalent | +1.0 |
Wrong answer or missing valid \boxed{} | -1.0 |
def score_answer(text: str, reference: str) -> RewardResult:
answer = extract_last_boxed(text[-ANSWER_WINDOW_CHARS:])
if answer is None:
return RewardResult(-1.0, False, False, None)
correct = answers_equivalent(answer.strip(), reference.strip())
return RewardResult(1.0 if correct else -1.0, correct, True, answer)5. Group-centered advantage and observation token masking
After all eight trajectories for a question finish, assign_group_advantages() centers rewards within the group:
Degenerate groups where every trajectory has advantage == 0 are skipped. build_datum() then concatenates all turns into one sequence while masking system, user, and tool-observation tokens to zero old logprob and zero advantage:
full_tokens.extend(delta_observation)
full_tokens.extend(turn.completion_tokens)
old_logprobs_by_token.extend([0.0] * len(delta_observation))
old_logprobs_by_token.extend(turn.logprobs)
advantages_by_token.extend([0.0] * len(delta_observation))
advantages_by_token.extend(
[trajectory.advantage] * len(turn.completion_tokens)
)
input_tokens = full_tokens[:-1]
target_tokens = full_tokens[1:]
old_logprobs = old_logprobs_by_token[1:]
advantages = advantages_by_token[1:]All four arrays undergo the same autoregressive shift and maintain identical length so only assistant-generated tokens contribute gradients.
6. Dynamic micro-batch packing and PPO update
One logical step contains up to 8 × 8 = 64 trajectories of up to 8,192 tokens. After computing group advantages, train.py packs Datums into micro-batches bounded by 32 items and items × max_sequence_length ≤ 64,000, scaling each micro-batch's advantages by n_k / N so accumulated gradients equal the global sample mean:
PPO_LOSS_CONFIG = {"clip_low_threshold": 0.8, "clip_high_threshold": 1.28}
datums = build_training_datums(trajectories)
micro_batches = pack_micro_batches(datums)
for micro_batch in micro_batches:
training_client.forward_backward(
weight_micro_batch_for_global_mean(
micro_batch,
total_samples=len(trajectories),
),
loss_fn="ppo",
loss_fn_config=PPO_LOSS_CONFIG,
).result()
if micro_batches:
training_client.optim_step(adam_params).result()Only one optim_step() runs per logical batch.
Run training
1. 20-step verification run
Start with 20 steps to verify the closed loop (reference training cost ¥22.89):
uv run python experiments/retool/train.py \
--max-steps 20 \
--save-every 5 \
--run-name retool-qwen35-4b-step20In the reference check, moving from the first 10 steps to the last 10 steps raised reward/correct from 0.289 to 0.389 and rollout/code_calls from 1.24 to 1.72, with zero degenerate groups.
2. Full 200-step training run
Once validated, run 200 steps (saving *-state and *-weights every 50 steps):
uv run python experiments/retool/train.py \
--max-steps 200 \
--save-every 50 \
--run-name retool-qwen35-4b-step200Across the 200-step SwanLab curves, behavior progresses in three stages: the model first learns to emit well-formed tool calls (valid_tool_call_rate 0.6 → 0.95), then writes runnable code (sandbox/error_rate 0.32 → 0.18), and finally uses code effectively to solve problems (reward/correct 0.2 → 0.6, reward/format 0.25 → 0.85).



AIME25 evaluation
eval.py reads AIME25 from experiments/opsd/datasets/aime_2025 by default (prepare it first with uv run python experiments/opsd/00-datasets.py --only aime25, or pass --dataset-path).
Evaluate both the base model and saved trio:// sampler weights under identical settings:
# Base model
uv run python experiments/retool/eval.py \
--mode retool \
--val-n 12 \
--temperature 1.0 \
--top-p 0.7 \
--output experiments/retool/eval-results/aime25-retool-base.jsonl
# Checkpoint
uv run python experiments/retool/eval.py \
--mode retool \
--val-n 12 \
--temperature 1.0 \
--top-p 0.7 \
--model-path trio://<your_sampler_weights_path> \
--output experiments/retool/eval-results/aime25-retool-step200.jsonlThe script also supports --mode text-only (tool disabled) for a text-only baseline. Once JSONL files are collected, plot the checkpoint comparison with:
uv run python experiments/retool/analysis.pyReference AIME25 results across the 200-step run (30 problems × 12 samples, 8,192-token trajectory budget):

| Model / Checkpoint | Average@12 | Pass@12 | Format | Avg code calls | Avg turns |
|---|---|---|---|---|---|
| Qwen3.5-4B Base | 23.61% | 50.00% | 25.83% | 1.69 | 2.69 |
| Step 20 | 32.22% | 63.33% | 36.67% | 1.37 | 2.37 |
| Step 50 | 41.11% | 63.33% | 52.78% | 1.70 | 2.70 |
| Step 100 | 44.72% | 66.67% | 57.78% | 1.66 | 2.66 |
| Step 150 | 46.11% | 73.33% | 70.83% | 2.43 | 3.43 |
| Step 200 | 47.50% | 63.33% | 76.11% | 1.98 | 2.98 |
- Average@12: fraction of correct generations out of 360 (an estimate of pass@1), rising from
23.61%to47.50%(+23.89percentage points,85 → 171correct generations); - Pass@12: fraction of the 30 problems solved at least once in 12 samples, rising from
50.00%to63.33%(peaking at73.33%at Step 150); - Format: fraction of generations ending with a valid
\boxed{}answer, rising from25.83%to76.11%. Remaining unformatted rollouts are primarily long AIME derivations truncated by the 8,192-token cap.
Metrics to monitor
| Metric | What it checks |
|---|---|
reward/mean | Mean trajectory outcome reward (-1 to +1) |
reward/correct | Final-answer mathematical equivalence rate |
reward/format | Fraction of trajectories with a valid \boxed{} answer |
rollout/valid_tool_call_rate | Valid <tool_call> calls over total tool-call attempts |
rollout/code_calls | Mean code-interpreter calls per trajectory |
rollout/turns | Mean assistant turns per trajectory |
rollout/trajectory_tokens | Mean total trajectory tokens (tracks pressure on the 8k cap) |
rollout/degenerate_group_rate | Fraction of questions with zero within-group variance |
sandbox/success_rate | Fraction of sandbox runs exiting cleanly |
sandbox/error_rate | Fraction of sandbox runs failing with syntax or runtime errors |
sandbox/timeout_rate | Fraction of sandbox runs hitting the 30s timeout |
sandbox/latency | Mean wall-clock execution time per sandbox call |
train/loss_tokens_per_rollout_batch | Assistant tokens entering the PPO loss |
If reward/correct drops alongside a spike in sandbox/timeout_rate or sandbox/error_rate, inspect the local sandbox environment before attributing the drop to policy regression.
Reproduction boundaries
- 8k trajectory budget vs. 16k in the paper: the main quota trade-off; long AIME derivations get truncated and keep Format around 76%. Raising the budget to 16k is the first improvement to try.
- Local sandbox ≠ cloud sandbox:
python -B -c, 30s timeouts, andRLIMIT_CPUcatch runaway loops, but file I/O is only constrained by the system prompt and memory limits on macOS are unreliable—do not run unattended. - Skipping cold-start SFT depends on the base model:
Qwen/Qwen3.5-4Balready invokes tools reliably; other base models may still need cold-start SFT. - No dual-clip: PyTRIO's built-in
ppoloss does not supportclip_ratio_c=10.0from the official recipe. - Evaluation scale and single run: AIME25 has 30 problems, so Pass@12 naturally fluctuates by ±1–2 problems (e.g., Step 150 → 200); results come from a single run and seed.
For the full write-up and additional discussion, see the source repository's ReTool README.
Was this documentation helpful?