Skip to content

Agentic RL

AgentOPSD

Code source and cost

  • The complete implementation comes from datawhalechina/agentic-rl-lab/experiments/agentopsd. This page was checked against commit 8630864; the source links and commands below refer to that revision.
  • The 80-step reference training run (10,240 long trajectories) cost ¥675.69 on PyTRIO, consuming 762.21M prefilling tokens (549.26M cached) / 30.52M train tokens / 9.98M sample tokens. This is a measured reference run rather than fixed pricing.
  • Because this project spans ALFWorld environments, SkillBank mapping, same-snapshot Teacher scoring, and turn-level credit assignment, this page focuses on the core logic while the source repository remains the runnable reference.

PyTRIO token usage and cost for the 80-step AgentOPSD training run

Introduction ​

In long-horizon agent tasks like ALFWorld, standard GRPO assigns one sequence-level advantage from the final 0/1 outcome to every turn equally—rewarding detours and pivotal steps alike. AgentOPSD keeps GRPO's outcome direction while adding a same-snapshot Self-Teacher for fine-grained turn-level credit assignment:

Agent loop, turn-level OPSD, and sequence-level GRPO in the AgentOPSD paper

The same frozen parameter snapshot plays both roles within each training step:

  • Student: interacts with ALFWorld without any skills, matching deployment conditions;
  • Self-Teacher: uses the exact same frozen snapshot with task-specific SkillBank text prepended to the initial prompt, re-scoring every assistant action token along the Student's trajectory;
  • Verifier: assigns a pure 0/1 outcome reward based on final task completion.
MethodPrimary supervisionGranularityWhat Teacher sees
GRPOSame-task group outcome rewardsFull trajectoryNo Teacher
OPSDSelf-scoring on Student completionsReasoning tokensReference solution
AgentOPSDOutcome GRPO + Self-Teacher local evidenceAgent turnsTask-matched Skills

Key design boundary:

The final outcome determines the update direction, while the Self-Teacher applies only a bounded per-turn multiplier (0.9×–1.1×) without rewriting trajectories or flipping reward signs. All evaluations run strictly without skills.

AgentOPSD turn-level credit recursion and bounded advantage reshaping

Configuration ​

ItemConfiguration
Base modelQwen/Qwen3.5-4B
Training methodPyTRIO LoRA, rank 32 (attention + MLP)
Environment & splitsALFWorld text-only (train 3,553 / valid_seen 140 / valid_unseen 134)
Training steps80 updates (10,240 trajectories total)
Batch per update16 games × group 8 = 128 trajectories
Horizon & token budgets≤ 50 turns · ≤ 14,336 Student tokens (+ 2,048 reserved for Teacher skills) · ≤ 512 tokens / action
Rollout samplingtemperature=1.0, top_p=1.0
RewardPure binary 0/1 outcome (no invalid-action penalty)
Turn creditgamma=0.95, reshape_lambda=0.5, weight_bound=0.2, epsilon=1e-4
Teacher scoringteacher_concurrency=16 (one compute_logprobs_async call per full trajectory)
LossBuilt-in PyTRIO ppo, clip [0.8, 1.24], PPO_EPOCHS=1
OptimizerAdam, lr 4e-6, β (0.9, 0.95), grad_clip_norm=1.0
CheckpointsSave state and sampler weights at Step 40, Step 80, and end
Random seed42

Long histories plus full-trajectory Teacher re-scoring make prefilling the dominant cost (762.21M tokens), though 549.26M cached prefix tokens significantly reduce the bill.

Project layout ​

text
experiments/agentopsd/
├── data.py          # Discover, filter, and fix ALFWorld game order
├── protocol.py      # alfworld_step schema, Student/Teacher prompts, strict token prefixes
├── environment.py   # Isolated per-branch TextWorld environments for each game
├── skills.py        # Load pinned SkillBank and map task_type → skill deterministically
├── skills/alfworld/ # Pinned general and task-specific Skill assets
├── rollout.py       # Concurrent skill-free Student rollouts with action spans & old logprobs
├── teacher.py       # Prepend skills, score full trajectory once, slice per-turn evidence
├── advantages.py    # GRPO sequence advantage, belief recursion, and bounded turn reshaping
├── loss.py          # Build action-only PPO Datums
├── train.py         # Main loop: snapshot → rollout → teacher → credit → PPO → checkpoint
├── eval.py          # Skill-free concurrent 274-game evaluation with full JSONL logs
├── analysis.py      # Verify identical game splits and plot checkpoint comparison
└── start.md         # Complete quick-start command sheet

