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

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).

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:
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
The setup covers all six solvable ALFWorld task families (train: 3,553 games, valid_seen: 140 games, valid_unseen: 134 games):
| Task type | Goal |
|---|---|
pick_and_place_simple | Pick up an object and place it in a target receptacle |
look_at_obj_in_light | Pick up an object and examine it under a light |
pick_clean_then_place_in_recep | Clean an object and place it in a target receptacle |
pick_heat_then_place_in_recep | Heat an object and place it in a target receptacle |
pick_cool_then_place_in_recep | Cool an object and place it in a target receptacle |
pick_two_obj_and_place | Find 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-4BLoRA weights online with PPO. Environment and tool observations remain in context but do not enter the loss.

Configuration
| Item | Configuration |
|---|---|
| Base model | Qwen/Qwen3.5-4B |
| Training method | PyTRIO LoRA, rank 32 |
| Environment & splits | ALFWorld text-only (train 3,553 / valid_seen 140 / valid_unseen 134) |
| Training steps | 80 updates (5,120 trajectories total) |
| Batch per update | 8 games × group 8 = 64 independent trajectories |
| Horizon & token budgets | ≤ 50 steps / trajectory · ≤ 12,000 trajectory tokens · ≤ 2,048 assistant tokens / turn |
| Rollout sampling | temperature=1.0, top_p=1.0 |
| Reward | 1[won] - 0.1 × invalid_actions (episode-level only) |
| Advantage | Same-game reward - mean(reward) (no std division) |
| Loss | ppo, clip 0.8 / 1.2 |
| Optimizer | Adam, lr 1e-6, β (0.9, 0.95), grad_clip_norm=1.0 |
| Checkpoints | Save state and sampler weights every 20 updates |
| Random seed | 42 |
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
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 sheetUse 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.
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):
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:
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:
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:
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):
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 onlineFor 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:


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):
# 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 disabledFull messages, actions, observations, and a final summary record are written to JSONL. Generate the checkpoint chart from the repository root:
cd ../..
uv run python experiments/alfworld/analysis.pyReference evaluation results across the 274 games:

| Model | Valid Seen (140) | Valid Unseen (134) | Overall (274) | Solved | Mean Reward | Mean Invalid Actions |
|---|---|---|---|---|---|---|
| Base | 52.86% | 52.99% | 52.92% | 145 / 274 | -0.0117 | 5.41 |
| Checkpoint 40 | 57.14% | 52.24% | 54.74% | 150 / 274 | 0.0237 | 5.24 |
| Checkpoint 80 | 55.00% | 58.96% | 56.93% | 156 / 274 | 0.0880 | 4.81 |
- Overall success rate improved from
52.92%to56.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.41to4.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 dropped11.8 pp.

Metrics to monitor
| Metric | What it checks |
|---|---|
reward/success_rate | Online episode completion rate (plus per-task breakdowns) |
reward/mean | Mean episode reward after invalid-action penalties |
rollout/steps_mean | Average environment interactions per episode |
rollout/truncated_rate | Fraction of trajectories truncated at the 12K-token cap |
rollout/valid_tool_call_rate | Fraction of turns matching the alfworld_step tool schema |
rollout/admissible_action_rate | Fraction of actions accepted by TextWorld |
rollout/invalid_actions_mean | Mean invalid actions per episode |
advantage/degenerate_group_rate | Fraction of game groups with identical rewards (zero gradient) |
train/loss_tokens | Assistant tokens contributing to PPO gradients |
train/max_sequence_tokens | Longest 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.
Was this documentation helpful?