Skip to content

[RL] Add Terminal-Bench 2.1 experiment via Verifiers (Qwen3.5 9B, 35B-A3B) - #4942

Merged
wwwjn merged 15 commits into
mainfrom
jianiw/tb-client-timeout
Oct 9, 2026
Merged

wwwjn merged 15 commits into
mainfrom
jianiw/tb-client-timeout

Conversation

@wwwjn

@wwwjn wwwjn commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Human Note:

  • This PR is using Agent-in-sandbox pattern.
  • End to end run verified using coreweave cluster.

Summary

Adds a Terminal-Bench 2.1 example: the task adapter under torchtitan/rl/examples/verifiers/terminal_bench, the recipes in torchtitan_recipes/rl/verifiers_terminal_bench.py, using the existing TitanRL/Verifiers bridge. Verifiers runs a Docker-isolated Terminus-2 agent and the Harbor verifier; TitanRL handles rollout grouping, generation, and training. TitanRL's core is unchanged.

This PR contains the whole experiment: the implementation from #4888 (commit b758984eb, unchanged), four fixes for rollouts that report reward=0.000 without the model having failed, and training recipes for Qwen3.5-9B and Qwen3.5-35B-A3B.

  • Training and validation tasks are Harbor datasets selected by id (org/name@ref), fetched and cached by the harbor CLI the way Verifiers does it; the recipe refuses to run if the two are the same dataset. The task-specific XML harness stays inside this experiment.
  • Two model sizes share the datasets, sampling, loop and optimizer settings. Each recipe is one self-contained config in torchtitan_recipes/rl/verifiers_terminal_bench.py. Both train on local/tmax@v1 (AI2 TMax, converted by prepare_tmax.py into ~/.cache/harbor/local_tmax_v1) and validate on terminal-bench/terminal-bench-2-1.
  • Validation over the 89 Terminal-Bench 2.1 tasks runs at the start and end of training, so there is no separate eval-only config.
  • Setup, fidelity limits and open dependencies are documented in the experiment README.

100-step run (Qwen3.5-9B-Base, TMax-15K, stock Verifiers Terminus-2, lr 1e-6)

step 0 (base) step 100
held-out reward (507 unseen tasks x 8 rollouts) 0.334 0.417
held-out pass@8 0.586 0.655
training reward (mean over steps 1-50 → 51-100) 0.344 0.393
  • On held-out tasks, reward goes up by +0.083 +- 0.008 (11 SE) after 100 steps. The step-100 policy is better on 217 tasks and worse on 46.
  • Most of the gain is the policy finishing tasks within the 30-turn cap more often, with the same accuracy when it finishes.

The held-out reward is the clearest evidence that training works: the per-step training curve is noisy because each step trains on 16 new tasks.

Here are the internal wandb links in case the summary stays internal; I left them out above in case it's the public PR:

Note the above run is slightly different some verifiers stock verison. The above run used agent-outside-sandbox due to network fireware restriction. We also verified the code runs for agent-in-sandbox (the PR version as-is): https://meta-fair.wandb.io/jianiw/sandoq-terminal-bench-agent-in-sandbox/workspace?nw=nwuserjianiw

Known gaps / follow-ups

  • Daytona is not supported by Verifiers 0.3.1. This experiment uses Docker.
  • Datasets are fetched by Harbor id into ~/.cache/harbor. A cluster without access to the Harbor Hub can pre-populate that cache; loading from an arbitrary local path is not supported here.
  • The published TB2.1 images do not all ship tmux; Harbor's Terminus-2 session installs it at run time, so the task container needs network then, as scoring already does.
  • Mainline TitanRL uses GRPO rather than the colleague run's DPPO trust-region loss, uses independent generator replicas rather than one eight-way DP generator, and does not offer the same per-group KV-cache salting or dedicated asynchronous periodic validation.
  • Evaluation is greedy pass@1, not the colleague's pass@5. Comparable results need pinned task/image revisions and a live GPU run against the same checkpoint.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 29, 2026