Use the complete source directory to run the example.

Environment and data ​

Requires Python >=3.13. Run all commands from the repository root; ALFWorld environments, skill selection, and credit computation run locally while sampling, Teacher scoring, and LoRA training run remotely on PyTRIO.

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

uv sync --extra alfworld
trio login
swanlab login

uv run --extra alfworld alfworld-download \
    --data-dir "$PWD/experiments/agentopsd/datasets/alfworld"

Core logic ​

1. Same-snapshot skill-free rollout and deterministic skill mapping ​

Each step freezes one policy snapshot sampling_client. The Student runs 16 games × 8 trajectories without skills (rollout.py), recording each turn's exact [action_start, action_end) token span and old logprobs.

skills.py maps ALFWorld's task_type deterministically to general_skills plus the matching task skill—avoiding noisy retrieval and ensuring no reward or future observation leaks into the Teacher prompt.

2. Single-pass Teacher scoring and action-span alignment ​

teacher.py replaces only the initial Student prompt prefix with the skill-augmented Teacher prefix and appends student_suffix untouched. Because trajectories grow strictly by prefix extension, each trajectory requires just one compute_logprobs_async() call on the same frozen snapshot; prefix_offset aligns every action span and sums token logprob gaps into turn evidence:

python
prefix_offset = teacher_initial_length - trajectory.student_initial_length
for step in trajectory.steps:
    values = teacher_logprobs[step.action_start + prefix_offset : step.action_end + prefix_offset]
    evidence = sum(teacher - student for teacher, student in zip(values, step.logprobs))

3. Belief recursion and bounded turn advantage reshaping ​

advantages.py computes the group-level GRPO sequence advantage Aseq=(ri−rˉ)/(σr+ϵ)A_{\text{seq}} = (r_i - \bar{r}) / (\sigma_r + \epsilon) with initial belief b0=rˉb_0 = \bar{r}, then recursively accumulates discounted evidence and relative belief shifts:

Et=γEt−1+et,Bt=σ(logit⁡(b0)+Et),ΔBt=Bt−Bt−1E_t = \gamma E_{t-1} + e_t, \qquad B_t = \sigma(\operatorname{logit}(b_0) + E_t), \qquad \Delta B_t = B_t - B_{t-1}

Outcome-aligned turn credits sign⁡(Aseq)⋅ΔBt\operatorname{sign}(A_{\text{seq}}) \cdot \Delta B_t are standardized within the trajectory, clipped to wt∈[1−b,1+b]w_t \in [1 - b, 1 + b] ([0.8, 1.2]), and blended with the sequence advantage:

At=Aseq⋅((1−λ)+λwt)A_t = A_{\text{seq}} \cdot \bigl((1 - \lambda) + \lambda w_t\bigr)

With weight_bound=0.2 and reshape_lambda=0.5, the final multiplier stays strictly within [0.9, 1.1]. All-success or all-failure groups produce zero sequence advantage and are skipped.

4. Action-only token masking and built-in PPO update ​

loss.py writes step.logprobs and credit.advantage exclusively onto [action_start, action_end) positions while leaving all system, user, and observation tokens at 0.0:

python
for step, credit in zip(trajectory.steps, trajectory.turn_credits):
    for offset, old_logprob in enumerate(step.logprobs):
        position = step.action_start + offset
        old_logprobs_by_token[position] = old_logprob
        advantages_by_token[position] = credit.advantage

After a uniform autoregressive shift, the batch runs one built-in ppo forward_backward (clip_low=0.8, clip_high=1.24) and one optim_step.

Run training ​

1. Minimal smoke check ​

Validate the environment, Student rollout, Teacher scoring, and PPO path with a 1-step check:

bash
uv run --extra alfworld python experiments/agentopsd/train.py \
    --max-steps 1 \
    --tasks-per-update 1 \
    --group-size 4 \
    --max-turns 20 \
    --save-every 1 \
    --seed 3 \
    --swanlab-mode disabled

2. Full 80-step training run ​

