Skip to content

Agentic RL

Spec-o3

Code source and cost

  • The complete implementation comes from datawhalechina/agentic-rl-lab/experiments/spec-o3. This page was checked against commit 8630864; the source links and commands below refer to that revision.
  • The initial Qwen/Qwen3.5-4B training sessions cost ¥699.68 in total: ¥27.72 for Cold-start SFT (2 epochs, 6.11M train tokens) and ¥671.96 for RL epoch 1 (239.39M prefilling / 79.13M train / 26.38M sample tokens). Evaluations, debugging runs, and the follow-up 4B/9B epoch 3 runs are separate. All figures are measured reference runs rather than fixed pricing.
  • See the SwanLab runs for SFT and RL curves. Because this example combines a custom multimodal template, a local spectral plotting tool, async SFT, and multimodal GRPO, this page covers the core implementation while the source repository remains the runnable reference.

PyTRIO usage for the initial 4B Spec-o3 SFT, RL epoch 1, and evaluation sessions

Introduction ​

Spec-o3 is a multimodal tool-augmented agent for vetting rare celestial object candidates from astronomical spectra. Given a full spectrum image and diagnostic guidelines, the model makes a YES / NO judgment for one of five target classes:

Task keyTarget class
cvCataclysmic Variables
ccCarbon Stars
ssS-type Stars
gmM-type Giants
wdWhite Dwarfs

Its core mechanism is Interleaved Multimodal Chain-of-Thought (iMCoT): the model reasons over the spectrum, invokes spectral_visualization_tool with a chosen wavelength interval, receives a newly plotted zoomed-in PNG spectrum in context, and repeats until it outputs a final decision:

text
user question + full spectrum image
→ assistant <think> selects wavelength window to inspect
→ <tool_call> spectral_visualization_tool(wavelength_range, label)
→ local tool plots zoomed spectrum PNG from .npz array
→ <tool_response> appends new image to context
→ assistant continues reasoning or outputs <answer>\boxed{YES|NO}...</answer>

Spec-o3 paper framework: multi-turn spectral visualization, interleaved multimodal reasoning, and GRPO training

This example adapts the paper's two-stage pipeline (Cold-start SFT → multimodal GRPO) to Qwen/Qwen3.5-4B / Qwen/Qwen3.5-9B LoRA on PyTRIO:

Only the model's LoRA weights are trained. The local spectral plotting tool and its returned text and images remain fixed environment observations with zero loss weight and zero advantage.

Configuration ​

ItemConfiguration (initial 4B reference / follow-up 4B & 9B)
Base modelQwen/Qwen3.5-4B (follow-up comparison with Qwen/Qwen3.5-9B)
Training methodPyTRIO LoRA, rank 32
SFT dataMaxwell-Jia/Spec-o3-ColdStartSFT (848 train / 94 val)
RL & eval dataMaxwell-Jia/SpecVI-Bench (3,108 RL train / 256 dev / 6,754 test)
SFT settings2 epochs (424 steps), batch size 4, Adam lr 2e-5, cross_entropy
RL settings1 epoch (389 rollout batches; extended to 3 epochs), 8 questions × group 8 = 64 rollouts, Adam lr 1e-6
RL horizon & budgetsUp to 8 turns (up to 7 tool calls), ≤ 2,048 tokens / turn, ≤ 16,384 total context
RL reward1[correct] - 0.2 × 1[format_error] (no tool-call bonus)
RL advantageGroup-standardized (r - mean) / (std(ddof=1) + 1e-6); zero-variance groups skipped
RL lossppo, clip [0.8, 1.2]
CheckpointsSFT every epoch; RL every 100 rollout steps and epoch end (state + sampler)

Main differences from the authors' released setup: the paper trains Qwen2.5-VL-3B/7B-Instruct on 8×H100 with full-parameter LLM SFT (5 epochs, cosine schedule), RL batch size 64 × 8 (3 epochs), and 32K context. This reproduction transfers the method to Qwen3.5 LoRA rank 32, constant learning rates, batch size 8, and a 16K context cap.

Project layout ​

text
experiments/spec-o3/
├── prepare_data.py                 # Download, clean, split SFT/SpecVI-Bench data and .npz spectra
├── templates/qwen3_5_spec_o3.jinja # Preserves multi-turn reasoning and marks {% generation %} spans
├── protocol.py                     # ImageChunk packing, SFT/RL Datum builders, action parser
├── tools.py                        # Rest-frame redshift correction and zoomed PNG plotting
├── rollout.py                      # Multi-turn multimodal rollout loop preserving tokens & logprobs
├── train_sft.py                    # Async multimodal SFT, validation loss, and checkpoint saving
├── train_rl.py                     # Group rollouts, rewards, standardized advantages, PPO updates
├── eval.py                         # Concurrent 256-sample dev evaluation with full artifacts
├── analysis.py                     # Plot the five-model comparison figure
└── start.md                        # Complete quick-start command sheet

Use the complete source directory to run the example.

Environment and data ​

Requires Python >=3.13 and pytrio==0.2.9. Data prep, plotting, and orchestration run locally while training and sampling execute remotely on PyTRIO. Run all commands inside experiments/spec-o3/:

bash
git clone https://github.com/datawhalechina/agentic-rl-lab.git
cd agentic-rl-lab
git checkout 8630864d9f007cb871b096b23d7a2242b2260be4

uv sync --locked
cd experiments/spec-o3
uv run trio login
uv run swanlab login

Prepare SFT data first, then RL/benchmark data (bench reads the SFT object list to keep SFT spectra out of the dev split):

bash
uv run python prepare_data.py sft
uv run python prepare_data.py bench

This populates datasets/sft/ (sft_train.jsonl 848 rows, sft_val.jsonl 94 rows) and datasets/rl/ (bench_rl_train.jsonl 3,108 rows, bench_dev.jsonl 256 rows, spectra/*.npz, and initial spectrum PNGs). JSONL files store absolute paths; re-run preparation if moving directories.

Core logic ​

1. Custom multimodal chat template and ImageChunk packing ​

qwen3_5_spec_o3.jinja adapts Qwen3.5's chat template in two ways: it preserves reasoning_content across every assistant turn and wraps assistant spans in {% generation %} so the tokenizer emits an exact supervision mask.

pack_chunks() in protocol.py expands each <|image_pad|> token into a trio.ImageChunk sized via the matching image_processor, assigning zero loss weight to every visual token position:

python
chunk = image_chunk(next(paths), image_processor)
chunks.append(chunk)
targets.extend([0] * chunk.expected_tokens)
weights.extend([0.0] * chunk.expected_tokens)

Subsequent tool-generated plots enter ModelInput through the exact same ImageChunk mechanism.

2. Local spectral zoom tool ​

tools.py loads wavelength, flux, and redshift from the pre-extracted .npz file, shifts to rest-frame wavelength, slices the requested window, and renders a fresh PNG:

python
wavelength = np.asarray(wavelength) / (1 + redshift)
low, high = wavelength_range
selected = (wavelength >= low) & (wavelength <= high)
ax.plot(wavelength[selected], flux[selected])

If fewer than two data points fall in the window, the tool returns a text message instead of an image so the model can adjust its range on the next turn.

3. Cold-start SFT to teach the interleaved protocol ​

The 4B base model achieves only 0.39% strict format compliance on the dev set, making cold-start SFT essential. train_sft.py runs async cross_entropy training over full demonstration trajectories, supervising only assistant reasoning, tool calls, and answers while normalizing weights by total batch assistant tokens.

4. Multi-turn multimodal rollout and token-in token-out continuation ​

train_rl.py samples turn 1 with num_samples=8 per question, then rollout.py advances all 8 trajectories concurrently:

  • Each turn appends exact sampled tokens and logprobs without re-encoding assistant text;
  • After plotting a new image, tool_continuation() encodes only the newly appended <tool_response> and next-turn prefix, filling target_tokens, logprobs, and action_mask with zeros;
  • Trajectories stop on a final answer, invalid action, 8 turns, or the 16,384-token budget.

5. Outcome reward, group-standardized advantage, and PPO update ​

trajectory_reward() scores only final answer accuracy and strict formatting, with no bonus for calling the tool:

r(τ)=1[correct]−0.2 1[format error]r(\tau) = \mathbb{1}[\text{correct}] - 0.2\,\mathbb{1}[\text{format error}]

AnswerFormatReward
CorrectValid1.0
CorrectInvalid0.8
WrongValid0.0
WrongInvalid-0.2

build_training_samples() standardizes rewards across the 8 trajectories of each question using sample standard deviation (ddof=1) and skips zero-variance groups (np.ptp == 0):

Ai=ri−mean⁡(r1,…,r8)std⁡(r1,…,r8)+10−6A_i = \frac{r_i - \operatorname{mean}(r_1, \ldots, r_8)}{\operatorname{std}(r_1, \ldots, r_8) + 10^{-6}}

Advantages are then normalized by total assistant tokens in the batch before one forward_backward_async(loss_fn="ppo") update with clip range [0.8, 1.2] and one optim_step_async.

Run training ​

1. Cold-start SFT (2 epochs) ​

bash
uv run python train_sft.py \
    --base-model Qwen/Qwen3.5-4B \
    --epochs 2 \
    --batch-size 4 \
    --rank 32 \
    --learning-rate 2e-5 \
    --run-name spec-o3-sft \
    --swanlab-mode online

For 9B, pass --base-model Qwen/Qwen3.5-9B with a distinct --run-name. Each epoch prints state_path (for RL) and sampler_path (for evaluation).

Spec-o3 4B cold-start SFT training loss and assistant supervised tokens per batch

2. GRPO from the SFT state ​

Replace <SFT_STATE_PATH> with the epoch 2 state_path printed above (the script restores the matching 4B/9B base model from the state):

bash
uv run python train_rl.py \
    --state-path '<SFT_STATE_PATH>' \
    --epochs 1 \
    --batch-size 8 \
    --group-size 8 \
    --learning-rate 1e-6 \
    --max-turns 8 \
    --max-tokens 2048 \
    --max-seq-len 16384 \
    --save-every 100 \
    --run-name spec-o3-rl \
    --swanlab-mode online

Set --epochs 3 to reproduce the 3-epoch checkpoints. Below are the SwanLab curves from the initial 4B RL epoch 1 run (format compliance climbs near 0.95 while reward and accuracy improve with batch-to-batch variance):

Initial 4B RL epoch 1 training curves: reward, strict format rate, assistant tokens, and training accuracy

Dev set evaluation ​

Evaluate on the fixed 256-sample dev set (bench_dev.jsonl, concurrency 16, temperature=0.6, seed=42, up to 8 turns, 16,384 context):

bash
# 4B Base (automatically appends a format reminder when --model-path is omitted)
uv run python eval.py \
    --base-model Qwen/Qwen3.5-4B \
    --output outputs/base-dev \
    --max-tokens 6132 \
    --max-seq-len 16384

# 4B SFT epoch 2 (use --max-tokens 6144 for a budget-matched comparison with RL)
uv run python eval.py \
    --base-model Qwen/Qwen3.5-4B \
    --model-path '<SFT_SAMPLER_PATH>' \
    --output outputs/sft-dev \
    --max-tokens 2048 \
    --max-seq-len 16384

# 4B / 9B RL checkpoint (set --base-model Qwen/Qwen3.5-9B for 9B)
uv run python eval.py \
    --base-model Qwen/Qwen3.5-4B \
    --model-path '<RL_SAMPLER_PATH>' \
    --output outputs/rl-4b-e3 \
    --max-tokens 6144 \
    --max-seq-len 16384

Summary across all five evaluated checkpoints:

Accuracy, Macro F1, strict format compliance, and solved counts across five Spec-o3 checkpoints on 256 dev samples

Model / StageMacro F1AccuracyFormatCorrect
Qwen3.5-4B Base53.99%38.67%0.39%99 / 256
Qwen3.5-4B SFT epoch 263.05%53.91%85.94%138 / 256
Qwen3.5-4B RL epoch 171.68%67.97%96.09%174 / 256
Qwen3.5-4B RL epoch 370.93%68.36%98.05%175 / 256
Qwen3.5-9B RL epoch 375.94%74.61%99.61%191 / 256

On 4B, SFT adds +39 correct samples (raising Format from 0.39% to 85.94%) and RL epoch 1 adds another +36. 9B RL epoch 3 reaches 191 / 256 with 99.61% strict format compliance and 1,011/1,011 successful tool calls. Per-task F1 for the two epoch 3 checkpoints:

ModelCC (56)CV (50)GM (51)SS (50)WD (49)
Qwen3.5-4B RL epoch 352.31%61.11%92.06%79.17%70.00%
Qwen3.5-9B RL epoch 367.80%71.79%87.72%84.62%67.80%

Metrics to monitor ​

MetricWhat it checks
train/loss / val/lossMean cross-entropy over supervised assistant tokens during SFT
train/rewardMean RL outcome reward across all rollouts
train/accuracyOnline YES/NO classification accuracy
train/format_rateFraction ending with a strict <answer>\boxed{...}</answer> block
train/degenerate_fractionFraction of questions skipped due to zero within-group reward variance
train/assistant_tokensTotal assistant tokens entering the PPO update (affected by skipped groups)
rollout/mean_generated_tokensMean generated tokens per trajectory (tracks reasoning length)
rollout/mean_turns / rollout/tool_callsMean turns per trajectory and total tool calls per batch

Reproduction boundaries ​

  • Dev split and generation budget: reported scores are on the 256-sample dev set (bench_test.jsonl with 6,754 samples is unevaluated); historical SFT evaluation used max_tokens=2048 versus 6144 for RL, so a 6,144-token SFT re-evaluation is needed for an exact budget-matched comparison.
  • Residual corrupted symbols in SFT data: 273 trajectories in the public SFT dataset still contain placeholder markers for unrecoverable scientific symbols and were kept as-is.
  • Method transfer rather than leaderboard replication: different base models (Qwen3.5-4B/9B), LoRA, 16K context, and smaller batches mean scores are not directly comparable to the paper's 8×H100 numbers.

For the full write-up and additional discussion, see the source repository's Spec-o3 README.