@wwwjn wwwjn changed the title [rl] Terminal-Bench: four silent paths to reward=0.000 [RL] Add Terminal-Bench 2.1 experiment via Verifiers (Qwen3.5 9B, 27B, 35B-A3B) Sep 29, 2026
@wwwjn wwwjn changed the title [RL] Add Terminal-Bench 2.1 experiment via Verifiers (Qwen3.5 9B, 27B, 35B-A3B) [WIP][RL] Add Terminal-Bench 2.1 experiment via Verifiers (Qwen3.5 9B, 27B, 35B-A3B) Sep 29, 2026
@wwwjn wwwjn changed the title [WIP][RL] Add Terminal-Bench 2.1 experiment via Verifiers (Qwen3.5 9B, 27B, 35B-A3B) [RL] Add Terminal-Bench 2.1 experiment via Verifiers (Qwen3.5 9B, 35B-A3B) Sep 29, 2026
@wwwjn
wwwjn marked this pull request as ready for review September 30, 2026 05:05
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 30, 2026

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

asynchronous periodic validation

We should have this, as we couldn't only rely on a single eval at the end of the job? It's a separate task.

Daytona is not supported by Verifiers 0.3.1. This experiment uses Docker.

We should add a clear note that this is showcasing a toy example with Docker, and for real training one should plug in a mature sandbox.

The 35B-A3B generator runs without CUDA graphs: the standard MoE token dispatcher copies the all-to-all split sizes to the host (token_dispatcher.py), and capture fails on that copy. Re-enable it together with a dispatcher that avoids the host read, such as HybridEP with non_blocking_capacity_factor.

I didn't understand why we are running without CUDA graphs -- in particular the default all-to-all shouldn't be used in any "real" config. Also, we are going to support DistMoE soon, and I think every RL config should be using that. For DistMoE I don't mind us iterate later, but I would like to get a rationale of not using HybridEP / DeepEP + not applying full cudagraph on trainer / generator in the first place. To me that is a merge blocker.

16 GPUs: 8 trainer (FSDP=8) and 8 one-GPU generators.
"""
max_context_length = 65536
model_config = model_registry(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we introduced a bug by requiring enable_sp in the model_registry on qwen3_5, but it seems this PR is not based on latest main? Anyways I'm fixing it in #4908

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will rebase once it's fixed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's different about examples/verifiers/ vs. experiments/verifiers/?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

experiment is the wrong path that I put, sorry. Let me update.

16 GPUs: 8 trainer (FSDP=8) and 8 one-GPU generators.
"""
max_context_length = 65536
model_config = model_registry(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Double-check/explicitly to use distMoE backend

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

experiment is the wrong path that I put, sorry. Let me update.

@@ -424,3 +429,43 @@ def _local_taskset_module(taskset: VerifiersTasksetConfig) -> str | None:
module = type(taskset).__module__
alias = module.replace(".", "_").lower()
return module if taskset.id == alias else None


def log_failed_trace(trace: Any, *, group_id: int, rollout_id: int) -> None:

@wwwjn wwwjn Oct 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to dig into how we can better integrate with verfieris observatibility tool

By experiments, HarnessError happens often (usually because of timeout) but we need to know the reason with good observability tool

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ideally this would be saved in the rollout itself, e.g. some metadata field or terminal output. I imagine that they already capture the terminal output? It might be okay to log it, but it should stay with the rollout anyway

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Verifiers already keeps all of this on the trace: trace.errors (type, message with the tail of the harness's stderr, full traceback), per-phase timing, per-call latency and finish reason in trace.calls, and the full message graph, which includes the terminal output Terminus-2 feeds back to the model.

We drop it when converting the verfier's trace to RolloutTurns.

Plan: add the logs field the Rollout TODO asks for, have VerifiersRollouter put the trace id, stop condition, errors and timing there, and fill env_messages from the trace so the terminal output is recorded. RolloutSampleRecorder then writes it with the rollout, and gets an option to always keep failed rollouts. Since this touches the shared Rollout type and recorder, I'd do it in a follow-up PR and keep the log line here for now, what do you thing?

@wwwjn
wwwjn force-pushed the jianiw/tb-client-timeout branch from 73f9a76 to 7d35564 Compare October 2, 2026 19:29
)


def rl_grpo_qwen35_35b_a3b_terminal_bench() -> Controller.Config:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

todo: migrate to DistMoE later

@wwwjn
wwwjn force-pushed the jianiw/tb-client-timeout branch from 77a4dbb to 91ff67f Compare October 5, 2026 16:16

@felipemello1 felipemello1 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this. My comments are mostly nits. If i had to summarize:
a) I think that some portions are too verbose;
b) readme is missing a good diagram/mental model of whats going on