bash
uv run --extra alfworld python experiments/agentopsd/train.py \
    --base-model Qwen/Qwen3.5-4B \
    --max-steps 80 \
    --tasks-per-update 16 \
    --group-size 8 \
    --max-turns 50 \
    --max-trajectory-tokens 14336 \
    --max-action-tokens 512 \
    --temperature 1.0 \
    --top-p 1.0 \
    --teacher-concurrency 16 \
    --gamma 0.95 \
    --reshape-lambda 0.5 \
    --weight-bound 0.2 \
    --ppo-clip-low 0.8 \
    --ppo-clip-high 1.24 \
    --lora-rank 32 \
    --learning-rate 4e-6 \
    --save-every 40 \
    --swanlab-mode online

Online reward fluctuates as sampled games vary per update, while AgentOPSD diagnostics confirm active turn-level reshaping: opsd/evidence_abs_mean and opsd/delta_b_abs_mean stay non-zero, opsd/weight_mean centers around 1.0, and opsd/weight_min frequently reaches 0.8:

Online reward and success-rate curves across the 80-step AgentOPSD run

AgentOPSD diagnostic curves: Teacher evidence, belief change, and turn weights

Evaluation ​

Evaluate all checkpoints strictly without skills on the fixed 274 games (valid_seen 140 + valid_unseen 134, temperature=0.01, seed=42):

bash
# Base model
uv run --extra alfworld python experiments/agentopsd/eval.py \
    --base-model Qwen/Qwen3.5-4B \
    --split all \
    --games-per-batch 16 \
    --temperature 0.01 \
    --seed 42 \
    --output experiments/agentopsd/eval_results/base-qwen35-4b-eval.jsonl \
    --swanlab-mode disabled

# Checkpoint (replace with saved sampler weights path)
uv run --extra alfworld python experiments/agentopsd/eval.py \
    --base-model Qwen/Qwen3.5-4B \
    --model-path 'trio://<your_sampler_weights_path>' \
    --split all \
    --games-per-batch 16 \
    --temperature 0.01 \
    --seed 42 \
    --output experiments/agentopsd/eval_results/checkpoint-eval-step80.jsonl \
    --swanlab-mode disabled

# Verify identical game IDs and plot comparison chart
uv run python experiments/agentopsd/analysis.py

Reference skill-free evaluation results:

Skill-free ALFWorld evaluation across 274 games for Base, Step 40, and Step 80

Model / CheckpointValid Seen (140)Valid Unseen (134)Overall (274)Mean Invalid Actions
Qwen3.5-4B Base60.0%57.5%58.8%7.07
AgentOPSD Step 4061.4%62.7%62.0%6.74
AgentOPSD Step 8064.3%67.2%65.7%5.68
  • Overall success rose by +6.9 percentage points (161/274 → 180/274), with Valid Unseen improving by +9.7 pp;
  • Mean invalid actions fell from 7.07 to 5.68 (-1.39) even without an explicit invalid-action reward penalty;
  • Both splits improved monotonically from Base → Step 40 → Step 80 under zero-skill inference.

Metrics to monitor ​

MetricWhat it checks
reward/success_rate / reward/meanOnline rollout success (noisy across batches; health check only)
advantage/degenerate_group_rateFraction of all-success or all-failure zero-gradient groups
opsd/evidence_abs_meanMagnitude of Teacher–Student action logprob gap
opsd/delta_b_abs_meanMagnitude of turn-level belief change (verifies active credit signal)
opsd/weight_mean / opsd/weight_min / opsd/weight_maxConfirms balanced turn weights centered near 1.0 within [0.8, 1.2]
tokens/teacher_scored / train/action_tokensTeacher-scored token volume vs. action tokens entering PPO
trajectory/truncated_rateFraction of rollouts truncated at the 14,336-token Student cap

Reproduction boundaries ​

  • Algorithmic reproduction rather than full-paper replication: uses Qwen/Qwen3.5-4B LoRA and built-in PyTRIO PPO without full-parameter training or full-vocabulary entropy regularization.
  • Matched GRPO baseline still needed: this run confirms the AgentOPSD pipeline works and outperforms Base under skill-free evaluation, but isolating turn-level credit gains over plain GRPO requires a matched --reshape-lambda 0 baseline and multi-seed runs.
  • Prefilling-heavy cost: growing multi-turn prefixes plus full-trajectory Teacher scoring dominate token usage; estimate costs on a short run before scaling.

For full discussion and additional details, see the source repository's AgentOPSD README.