AgentOPSD
Code source and cost
- The complete implementation comes from
datawhalechina/agentic-rl-lab/experiments/agentopsd. This page was checked against commit8630864; 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.

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:

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.
| Method | Primary supervision | Granularity | What Teacher sees |
|---|---|---|---|
| GRPO | Same-task group outcome rewards | Full trajectory | No Teacher |
| OPSD | Self-scoring on Student completions | Reasoning tokens | Reference solution |
| AgentOPSD | Outcome GRPO + Self-Teacher local evidence | Agent turns | Task-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.

Configuration
| Item | Configuration |
|---|---|
| Base model | Qwen/Qwen3.5-4B |
| Training method | PyTRIO LoRA, rank 32 (attention + MLP) |
| Environment & splits | ALFWorld text-only (train 3,553 / valid_seen 140 / valid_unseen 134) |
| Training steps | 80 updates (10,240 trajectories total) |
| Batch per update | 16 games × group 8 = 128 trajectories |
| Horizon & token budgets | ≤ 50 turns · ≤ 14,336 Student tokens (+ 2,048 reserved for Teacher skills) · ≤ 512 tokens / action |
| Rollout sampling | temperature=1.0, top_p=1.0 |
| Reward | Pure binary 0/1 outcome (no invalid-action penalty) |
| Turn credit | gamma=0.95, reshape_lambda=0.5, weight_bound=0.2, epsilon=1e-4 |
| Teacher scoring | teacher_concurrency=16 (one compute_logprobs_async call per full trajectory) |
| Loss | Built-in PyTRIO ppo, clip [0.8, 1.24], PPO_EPOCHS=1 |
| Optimizer | Adam, lr 4e-6, β (0.9, 0.95), grad_clip_norm=1.0 |
| Checkpoints | Save state and sampler weights at Step 40, Step 80, and end |
| Random seed | 42 |
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
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 sheetUse 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.
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:
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 with initial belief , then recursively accumulates discounted evidence and relative belief shifts:
Outcome-aligned turn credits are standardized within the trajectory, clipped to ([0.8, 1.2]), and blended with the sequence advantage:
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:
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.advantageAfter 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:
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 disabled2. Full 80-step training run
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 onlineOnline 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:


Evaluation
Evaluate all checkpoints strictly without skills on the fixed 274 games (valid_seen 140 + valid_unseen 134, temperature=0.01, seed=42):
# 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.pyReference skill-free evaluation results:

| Model / Checkpoint | Valid Seen (140) | Valid Unseen (134) | Overall (274) | Mean Invalid Actions |
|---|---|---|---|---|
| Qwen3.5-4B Base | 60.0% | 57.5% | 58.8% | 7.07 |
| AgentOPSD Step 40 | 61.4% | 62.7% | 62.0% | 6.74 |
| AgentOPSD Step 80 | 64.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.07to5.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
| Metric | What it checks |
|---|---|
reward/success_rate / reward/mean | Online rollout success (noisy across batches; health check only) |
advantage/degenerate_group_rate | Fraction of all-success or all-failure zero-gradient groups |
opsd/evidence_abs_mean | Magnitude of Teacher–Student action logprob gap |
opsd/delta_b_abs_mean | Magnitude of turn-level belief change (verifies active credit signal) |
opsd/weight_mean / opsd/weight_min / opsd/weight_max | Confirms balanced turn weights centered near 1.0 within [0.8, 1.2] |
tokens/teacher_scored / train/action_tokens | Teacher-scored token volume vs. action tokens entering PPO |
trajectory/truncated_rate | Fraction of rollouts truncated at the 14,336-token Student cap |
Reproduction boundaries
- Algorithmic reproduction rather than full-paper replication: uses
Qwen/Qwen3.5-4BLoRA 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 0baseline 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.
Was this documentation helpful?