Other than that, it seems ok, but i would only be able to approve after seeing the wandb/console logs. I didnt check if you shared them.

No need to answer all of my comments. My recommendation is to launch 3 subagents, have each propose changes based on my comments, then have a final doc with the final recommended changes with the my enumerated comment quoted + before/after for you to eval.

Comment on lines +34 to +36
# - model_info: litellm does not know the served model name, so the context
# and per-turn output budgets come from the recipe's generator settings.
_PROGRAM_MARKER = " record_terminal_session=False,\n"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is litellm?

connection_timeout_sec: float = 1800.0


def terminal_bench_rollouter_config(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

noob question: should we have this builder, or just put it in the class above directly?
I am not sure what the builder gets us, other than indirection

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah this I think we can remove and bake it directly to the config_registry .py that is now our recipes.

@@ -424,3 +429,43 @@ def _local_taskset_module(taskset: VerifiersTasksetConfig) -> str | None:
module = type(taskset).__module__
alias = module.replace(".", "_").lower()
return module if taskset.id == alias else None


def log_failed_trace(trace: Any, *, group_id: int, rollout_id: int) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ideally this would be saved in the rollout itself, e.g. some metadata field or terminal output. I imagine that they already capture the terminal output? It might be okay to log it, but it should stay with the rollout anyway

Comment on lines +173 to +177
Generator CUDA graphs are off. The standard MoE token dispatcher copies the
all-to-all split sizes to the host, which CUDA graph capture does not allow
("Cannot copy between CPU and CUDA tensors during CUDA graph capture"). Turn
capture back on together with a dispatcher that avoids the host read, such as
HybridEP with ``non_blocking_capacity_factor``.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are we not using cudagraph because of distmoe?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are not using cudagraph because of lacking of distmoe


# TODO: Enable CUDA graphs for RL trainers after eager/graph numerics parity is
# verified.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is such a long file. It would be nice if we did something like:

all = [
"config_name_1",
...
"config_name_n,
]

if you dont mind asking the agent to do it for all configs..

Comment on lines +20 to +56
+------------------------- GPU actors (Monarch) -------------------------+
| router -> vLLM generators <-- new weights -- trainer (GRPO loss) |
+-------^-----------------------------------------------------^----------+
| 4. generate | 7. batch
+-------|-------- controller process (torchtitan.rl.train) ---|----------+
| GenerationServer dataset -> VerifiersRollouter -> batcher |
| (localhost HTTP) | ^ |
+-------^---------------------------------|------|-----------------------+
| 4. token ids 1. task | | 6. trace, reward
+-------|---------------------------------v------|-----------------------+
| Verifiers env server (spawned process) |
| per rollout: interception server (chat messages <-> token ids) |
| and a Docker runtime |
+-------^---------------------------------|------------------------------+
| 3. chat request 2. Terminus-2 |
| each turn 5. test.sh v
+-------|---------- Docker container, one per rollout -------------------+
| Terminus-2 agent <--> tmux shell |
| tests/test.sh -> reward file |
+------------------------------------------------------------------------+
```

1. **Task.** `VerifiersRollouter` sends the sampled task to the env server once per
rollout in the group.
2. **Agent.** The env server starts a container from the task's `docker_image` and runs
Verifiers' built-in Terminus-2 harness in it. The agent types commands into a tmux
shell and reads the screen back.
3. **Model call.** Each agent turn is a chat request to Verifiers' interception server,
which records the turn in the rollout's trace.
4. **Generation.** The request reaches TitanRL's `GenerationServer` as token ids and is
served by the vLLM generators.
5. **Grading.** When the agent stops, Verifiers runs the task's `tests/test.sh` in the
container and reads the reward file it writes.
6. **Trace.** `VerifiersRollouter` turns the trace into rollout turns, with the exact
tokens the generators sampled, and computes group advantages.
7. **Training.** The batcher feeds the trainer, and the generators load the new weights
after each step.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is beautiful, ty! I am just a bit confused about which number represents tool call.

Comment on lines +61 to +67
| What | Where |
| --- | --- |
| Recipes: model, parallelism, generator, training loop, and the Verifiers setup (datasets, harness, Docker runtime, timeouts) | `torchtitan_recipes/rl/verifiers_terminal_bench.py` |
| Harbor taskset, declared here so the env-server worker imports it | [`taskset.py`](./taskset.py) |
| Offline TMax to Harbor task conversion | [`prepare_tmax.py`](./prepare_tmax.py) |
| Bridge: task dataset, env server, generation server, trace to turns | [Verifiers integration](../README.md) |
| CPU tests | `tests/rl/unit_tests/cpu/test_verifiers_terminal_bench*.py` |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

very nice, ty!

@felipemello1 felipemello1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I love it, thanks! Lets get one run with good rewards and update the readme with the image. I am happy to approve after that.

awesome work!

wwwjn added 4 commits October 8, 2026 16:57
Train a Qwen3.5 terminal agent (9B or 35B-A3B) on AI2's TMax tasks and
validate on the 89 Terminal-Bench 2.1 tasks, through the Verifiers bridge.

Layout follows torchtitan_recipes:
- torchtitan/rl/examples/verifiers/terminal_bench/: task adapter (Harbor
  taskset, Terminus-2 harness, rollouter) and the offline TMax converter.
- torchtitan_recipes/rl/verifiers_terminal_bench.py: the two real-model
  recipes (rl_grpo_qwen35_9b_terminal_bench, rl_grpo_qwen35_35b_a3b_terminal_bench).
- tests/rl/unit_tests/cpu/test_verifiers_terminal_bench*.py: CPU tests.

Recipes train on local/tmax@v1 (written by prepare_tmax.py to
~/.cache/harbor/local_tmax_v1) and validate on terminal-bench/terminal-bench-2-1.
The Verifiers rollouter logs the cause, phase timing and model-call latency of
failed rollouts.
Move the alphabet-sort debug-model recipes (gpt_oss_debug_*, qwen3_moe_debug_*,
qwen3_5_debug_*, qwen3_0_6b_varlen_checkpoint_test) and the CI wrappers from
torchtitan_recipes/tests/rl.py into torchtitan_recipes/tests/rl/alphabet_sort.py.
torchtitan_recipes/rl/alphabet_sort.py now holds only verified real-model
recipes.
The Terminus-2 harness hardcoded model_info (63488 input / 16384 output
tokens) and the rollouter hardcoded GenerationServer.max_rollout_tokens=65536,
both duplicating the recipe's max_context_length and sampling max_tokens.
Changing either recipe value would silently desync the agent's context budget
and the generation server from the generator.

terminal_bench_rollouter_config now takes max_context_length and max_tokens;
the recipes pass the same values they give the trainer and generator sampler.
The harness config carries them as required max_input_tokens /
max_output_tokens fields and renders model_info from them. Also document why
each patched Terminus-2 option differs from the upstream default.
Rewrite the Terminal-Bench README around a diagram of one rollout and a file
map, mark local Docker as a toy sandbox, and drop recipe details and gaps that
are not specific to Terminal-Bench.

Correct comments that did not match the code:
- connection_timeout_sec bounds the env-server startup health wait, not model
  calls.
- Summarization is context compaction; it stays off because its three summary
  calls would be trained under the task reward, not because of token mismatch.
- With all-zero rewards the batcher raises after 10 untrainable batches; the
  run does not hang.
- Verifiers' Docker runtime uses host networking by default.

Add TODOs for removing the Terminus-2 program patch and for storing rollout
failure details on the Rollout.
wwwjn added 10 commits October 8, 2026 16:57
max_turns is now an argument of terminal_bench_rollouter_config, forwarded to
both the Terminus-2 program and Verifiers' AgentConfig, instead of a
NUM_AGENT_TURNS constant in harness.py. Rename the program test after what it
checks.
Apply ufmt to four files. Skip the Harbor taskset round-trip test when the
harbor package is not installed; the RL CPU CI installs only the DAPO-math
requirements.
Drop harness.py, which patched four arguments into Verifiers' Terminus-2
program: parser_name="xml", enable_summarize=False, max_turns=120 and
model_info. A 100-step Qwen3.5-9B-Base ablation on TMax-15K showed the stock
harness is not worse (paired reward on the same 1600 tasks: patched - stock =
-0.010 +- 0.004), and the stock run improves on 512 held-out tasks from 0.334
to 0.417 (+0.083 +- 0.008).

The rollouter now uses Terminus2HarnessConfig(id="terminus_2") directly, so
the harness alias registration and the agent token budget (max_tokens) go
away. The recipe's max_turns=120 now only sets AgentConfig.max_turns.
- Context 65536 -> 131072. Terminus-2 turns on TMax average about 1.1K tokens
  (completion plus terminal output), so max_turns=120 needs about 128K; at
  65536 a long rollout hits the context limit around turn 60.
- target_offpolicy_steps 4 -> 3, and 12 prompts per step instead of 8
  (384 rollouts per step). Generator time is about a third of a rollout's
  wall time; the rest is the sandbox. A one-GPU generator serving 128
  rollouts runs about 40 concurrent requests at 13 ms per token, and inter-token
  latency only climbs past about 60, so the 8 one-GPU generators take the
  larger batch. Step time is set by the slowest rollout in each group, so the
  extra rollouts cost little wall time.
- The env server ran at most 16 rollouts (4 workers x 4) while the controller
  keeps (target_offpolicy_steps + 1) x prompts x samples in flight (1536 for
  the 9B recipe). terminal_bench_rollouter_config now takes
  max_concurrent_rollouts and both recipes pass that in-flight count, spread
  over 16 workers.
Address review: terminal_bench_rollouter_config only added indirection.
Move it into torchtitan_recipes/rl/verifiers_terminal_bench.py as the
private _terminal_bench_rollouter_config, following
_verifiers_math_rollouter_config in verifiers_dapo_math.py.

Drop TerminalBenchRollouter: it only raised the connection_timeout_sec
default to 1800 s, which the recipe now sets on VerifiersRollouter.Config
directly. With nothing left, terminal_bench/rollouter.py is removed.

Both recipes build the same rollouter config as before apart from the
config class.
…ollout

Address review: a failed rollout's reason went only to a log line, so the
recorded rollout could not say why it failed.

- `Rollout.logs`: a rollouter-specific debug record, written by
  `RolloutSampleRecorder` and not used for training.
- `VerifiersRollouter` stores a summary of the Verifiers trace there for every
  rollout: trace id, stop condition, episode and trace errors with tracebacks
  (a failed harness's message ends with its stderr), per-phase wall time and
  model-call stats. The failure log line is built from the same record.
- Non-sampled trace nodes after a sampled one (e.g. the terminal output
  Terminus-2 sends back) become that turn's `env_messages`, so the recorded
  turns show what the environment returned.
- `KeepExtremeRewardsFilter.keep_errors` also records every errored rollout,
  not only the reward extremes of its group. The Terminal-Bench recipes turn it
  on; the default is unchanged.
Restore harness.py, now inserting only interleaved_thinking=True into
Verifiers' Terminus-2 program. Harbor's Terminus-2 defaults to
interleaved_thinking=False and drops each turn's reasoning_content from the
chat history it sends back. Verifiers matches that history against the turns
it sampled, reasoning included, so with the recipes' thinking renderers every
turn after the first started a new branch of the trace, and each branch became
its own full-context training sample. With the flag, a rollout stays one
growing context, which thinking_retention="all" assumes.

Verifiers 0.3.1's Terminus-2 config has no field for agent arguments, so the
harness patches the program as before, and fails loudly if the program
changes. The XML parser, summarization and turn-limit options removed in
"[rl] Use Verifiers' stock Terminus-2 harness" stay removed.

Test plan: CPU tests for the recipe, including the fresh-interpreter worker
check. Ran the served program against a stub OpenAI server: request 2 sent
back turn 1's reasoning_content, and request 3 sent turns 1 and 2.
…imit

Verifiers' Terminus-2 config exposes only the Harbor version, so harness.py
patched a single argument, interleaved_thinking=True, into its program.
TerminalBenchTerminusHarnessConfig now carries Terminus-2 arguments as
fields with the same names and inserts them: parser_name, enable_summarize,
max_turns, model_info (a TerminusModelInfo with max_input_tokens and
max_output_tokens), and interleaved_thinking. Defaults match Harbor's,
except interleaved_thinking, which stays True.

Passing model_info fixes summarization. Terminus-2 summarizes once fewer
than 8000 tokens of the context limit remain, and it reads that limit from
LiteLLM's model table. LiteLLM does not know the served model name and
returned its 1,000,000-token fallback, so proactive summarization could
never fire before the generation server capped the rollout. Terminus-2
registers model_info with LiteLLM under the served name, and the recipes
pass the generator's max_context_length and sampling max_tokens, so
Terminus-2 sees 131072/16384 (9B) and 65536/16384 (35B-A3B). Summarization
stays enabled (Harbor's default), so long rollouts now summarize near the
cap; each summary is three extra policy calls trained under the task reward.

The XML parser, enable_summarize=False and Terminus-2 turn limit from the
earlier ablation stay off by default; they are now config fields.

Test plan: CPU tests for the recipe. The program test parses the rendered
program and checks the Terminus2(...) keywords, and the worker test checks
that the config survives the env-server JSON round trip. Constructed Harbor
0.22.0's Terminus2 from the 9B recipe's rendered program:
get_model_context_limit() returns 131072 (was 1000000) and
get_model_output_limit() returns 16384 (was None).
…erifiers' program

harness.py inserted Terminus-2 arguments into Verifiers 0.3.1's program
source after a fixed line of its Terminus2(...) call, which breaks silently
on any formatting change upstream. Verifiers 0.3.1 has no other way in: its
Terminus-2 config exposes only the Harbor version, and the program takes a
fixed set of CLI arguments.

Copy the harness and its program from Verifiers 0.3.1 instead:
- terminus_harness.py is Verifiers' program.py plus the --enable-summarize
  and --no-interleaved-thinking flags of PrimeIntellect-ai/verifiers#2458,
  which builds Terminus2(...) from them. It runs in the sandbox as a uv
  script; the Harbor version in its header is the only substitution.
- TerminalBenchTerminusHarness subclasses Verifiers' Harness directly. Its
  config has version, interleaved_thinking=True and enable_summarize=False,
  #2458's names and defaults, and launch() turns them into flags.

Drop parser_name, Terminus-2's max_turns and model_info (TerminusModelInfo,
and max_output_tokens in _terminal_bench_rollouter_config). The first two
were Harbor's defaults. Without model_info, Terminus-2 assumes a 1M-token
context, so it cannot summarize, which matches the 9B runs, and
enable_summarize defaults to False anyway. Verifiers ends a rollout at the
context limit, so turning summarization on also needs the context limit.

Both files link the Verifiers sources and carry a TODO to delete them and
use Verifiers' Terminus2HarnessConfig once a release includes #2458.

Test plan: CPU tests for the recipe, the TMax converter and the Verifiers
bridge, on Verifiers 0.3.1 and Harbor 0.22.0 (26 passed). The new harness
test launches the harness against a recording runtime, runs the program it
prepared with Harbor's Terminus2 replaced, and checks the default and
flipped options reach the constructor. pre-commit and pyrefly pass.
@wwwjn
wwwjn force-pushed the jianiw/tb-client-timeout branch from dca9497 to f0a27e8 Compare October 9, 2026 00:00
@wwwjn

wwwjn commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

The CI failure is not related, Merge this base version with updated flexibale harness.py and continue iterating on configs

@felipemello1

Copy link
Copy Markdown
Contributor
image

@wwwjn
wwwjn merged commit 41d0fe1 into main Oct 9, 2026
wwwjn added a commit that referenced this pull request Oct 12, 2026
#5182)

## Problem

vLLM validates a request's prompt and sampling params only when the
generator's engine loop admits it (`render_cmpl` / `add_request` in
`VLLMGenerator._engine_loop`). An error there escapes the loop:
- every outstanding request on that generator fails;
- the generator closes for good, and every later call to it fails with
"generator is closed";
- the inter-generator router keeps routing to it: a closed generator
fails fast, so it looks least loaded;
- nothing tells the controller. The rollouter turns each failed call
into an ERROR rollout, so the run silently loses that generator.

One bad request is enough. In a multi-turn agentic RL run
(Terminal-Bench with Terminus-2, 131,072-token context), four prompts of
131,149 to 133,854 tokens closed four of 28 generators within 30
minutes. After that most rollouts failed and no batch was trainable. An
earlier run lost a generator to a prompt of exactly 131,072 tokens.

The prompts were not dataset prompts. Each turn's prompt is the whole
conversation so far, so it grows over a long rollout. The env side is
meant to end such a rollout:
- **`TokenEnv`** checks `len(next_prompt) >= max_rollout_tokens` before
every generation, but `max_rollout_tokens` defaults to `None`, which
disables the check.
- **Verifiers** checks each prompt against the `max_model_len` that
`GenerationServer` advertises on `GET /v1/models`. But it looks the
limit up once per worker process and caches "no limit" if the lookup
fails, and it uses `>`, so a prompt of exactly `max_model_len` passes.
- **prime-rl** uses the same Verifiers client, but vLLM's API server
validates each request and returns a 400 for that request only. Our
generator runs `LLMEngine` inside a shared engine loop, so the same
request crashed it instead.

## Fix

**1. A request vLLM rejects fails alone
(`VLLMGenerator._engine_loop`).**
- The loop renders and admits each request on its own
(`render_cmpl([prompt])`, then `add_request`) and catches `ValueError`.
- `ValueError` (including `VLLMValidationError`) is what vLLM raises for
every admission check, all before it changes engine state:
  - prompt longer than `max_model_len`;
- empty prompt, or one of exactly `max_model_len` (no room for an output
token);
  - invalid sampling params, e.g. `max_tokens=0`;
  - out-of-vocab token ids.
- Only that request's reply fails, with vLLM's own error. The loop keeps
running.
- No vLLM rules are copied. The pre-check in `generate()` from the
earlier commits is removed.
- TP ranks stay in step: the checks are deterministic, so every TP rank
of a replica rejects the same requests and none of them adds it.

**2. Rejections on any DP replica reach rank 0 (`RequestDispatcher`).**
- Rank 0 holds every reply future, but with DP > 1 a request can be
admitted, and rejected, on another replica.
- Rank 0's own replica fails those replies directly.
- Another replica's TP rank 0 sends a `_RejectedRequests` message to
rank 0 over the existing result port. Rank 0's drain task fails those
replies and frees their DP-router reservations.
- Without this, a request rejected on a peer replica would never be
answered, and its `generate()` call would hang.

**3. A dead engine loop fails the run (`wait_engine_loop` →
`wait_engine_loops` → `Controller.run`).**
- **Generator:** `wait_engine_loop()` awaits the engine loop's future,
`await asyncio.wrap_future(self._engine_loop_future)`. That adds a
done-callback and suspends only this call. The engine loop keeps running
on its own engine thread and event loop, untouched. The actor's event
loop keeps serving `generate`, `pull_model_state_dict` and `close`.
  - It returns when the loop ends cleanly (on `close()`).
  - It raises the loop's exception if the loop crashed.
- **Actor endpoint:** a `@concurrent_endpoint`, like `generate`, so
Monarch runs it alongside other calls. That decorator is what makes this
safe: a plain `@endpoint` handles one call at a time, so a call that
never returns would block every later call to that actor.
- **Router:** `wait_engine_loops` is also a `concurrent_endpoint`. It
calls `wait_engine_loop` on every rank of every generator and suspends
in `_fanout`; routing `generate` calls continues.
- **Controller:** it's one more task among the background tasks `run()`
already waits on with `asyncio.wait`.
- Engine loops only end at close, so if this task finishes mid-run,
`run()` raises.
- If it raised, `run()` re-raises the engine loop's error; if it
returned, `run()` raises "exited unexpectedly".
  - Before this, a crash surfaced only as failed rollouts.
- **Cost:** one pending RPC per generator rank and a callback. No
polling, no GPU work.

**4. Clean errors for HTTP clients (`GenerationServer`).**
- Rejects a prompt of `max_rollout_tokens` tokens or more with HTTP 400.
That's the same bound as `TokenEnv.Config.max_rollout_tokens`: the
prompt plus at least one output token must fit.
- The message uses the OpenAI-style "maximum context length" wording,
which Verifiers maps to an overlong prompt, so the rollout ends cleanly
as `context_length`.
- Without it, the generator's `ValueError` would come back through the
router as a wrapped actor error and an HTTP 500, which harnesses retry.

**5. A first prompt that doesn't fit is flagged
(`VerifiersRollouter`).**
- A rollout that stops for context length before its first turn has a
first prompt that never fit, which is a data problem, not the policy's.
- It already ends as ERROR (no turns). It now also logs a warning naming
the task.
- The dataset can't be filtered for this up front: the harness builds
the first prompt inside the env server from the task plus its own system
prompt and tools.

## Notes

- **prompt + `max_tokens` > `max_model_len`:** vLLM's `LLMEngine` path
admits such a request with `max_tokens` unchanged and stops it at
`max_model_len` with `finish_reason="length"` (`check_stop`). That isn't
an error, so nothing here changes it. vLLM's OpenAI server rejects it
instead, because it renders with `max_output_tokens=max_tokens`.
- **Cost of per-request rendering:** `render_cmpl` tokenizes nothing for
token prompts, so the extra calls are cheap. `_build_sampling_params`
still runs once per request, as before.

## Not in this PR (follow-ups)

- **Fail the run vs stop routing:** a dead engine loop now fails the
run. Keeping the run going on the remaining generators would be a router
change (mark the generator unroutable); it trades a loud failure for
silently reduced capacity.
- **Terminal-Bench recipe (#4942):** should set Verifiers'
`AgentConfig.max_total_tokens`, so rollouts stop by context size on the
env side, as `TokenEnv` does.
- **`renderers` (upstream):** should retry a failed `/v1/models` lookup
instead of caching "no limit".
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants