Skip to content

Agentic RL

ALFWorld

Code source and cost

  • The complete implementation comes from datawhalechina/agentic-rl-lab/experiments/alfworld. This page was checked against commit 8630864; the source links and commands below refer to that revision.
  • The 80-step reference training session cost ¥1,613.71 on PyTRIO, consuming 843.51M prefilling / 62.24M train / 14.28M sample tokens across 5,120 long trajectories. This is a measured reference run rather than fixed pricing.
  • See the SwanLab runs for training curves. Because this project spans environment wrappers, a multi-turn rollout state machine, training, and evaluation, this page focuses on the core logic while the source repository remains the runnable reference.

PyTRIO usage for the 80-step ALFWorld training run

Introduction ​

ALFWorld aligns TextWorld (a PDDL-backed text environment) with ALFRED / AI2-THOR (3D embodied household rooms), requiring an agent to navigate rooms and manipulate objects to complete multi-step chores (e.g., Put a heated apple in the fridge).

Aligned TextWorld text environment and AI2-THOR embodied environment in ALFWorld

This example uses ALFWorld's text-only mode with Qwen/Qwen3.5-4B and PyTRIO to implement stateful, long-horizon Agentic RL. Each trajectory can interact with the environment for up to 50 steps and 12,000 tokens, where every tool call mutates the underlying PDDL state:

text
task goal + current observation + available actions
→ assistant calls alfworld_step(action)
→ TextWorld / PDDL checks preconditions and updates state
→ returns new observation + available actions + done / won
→ appended to the full multi-turn history for the next decision

ALFWorld single-tool multi-turn interaction loop

The setup covers all six solvable ALFWorld task families (train: 3,553 games, valid_seen: 140 games, valid_unseen: 134 games):

Task typeGoal
pick_and_place_simplePick up an object and place it in a target receptacle
look_at_obj_in_lightPick up an object and examine it under a light
pick_clean_then_place_in_recepClean an object and place it in a target receptacle
pick_heat_then_place_in_recepHeat an object and place it in a target receptacle
pick_cool_then_place_in_recepCool an object and place it in a target receptacle
pick_two_obj_and_placeFind two objects of the same type and place them in a target receptacle

Scope boundary:

The original ALFWorld paper focuses on text-to-embodied alignment and DAgger imitation learning. This example uses its text-only environment with GRPO-style same-game group rollouts and group-relative advantages, updating Qwen/Qwen3.5-4B LoRA weights online with PPO. Environment and tool observations remain in context but do not enter the loss.

ALFWorld and PyTRIO same-game group rollout and PPO training loop

Configuration ​

ItemConfiguration
Base modelQwen/Qwen3.5-4B
Training methodPyTRIO LoRA, rank 32
Environment & splitsALFWorld text-only (train 3,553 / valid_seen 140 / valid_unseen 134)
Training steps80 updates (5,120 trajectories total)
Batch per update8 games × group 8 = 64 independent trajectories
Horizon & token budgets≤ 50 steps / trajectory · ≤ 12,000 trajectory tokens · ≤ 2,048 assistant tokens / turn
Rollout samplingtemperature=1.0, top_p=1.0
Reward1[won] - 0.1 × invalid_actions (episode-level only)
AdvantageSame-game reward - mean(reward) (no std division)
Lossppo, clip 0.8 / 1.2
OptimizerAdam, lr 1e-6, β (0.9, 0.95), grad_clip_norm=1.0
CheckpointsSave state and sampler weights every 20 updates
Random seed42

Most of the cost comes from prefilling (843.51M tokens): averaging 21–23 turns per episode means every new turn re-prefills the growing full interaction history.

Project layout ​

text
experiments/alfworld/
├── data.py          # Discover, filter (solvable=true), shuffle, and cycle ALFWorld games
├── protocol.py      # alfworld_step tool schema, parser, and token-level continuation
├── environment.py   # K independent TextWorld instances per game and stepping
├── rollout.py       # Async multi-turn rollout state machine, episode rewards, JSONL export
├── advantages.py    # Same-game group-relative advantages and degenerate group stats
├── train.py         # Full-trajectory Datum construction, PPO updates, SwanLab, checkpoints
├── eval.py          # Concurrent evaluation across 274 validation games with full logs
├── analysis.py      # Aggregate evaluation JSONL summaries and plot checkpoint charts
└── start.md         # Quick-start command sheet

Use the complete source directory to run the example.

Environment and data ​

Requires Python >=3.13. ALFWorld is installed as an optional dependency via --extra alfworld. TextWorld state transitions and orchestration run locally, while sampling and LoRA training execute 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

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

Once downloaded to the default experiments/alfworld/datasets/alfworld path, training and evaluation scripts locate it automatically without --data-root.

Core logic ​

1. Single-tool protocol and full-history continuation ​

protocol.py exposes a single tool alfworld_step(action: str) with enable_thinking=False. Every turn presents the task goal, current observation, and admissible actions, requiring exact object instance identifiers (such as apple 1 and fridge 1). The model cannot self-declare completion—termination comes strictly from the environment (won / done) or the 12,000-token limit.

build_next_prompt() appends only the assistant closing tokens and new tool observation onto the exact sampled completion_tokens, avoiding text re-tokenization so rollout old logprobs stay aligned with training tokens.

2. K independent environments per game and concurrent rollouts ​

ALFWorldGroup in environment.py instantiates K=8 independent TextWorld environments from the same game.tw-pddl and verifies identical initial observations on reset().

In rollout.py, turn 1 issues one num_samples=8 call on the shared prompt. After step 1, environment states diverge and all active trajectories advance concurrently via sample_async while preserving strict causality inside each trajectory.

3. Episode reward and group-centered advantage ​

Each completed trajectory receives one episode-level return (no intermediate step rewards):

ri=1[woni]−0.1×invalid_actionsir_i = \mathbb{1}[\text{won}_i] - 0.1 \times \text{invalid\_actions}_i

Both invalid tool-call formats and inadmissible environment actions increment invalid_actions. assign_advantages() then centers rewards across the 8 trajectories of the same game:

python
mean_reward = sum(trajectory.reward for trajectory in group) / len(group)
advantages = [float(trajectory.reward - mean_reward) for trajectory in group]

Degenerate groups where all 8 trajectories share the same reward (|advantage| <= 1e-12) are logged and skipped during backward.

4. Observation token masking and PPO update ​

build_trajectory_datum() packs each full multi-turn trajectory into one autoregressively shifted Datum, zeroing old_logprob and advantage for all system, user, and tool-observation tokens so only assistant completion tokens receive policy gradients:

python
full_tokens.extend(delta_environment)
old_logprobs_by_token.extend([0.0] * len(delta_environment))
advantages_by_token.extend([0.0] * len(delta_environment))

full_tokens.extend(step.completion_tokens)
old_logprobs_by_token.extend(step.logprobs)
advantages_by_token.extend(
    [trajectory.advantage] * len(step.completion_tokens)
)

main() submits all non-zero-advantage Datums for a single PPO update per rollout batch:

python
training_client.forward_backward(
    [item.datum for item in datums],
    loss_fn="ppo",
    loss_fn_config={
        "clip_low_threshold": args.ppo_clip_low,   # 0.8
        "clip_high_threshold": args.ppo_clip_high, # 1.2
    },
).result()
training_client.optim_step(adam_params).result()

Run training ​

Launch the 80-step training run from experiments/alfworld/ (saving *-state and *-weights every 20 updates):

bash
uv run --extra alfworld python train.py \
    --base-model Qwen/Qwen3.5-4B \
    --max-steps 80 \
    --games-per-batch 8 \
    --group-size 8 \
    --max-episode-steps 50 \
    --max-trajectory-tokens 12000 \
    --max-assistant-tokens 2048 \
    --temperature 1.0 \
    --learning-rate 1e-6 \
    --save-every 20 \
    --swanlab-mode online

For a quick pipeline check, lower --max-steps 10, --games-per-batch 4, and --swanlab-mode disabled.

SwanLab curves from the 80-step reference run (full logs on SwanLab). Because batch task difficulty varies across updates, online reward fluctuates and real progress should be judged on fixed validation splits:

Reward and success-rate curves across the 80-step ALFWorld training run

Trainer metrics across the 80-step ALFWorld training run

Evaluation ​

Evaluate the base model and checkpoints on all 274 fixed validation games (valid_seen 140 + valid_unseen 134, temperature=0.01, seed=42, max 50 steps):

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

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

Full messages, actions, observations, and a final summary record are written to JSONL. Generate the checkpoint chart from the repository root:

bash
cd ../..
uv run python experiments/alfworld/analysis.py

Reference evaluation results across the 274 games:

Success rates and mean invalid actions for Base, Checkpoint 40, and Checkpoint 80 on 274 ALFWorld games

ModelValid Seen (140)Valid Unseen (134)Overall (274)SolvedMean RewardMean Invalid Actions
Base52.86%52.99%52.92%145 / 274-0.01175.41
Checkpoint 4057.14%52.24%54.74%150 / 2740.02375.24
Checkpoint 8055.00%58.96%56.93%156 / 2740.08804.81
  • Overall success rate improved from 52.92% to 56.93% (+4.01 pp, +11 solved games), driven primarily by Valid Unseen generalization (52.99% → 58.96%, +5.97 pp);
  • Mean invalid actions dropped from 5.41 to 4.81, reflecting fewer formatting and admissibility errors;
  • Gains vary across task types: on valid_unseen, Heat then place (+26.1 pp) and Clean then place (+9.7 pp) rose sharply, while Pick two & place dropped 11.8 pp.

Per-task success rates across the six ALFWorld task types on Valid Seen and Valid Unseen

Metrics to monitor ​

MetricWhat it checks
reward/success_rateOnline episode completion rate (plus per-task breakdowns)
reward/meanMean episode reward after invalid-action penalties
rollout/steps_meanAverage environment interactions per episode
rollout/truncated_rateFraction of trajectories truncated at the 12K-token cap
rollout/valid_tool_call_rateFraction of turns matching the alfworld_step tool schema
rollout/admissible_action_rateFraction of actions accepted by TextWorld
rollout/invalid_actions_meanMean invalid actions per episode
advantage/degenerate_group_rateFraction of game groups with identical rewards (zero gradient)
train/loss_tokensAssistant tokens contributing to PPO gradients
train/max_sequence_tokensLongest training sequence in the batch (proximity to 12K cap)

Reproduction boundaries ​

  • Not a paper-algorithm reproduction: reuses ALFWorld's text-only environment with GRPO-style PPO rather than DAgger or the embodied BUTLER system.
  • Prefilling-dominated cost: replaying long full-history trajectories accounts for most token consumption; estimate token budgets on a small run before scaling up.
  • Single run and single eval seed: results reflect one 80-step run and one evaluation seed, with non-monotonic behavior across splits (e.g., Checkpoint 40 peaks on valid_seen).

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