Compare commits

...
Author SHA1 Message Date
03f12efbaf feat!: drop v0 env compat (#3226)
* feat!: drop v0 env compat from the orchestrator and configs

The verifiers legacy bridge is removed upstream, so every v0 code path
goes:

- configs: drop the [legacy] block, is_legacy, the legacy/env conflict
  validators, and resolve_legacy_env_kwargs from EnvConfig and
  EnvServerConfig; env-server TOMLs no longer carry a legacy section
- env-server entrypoint: always serve a taskset (no bridge fork)
- orchestrator: Env always loads its taskset client-side (info()/
  run_group()/task_idx addressing removed); requires_group_scoring and
  its consumers (variable permit costs, group-scored partial drops,
  run_group fan-out) are gone — one permit is one episode everywhere
- TrainSource rows always carry the task; the pending-draw head-of-line
  hold and per-env permit costs are gone (next_example takes no args)
- GroupState.task is required; task_idx derives from task.data.idx
- env taskset ids drop the -v1 suffix across configs, examples, docs,
  skills, and the workspace members (companion renames in verifiers and
  research-environments)
- port the qwen3-vl features-payload test from the v0 RendererClient to
  renderers.client.generate (the path the v1 train client drives)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers + research-environments to the rename branches and relock

deps/verifiers -> feat/legacy-package (6a8de86), deps/research-environments
-> feat/drop-v1-suffix (27ed790). Re-pin to the merged commits before landing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin to the reworked branch head

v0 code stays in place upstream; the branch now only removes the v1
legacy bridge and the -v1 suffixes (lock unchanged).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (v1 CLI simplifications)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (main merged, python floors)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (v1 drops on-demand Hub installs)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (v0 tree under verifiers.legacy, aliased)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (ID plain str, public alias names)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (ruff fixes)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (static-tooling fixes)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (gepa schema id fix)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (docs/legacy move)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (hub installs restored in v1)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: pin verifiers to the merged main commit

deps/verifiers -> main 91d4f69e6 (#2303 merged); research-environments
-> the rename branch head with the automationbench_env collision fix.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: floor verifiers at 0.3.1.dev12

The first dev release carrying the v0 deprecation (verifiers#2303);
submodule follows main.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: verifiers submodule points at main head (the #2303 merge), not its parent

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: pin submodules to the merged mains and floor verifiers at 0.3.1.dev13

deps/verifiers -> f24b8ec0 (#2311), deps/research-environments ->
c0a0d1d7a (#754); 0.3.1.dev13 is the release cut from that verifiers
commit.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers to main d53ab56f (0.3.1.dev14)

Picks up the model-catalog revert (verifiers#2314).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-10 21:54:01 -07:00
79 changed files with 634 additions and 820 deletions
+1 -1
View File
@@ -36,7 +36,7 @@ max_completion_tokens = 768
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
id = "alphabet-sort"
min_turns = 3
max_turns = 5
+1 -1
View File
@@ -23,7 +23,7 @@ seq_len = 8192
name = "hendrycks-math"
[orchestrator.train.source.env.taskset]
id = "math-env-v1"
id = "math-env"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
+1 -1
View File
@@ -26,7 +26,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
+1 -1
View File
@@ -44,7 +44,7 @@ max_completion_tokens = 512
name = "wiki-search"
[orchestrator.train.source.env.taskset]
id = "wiki-search-v1"
id = "wiki-search"
[orchestrator.train.source.env.agent.harness]
id = "null"
+1 -1
View File
@@ -25,7 +25,7 @@ group_size = 8
name = "wordle"
[orchestrator.train.source.env.taskset]
id = "wordle-v1"
id = "wordle"
[orchestrator.train.source.env.player.harness]
id = "null"
+1 -1
View File
@@ -26,7 +26,7 @@ max_completion_tokens = 384
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
id = "alphabet-sort"
min_turns = 2
max_turns = 2
min_names_per_turn = 1
@@ -30,7 +30,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -29,7 +29,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -29,7 +29,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -41,7 +41,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -60,7 +60,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
@@ -47,7 +47,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -66,7 +66,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
@@ -27,7 +27,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -26,7 +26,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
+1 -1
View File
@@ -22,7 +22,7 @@ group_size = 16
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
id = "alphabet-sort"
min_turns = 3
max_turns = 5
+2 -2
View File
@@ -22,7 +22,7 @@ seq_len = 8192
name = "hendrycks-math"
[orchestrator.train.source.env.taskset]
id = "math-env-v1"
id = "math-env"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
@@ -40,7 +40,7 @@ name = "aime2024"
group_size = 32
[orchestrator.eval.source.env.taskset]
id = "aime24-v1"
id = "aime24"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+1 -1
View File
@@ -22,7 +22,7 @@ group_size = 16
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
+1 -1
View File
@@ -27,7 +27,7 @@ enforce = true
name = "wiki-search"
[orchestrator.train.source.env.taskset]
id = "wiki-search-v1"
id = "wiki-search"
[orchestrator.train.source.env.agent.harness]
id = "null"
+1 -1
View File
@@ -22,7 +22,7 @@ group_size = 16
name = "wordle"
[orchestrator.train.source.env.taskset]
id = "wordle-v1"
id = "wordle"
[orchestrator.train.source.env.player.harness]
id = "null"
@@ -24,7 +24,7 @@ max_completion_tokens = 64
name = "color-codeword"
[orchestrator.train.source.env.taskset]
id = "color-codeword-v1"
id = "color-codeword"
images_per_turn = 1
[orchestrator.train.source.env.agent.harness]
+1 -1
View File
@@ -28,7 +28,7 @@ alpha = 0.1
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
id = "alphabet-sort"
min_turns = 3
max_turns = 5
+2 -2
View File
@@ -25,7 +25,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -44,7 +44,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+2 -2
View File
@@ -25,7 +25,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -44,7 +44,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+3 -3
View File
@@ -35,7 +35,7 @@ max_completion_tokens = 128
name = "reverse-text-grpo"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -47,7 +47,7 @@ type = "subprocess"
name = "reverse-text-opd"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -73,7 +73,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+2 -2
View File
@@ -37,7 +37,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -56,7 +56,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+2 -2
View File
@@ -37,7 +37,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -56,7 +56,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+2 -2
View File
@@ -25,7 +25,7 @@ max_completion_tokens = 512
name = "kuhn-poker"
[orchestrator.train.source.env.taskset]
id = "kuhn-poker-v1"
id = "kuhn-poker"
[orchestrator.train.source.env.player0.harness]
id = "null"
@@ -50,7 +50,7 @@ max_completion_tokens = 512
name = "kuhn-poker"
[orchestrator.eval.source.env.taskset]
id = "kuhn-poker-v1"
id = "kuhn-poker"
[orchestrator.eval.source.env.player0.harness]
id = "null"
+2 -2
View File
@@ -33,7 +33,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -52,7 +52,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+2 -2
View File
@@ -42,7 +42,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -61,7 +61,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+2 -2
View File
@@ -42,7 +42,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -61,7 +61,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+3 -3
View File
@@ -21,7 +21,7 @@ max_completion_tokens = 128
name = "reverse-text-a"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -33,7 +33,7 @@ type = "subprocess"
name = "reverse-text-b"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -52,7 +52,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+1 -1
+7 -7
View File
@@ -126,7 +126,7 @@ type = "grpo"
name = "math" # inherits the top-level grpo
[orchestrator.train.source.env.taskset]
id = "math-v1"
id = "math"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -138,7 +138,7 @@ type = "subprocess"
name = "terminal"
[orchestrator.train.source.env.taskset]
id = "terminal-v1"
id = "terminal"
[orchestrator.train.source.env.agent.harness]
id = "bash"
@@ -354,7 +354,7 @@ The solver attempts for A should not be compared with the solver attempts for B:
For example, if three solvers receive rewards `[1, 1, 0]` on one proposed problem, their average is `2/3` and their advantages are `[1/3, 1/3, -2/3]`. Solver rewards from other proposed problems do not affect those values. The proposers are scored separately according to how useful their problems were for the solvers, then compared with the other proposers in the group.
Configure which roles are compared within a single proposed problem with `episode_agents`. For `proposer-solver-v1`, that role is `solver`:
Configure which roles are compared within a single proposed problem with `episode_agents`. For `proposer-solver`, that role is `solver`:
```toml
[orchestrator.algo]
@@ -367,7 +367,7 @@ group_size = 4 # proposed problems per source task
env.n = 4 # solver attempts per proposed problem
[orchestrator.train.source.env.taskset]
id = "proposer-solver-v1"
id = "proposer-solver"
[orchestrator.train.source.env.proposer.harness]
id = "null"
@@ -401,7 +401,7 @@ decay = 0.95
name = "kuhn-poker"
[orchestrator.train.source.env.taskset]
id = "kuhn-poker-v1"
id = "kuhn-poker"
[orchestrator.train.source.env.player0.harness]
id = "null"
@@ -416,7 +416,7 @@ id = "null"
type = "subprocess"
```
Both of `kuhn-poker-v1`'s agents late-bind to the run's own model — shared-policy self-play against a continuously improving opponent. Pin one agent to a frozen endpoint (`env.player1.model = ...`) for asymmetric play; its traces are marked untrainable by the env and never reach the advantage computation. A single-agent env under `rae` degrades to REINFORCE with an EMA baseline.
Both of `kuhn-poker`'s agents late-bind to the run's own model — shared-policy self-play against a continuously improving opponent. Pin one agent to a frozen endpoint (`env.player1.model = ...`) for asymmetric play; its traces are marked untrainable by the env and never reach the advantage computation. A single-agent env under `rae` degrades to REINFORCE with an EMA baseline.
### Authoring an Algorithm
@@ -481,7 +481,7 @@ Filtered rollouts still appear in W&B distributions, just not in the trainer bat
## Multi-Turn Trajectories
Multi-turn rollouts (tool use, browser environments, long conversations) used to be stitched into a single fake "single-turn" sample, which silently corrupted the importance ratio when chat templates didn't roundtrip. Since [`verifiers` v0.1.8](https://github.com/PrimeIntellect-ai/verifiers/releases/tag/v0.1.8), `prime-rl` records each LLM request/response as an independent **trajectory step** and merges them at training time using best-effort interleaving — with [renderers](#renderers) as the mechanism that keeps the merge safe by construction.
For multi-turn rollouts (tool use, browser environments, long conversations), `prime-rl` records each LLM request/response as an independent **trajectory step** and merges them at training time using best-effort interleaving — with [renderers](#renderers) as the mechanism that keeps the merge safe by construction.
### Extension Property
+3 -3
View File
@@ -155,7 +155,7 @@ name = "gsm8k"
ratio = 3 # 75% of batches
[orchestrator.train.source.env.taskset]
id = "gsm8k-v1"
id = "gsm8k"
split = "train"
[orchestrator.train.source.env.agent.harness]
@@ -169,7 +169,7 @@ name = "reverse-text"
ratio = 1 # default — 25% of batches
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -181,7 +181,7 @@ type = "subprocess"
name = "gsm8k-eval"
[orchestrator.eval.source.env.taskset]
id = "gsm8k-v1"
id = "gsm8k"
split = "test"
[orchestrator.eval.source.env.agent.harness]
+1 -1
View File
@@ -90,7 +90,7 @@ The RL entrypoint supports several training algorithms, switched via `[orchestra
|---|---|---|
| `grpo` (default) | None | Standard group-relative RL |
| `max_rl` | None | [MaxRL](https://arxiv.org/abs/2602.02710): GRPO with mean-normalized advantages (maximum-likelihood RL) |
| `rae` | None | [SPIRAL](https://arxiv.org/abs/2506.24119)'s role-conditioned advantage estimation: reward minus a per-agent EMA baseline, for multi-agent self-play envs (e.g. `kuhn-poker-v1`) |
| `rae` | None | [SPIRAL](https://arxiv.org/abs/2506.24119)'s role-conditioned advantage estimation: reward minus a per-agent EMA baseline, for multi-agent self-play envs (e.g. `kuhn-poker`) |
| `hierarchical_grpo` | None | GRPO for proposer-solver envs: compare solvers only with attempts on the same proposed problem, and compare proposers with the other proposals in the group |
| `opd` | Required, must be vLLM (needs `prompt_logprobs`) | [On-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): the policy generates rollouts, the trainer minimizes per-token reverse KL to a reference model |
| `sft` | Required, any OpenAI-compatible endpoint | Hard-distill: a frozen model generates rollouts, the policy trains on its tokens |
+3 -3
View File
@@ -109,7 +109,7 @@ idle_timeout = "None"
labels = ["glm45air-search"]
[orchestrator.train.source.env.taskset]
id = "openseeker-v1"
id = "openseeker"
[[orchestrator.train.source.env.taskset.task.judges]]
id = "reference"
@@ -142,7 +142,7 @@ idle_timeout = "None"
labels = ["glm45air-search"]
[orchestrator.train.source.env.taskset]
id = "redsearcher-v1" # optional `difficulty` filter (easy/medium/hard)
id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
[[orchestrator.train.source.env.taskset.task.judges]]
id = "reference"
@@ -184,7 +184,7 @@ labels = ["glm45air-search"]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "browsecomp-v1"
id = "browsecomp"
[orchestrator.eval.source.env.taskset.task.judge]
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
+3 -3
View File
@@ -1,4 +1,4 @@
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe-v1` SWE taskset, rlm harness on a prime sandbox
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, rlm harness on a prime sandbox
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
# a glm4_moe model, which supports routed_experts.
@@ -101,7 +101,7 @@ thinking_retention = "all"
name = "scaleswe"
[orchestrator.train.source.env.taskset]
id = "scaleswe-v1"
id = "scaleswe"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
@@ -124,7 +124,7 @@ interval = 20
name = "swebench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
+3 -3
View File
@@ -105,7 +105,7 @@ idle_timeout = "None"
labels = ["glm45air-terminal"]
[orchestrator.train.source.env.taskset]
id = "tmax-v1"
id = "tmax"
# # Metric-only monitors (weight 0): rlm harness-mechanics + swe code-usage rubrics, judged by GLM-5.2.
# [[orchestrator.train.source.env.taskset.judges]]
@@ -144,7 +144,7 @@ labels = ["glm45air-terminal"]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
id = "swebench-verified"
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
@@ -178,7 +178,7 @@ labels = ["glm45air-terminal"]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "terminal-bench-2-v1"
id = "terminal-bench-2"
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
+1 -1
View File
@@ -131,7 +131,7 @@ clear_thinking = false
name = "r2e"
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
+1 -1
View File
@@ -79,7 +79,7 @@ interval = 20
name = "swe-bench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
+7 -7
View File
@@ -52,7 +52,7 @@ name = "swe"
ratio = 0.3
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "bash"
@@ -66,7 +66,7 @@ name = "deepdive"
ratio = 0.2
[orchestrator.train.source.env.taskset]
id = "deepdive-v1"
id = "deepdive"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
@@ -82,7 +82,7 @@ name = "math"
ratio = 0.3
[orchestrator.train.source.env.taskset]
id = "i3_math_v1"
id = "i3_math"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -95,7 +95,7 @@ name = "logic"
ratio = 0.2
[orchestrator.train.source.env.taskset]
id = "i3_logic_v1"
id = "i3_logic"
[orchestrator.train.source.env.taskset.filter]
max = 0.874
@@ -111,7 +111,7 @@ name = "code"
ratio = 0.2
[orchestrator.train.source.env.taskset]
id = "i3_code_v1"
id = "i3_code"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -130,7 +130,7 @@ interval = 25
name = "swe-bench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
@@ -143,7 +143,7 @@ labels = ["intellect-3.1", "swe-bench-verified"]
name = "aime2025"
[orchestrator.eval.source.env.taskset]
id = "aime25-v1"
id = "aime25"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+2 -2
View File
@@ -52,7 +52,7 @@ max_off_policy_steps = 16
name = "swe"
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "bash"
@@ -68,7 +68,7 @@ interval = 25
name = "swe-bench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
+2 -2
View File
@@ -85,7 +85,7 @@ truncate_history_thinking = false
name = "scaleswe"
[orchestrator.train.source.env.taskset]
id = "scaleswe-v1"
id = "scaleswe"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
@@ -106,7 +106,7 @@ interval = 20
name = "swebench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
+2 -2
View File
@@ -52,7 +52,7 @@ max_completion_tokens = 32768
name = "math"
[orchestrator.train.source.env.taskset]
id = "i3_math_v1"
id = "i3_math"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -67,7 +67,7 @@ interval = 25
name = "aime2025"
[orchestrator.eval.source.env.taskset]
id = "aime25-v1"
id = "aime25"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+2 -2
View File
@@ -50,7 +50,7 @@ max_off_policy_steps = 16
name = "swe"
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "bash"
@@ -66,7 +66,7 @@ interval = 25
name = "swe-bench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
+1 -1
View File
@@ -38,7 +38,7 @@ max_off_policy_steps = 32
[[orchestrator.train.source]]
[orchestrator.train.source.env.taskset]
id = "general-agent-v1"
id = "general-agent"
min_tier = 1
[orchestrator.train.source.env.taskset.task.tools]
+4 -4
View File
@@ -1,6 +1,6 @@
# Alphabet Sort
In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to sort names alphabetically using LoRA. Unlike other examples, this task doesn't require SFT warmup as the base model already understands the conversation format. We proceed directly to multi-turn RL against the `alphabet-sort-v1` taskset.
In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to sort names alphabetically using LoRA. Unlike other examples, this task doesn't require SFT warmup as the base model already understands the conversation format. We proceed directly to multi-turn RL against the `alphabet-sort` taskset.
> This example runs on a single H100 GPU.
@@ -9,7 +9,7 @@ In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to sort na
The taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
uv run python -c "import alphabet_sort_v1"
uv run python -c "import alphabet_sort"
```
Start the tmux session:
@@ -38,7 +38,7 @@ uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507
Evaluate the base model:
```bash
# In the `Trainer` pane
uv run eval alphabet-sort-v1 --harness.id null \
uv run eval alphabet-sort --harness.id null \
-m Qwen/Qwen3-4B-Instruct-2507 \
--client.base-url http://localhost:8000/v1 \
-n 20 \
@@ -115,7 +115,7 @@ uv run inference --vllm.enable-lora --vllm.model PrimeIntellect/Qwen3-4B-Instruc
```bash
# In the `Trainer` pane
uv run eval alphabet-sort-v1 --harness.id null \
uv run eval alphabet-sort --harness.id null \
-m PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL \
--client.base-url http://localhost:8000/v1 \
-n 20 \
+1 -1
View File
@@ -35,7 +35,7 @@ max_completion_tokens = 768
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
id = "alphabet-sort"
min_turns = 3
max_turns = 5
+2 -2
View File
@@ -20,7 +20,7 @@ seq_len = 8192
name = "hendrycks-math"
[orchestrator.train.source.env.taskset]
id = "math-env-v1"
id = "math-env"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
@@ -38,7 +38,7 @@ name = "aime2024"
group_size = 32
[orchestrator.eval.source.env.taskset]
id = "aime24-v1"
id = "aime24"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+6 -6
View File
@@ -1,15 +1,15 @@
# Reverse Text
We demonstrate how to train `Qwen3-0.6B` to reverse a small chunk of text. We will use a SFT warmup to learn the skill of text reversal on longer documents and then a quick RL run on the `reverse-text-v1` taskset. We use a similar setup in our CI and for development.
We demonstrate how to train `Qwen3-0.6B` to reverse a small chunk of text. We will use a SFT warmup to learn the skill of text reversal on longer documents and then a quick RL run on the `reverse-text` taskset. We use a similar setup in our CI and for development.
> The commands in this example were designed to be run on 2 GPUs (one trainer and one inference GPU). It is possible to run on less or more GPUs using different deployment strategies. If you run on a different setup, you may need to adjust the start commands.
## Setup
The `reverse-text-v1` taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
The `reverse-text` taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
uv run python -c "import reverse_text_v1"
uv run python -c "import reverse_text"
```
First, let's start a `tmux` session which we will use throughout the experiment.
@@ -27,7 +27,7 @@ uv run inference --vllm.model Qwen/Qwen3-0.6B
```bash
# Run this in the `Trainer` pane
uv run eval reverse-text-v1 --harness.id null -m Qwen/Qwen3-0.6B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval reverse-text --harness.id null -m Qwen/Qwen3-0.6B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
This is of course just a quick vibe check and no full-fledged evaluation, but we can see that the model struggles with this task. In this specific instance, we got an **average reward of ~0.05** across the 20x3 rollouts. Let's do some training!
@@ -100,7 +100,7 @@ uv run inference --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
```bash
# Run this in the `Trainer` pane
uv run eval reverse-text-v1 --harness.id null -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval reverse-text --harness.id null -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
Way better! Now we get an **average reward of ~0.8**.
@@ -213,7 +213,7 @@ kubectl exec -it my-exp-inference-0 -- bash
uv run inference --vllm.model /data/outputs/weights/step_20
# Back in trainer pod, run evaluation
uv run eval reverse-text-v1 --harness.id null \
uv run eval reverse-text --harness.id null \
-m /data/outputs/weights/step_20 \
--client.base-url $INFERENCE_URL \
-n 20 -r 3 --sampling.max-tokens 1024 --no-push
+1 -1
View File
@@ -19,7 +19,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
+4 -4
View File
@@ -16,7 +16,7 @@ In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to answer
The taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
uv run python -c "import wiki_search_v1"
uv run python -c "import wiki_search"
```
Set up the credentials for the configured reference judge:
@@ -77,7 +77,7 @@ Evaluate the base model:
```bash
# In the `Trainer` pane
uv run eval wiki-search-v1 --harness.id null \
uv run eval wiki-search --harness.id null \
-m Qwen/Qwen3-4B-Instruct-2507 \
--client.base-url http://localhost:8000/v1 \
-n 20 \
@@ -119,7 +119,7 @@ uv run inference --vllm.enable-lora --vllm.model <user>/Qwen3-4B-Instruct-WikiSe
```bash
# In the `Trainer` pane
uv run eval wiki-search-v1 --harness.id null \
uv run eval wiki-search --harness.id null \
-m <user>/Qwen3-4B-Instruct-WikiSearch-RL \
--client.base-url http://localhost:8000/v1 \
-n 20 \
@@ -135,7 +135,7 @@ The V1 taskset fixes the question bank and searchable corpus. You can replace it
```toml
[[orchestrator.train.source]]
name = "wiki-search"
taskset = { id = "wiki-search-v1", task = { judges = [{ id = "reference", model = "openai/gpt-5.4-nano" }] } }
taskset = { id = "wiki-search", task = { judges = [{ id = "reference", model = "openai/gpt-5.4-nano" }] } }
harness = { id = "null" }
runtime = { type = "subprocess" }
```
+1 -1
View File
@@ -44,7 +44,7 @@ max_completion_tokens = 512
name = "wiki-search"
[orchestrator.train.source.env.taskset]
id = "wiki-search-v1"
id = "wiki-search"
[orchestrator.train.source.env.agent.harness]
id = "null"
+4 -4
View File
@@ -1,6 +1,6 @@
# Wordle
In this example, we demonstrate how to train `Qwen3-1.7B` to play Wordle. This will require a SFT warmup to learn the format and, finally, multi-turn RL against the `wordle-v1` taskset to improve performance.
In this example, we demonstrate how to train `Qwen3-1.7B` to play Wordle. This will require a SFT warmup to learn the format and, finally, multi-turn RL against the `wordle` taskset to improve performance.
> The commands in this example were designed to be run on 2 GPUs (one trainer and one inference GPU). It is possible to run on less or more GPUs using different deployment strategies. If you run on a different setup, you may need to adjust the start commands.
@@ -9,7 +9,7 @@ In this example, we demonstrate how to train `Qwen3-1.7B` to play Wordle. This w
The taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
uv run python -c "import wordle_v1"
uv run python -c "import wordle"
```
Start the pre-layouted `tmux` session which we will use to run all experiments and view logs conveniently
@@ -29,7 +29,7 @@ Then, use the `eval` entrypoint to evaluate the model in the `wordle` environmen
```bash
# Run this in the `Trainer` pane
uv run eval wordle-v1 --harness.id null -m Qwen/Qwen3-1.7B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval wordle --harness.id null -m Qwen/Qwen3-1.7B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
We got an **average reward of ~0.2** across the 20x3 rollouts. From the summary, we can see that the most of the reward is coming from format and partial rewards. In fact, the model does not guess the correct word within any game, leading to a win rate of **0%**. Looking at some samples, it is evident repeatedly submitting guesses in the wrong format and is not able to revise its strategy from the environment feedback. Let's do some SFT warmup to get the model to learn the format of the environment.
@@ -103,7 +103,7 @@ uv run inference --vllm.model PrimeIntellect/Qwen3-1.7B-Wordle-RL
```bash
# Run this in the `Trainer` pane
uv run eval wordle-v1 --harness.id null -m PrimeIntellect/Qwen3-1.7B-Wordle-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval wordle --harness.id null -m PrimeIntellect/Qwen3-1.7B-Wordle-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
Way better! Our model now wins **~60%** and gets an average reward of **~1.5**.
+1 -1
View File
@@ -22,7 +22,7 @@ group_size = 16
name = "wordle"
[orchestrator.train.source.env.taskset]
id = "wordle-v1"
id = "wordle"
[orchestrator.train.source.env.player.harness]
id = "null"
+1 -1
View File
@@ -17,7 +17,7 @@ max_completion_tokens = 128
name = "reverse-text"
[train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[train.source.env.agent.harness]
id = "null"
@@ -246,7 +246,7 @@ class RAEAlgoConfig(BaseAlgoConfig):
https://arxiv.org/abs/2506.24119): scalar advantage = reward minus a
per-agent EMA baseline of that agent's own rewards, consumed by the ``rl``
loss component. The advantage estimator for multi-agent self-play envs
(``kuhn-poker-v1`` and friends): in a zero-sum game the group mean is ~0
(``kuhn-poker`` and friends): in a zero-sum game the group mean is ~0
whatever the policy does, so a group-relative baseline mixes the agents'
opposite reward scales — a structural first-mover edge would read as
permanent credit. Per-agent baselines measure each agent against its own
@@ -274,16 +274,16 @@ class HierarchicalGRPOAlgoConfig(BaseAlgoConfig):
episode_agents: list[str] = Field(min_length=1)
"""Roles compared within one proposed problem. Use ``["solver"]`` for
``proposer-solver-v1``."""
``proposer-solver``."""
def validate_env(self, env_config: vf.EnvConfig) -> None:
"""Require the proposer-solver structure used by the comparisons."""
try:
from proposer_solver_v1 import ProposerSolverEnvConfig
from proposer_solver import ProposerSolverEnvConfig
except ImportError as e:
raise ValueError(
"algorithm 'hierarchical_grpo' requires a proposer-solver env, but the "
"proposer-solver-v1 package is not installed (`uv sync --all-packages`)."
"proposer-solver package is not installed (`uv sync --all-packages`)."
) from e
if not isinstance(env_config, ProposerSolverEnvConfig):
raise ValueError(
@@ -8,9 +8,9 @@ from prime_rl.utils.config import BaseConfig
class EnvServerConfig(BaseConfig):
"""``uv run env-server``: what to serve (``[env]``, or ``[legacy]`` for a classic v0
env) and how it's hosted (``[serve]``). The ``rl`` launcher writes one of these per
train/eval source, with ``serve.address`` set to the source's derived address."""
"""``uv run env-server``: what to serve (``[env]``) and how it's hosted (``[serve]``).
The ``rl`` launcher writes one of these per train/eval source, with ``serve.address``
set to the source's derived address."""
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
"""The environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
@@ -18,9 +18,6 @@ class EnvServerConfig(BaseConfig):
serve: vf.ServeConfig = vf.ServeConfig()
"""How it's served: the worker pool, the bind address, each worker's episode bound."""
legacy: vf.LegacyEnvConfig = vf.LegacyEnvConfig()
"""A classic (v0) environment to serve through the bridge instead of ``env``."""
log: LogConfig = LogConfig()
output_dir: Path = Path("outputs")
@@ -32,35 +29,12 @@ class EnvServerConfig(BaseConfig):
"""Narrow ``env`` to the selected env's config class."""
return vf.resolve_env_field(data, vf.narrowed_env_annotation(cls))
@property
def is_legacy(self) -> bool:
"""Whether this serves the v0 bridge: a legacy id and no v1 taskset."""
return self.legacy.id is not None and not self.env.taskset.id
@property
def env_id(self) -> str:
"""The served env's identifier: the v1 env's, else the v0 env id."""
return self.env.env_id or self.legacy.id or ""
return self.env.env_id or ""
@model_validator(mode="after")
def validate_env(self):
# A v0 id next to any v1 env identity leaves one of the two going nowhere, and
# which one depends on `is_legacy`: a taskset makes it False, so the v0 env never
# loads; a bare `env.id` leaves it True, so the v0 env runs under the v1 name.
if self.legacy.id is not None and self.env.env_id:
if self.env.taskset.id:
raise ValueError(
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with "
f"the v1 taskset {self.env.taskset.id!r}. Pairing a reusable env with a taskset "
f"is env.id = {self.legacy.id!r}; to run the v0 env instead, drop the taskset."
)
raise ValueError(
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with the "
f"v1 env.id {self.env.id!r}: the v0 env is what would run, stamped with the v1 "
"env's name. Keep whichever one you meant to run."
)
if not self.env_id:
raise ValueError(
'no env configured — set env = { taskset = { id = "<id>" } } (v1) or legacy = { id = "<id>" } (v0)'
)
raise ValueError('no env configured — set env = { taskset = { id = "<id>" } }')
return self
@@ -119,8 +119,7 @@ class EvalSamplingConfig(BaseConfig):
class EnvConfig(BaseConfig):
"""One environment a run pulls from: the verifiers blocks it composes (``env`` — what
runs, ``serve`` — how it's hosted, ``legacy`` — a classic v0 env instead) plus this
orchestrator's own per-env knobs."""
runs, ``serve`` — how it's hosted) plus this orchestrator's own per-env knobs."""
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
"""The verifiers environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
@@ -128,9 +127,6 @@ class EnvConfig(BaseConfig):
serve: vf.ServeConfig = vf.ServeConfig()
"""How this source's env server is hosted. The sizing knobs are consumed by the launcher, which writes each source's env-server config with an unset ``address`` filled in as the derived ``tcp://127.0.0.1:<env_server_base_port + index>``. Setting ``address`` marks the server externally managed: the launchers neither write its env-server TOML nor spawn a server for it, and the orchestrator connects to the given address — e.g. a k8s deployment running env servers in their own pods."""
legacy: vf.LegacyEnvConfig = vf.LegacyEnvConfig()
"""A classic (v0) environment to run through the bridge instead of ``env``."""
name: str | None = None
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
@@ -143,15 +139,9 @@ class EnvConfig(BaseConfig):
"""Narrow ``env`` to the selected env's config class."""
return vf.resolve_env_field(data, vf.narrowed_env_annotation(cls))
@property
def is_legacy(self) -> bool:
"""A classic (v0) env run through the bridge: a legacy id and no v1 taskset."""
return self.legacy.id is not None and not self.env.taskset.id
@property
def env_id(self) -> str:
"""The env's identifier: the v1 env's, else the v0 env id."""
return self.env.env_id or self.legacy.id or ""
return self.env.env_id or ""
@property
def resolved_name(self) -> str:
@@ -159,47 +149,14 @@ class EnvConfig(BaseConfig):
@model_validator(mode="after")
def validate_env(self):
# A v0 id next to any v1 env identity leaves one of the two going nowhere, and
# which one depends on `is_legacy`: a taskset makes it False, so the v0 env never
# loads; a bare `env.id` leaves it True, so the v0 env runs under the v1 name.
if self.legacy.id is not None and self.env.env_id:
if self.env.taskset.id:
raise ValueError(
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with "
f"the v1 taskset {self.env.taskset.id!r}. Pairing a reusable env with a taskset "
f"is env.id = {self.legacy.id!r}; to run the v0 env instead, drop the taskset."
)
raise ValueError(
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with the "
f"v1 env.id {self.env.id!r}: the v0 env is what would run, stamped with the v1 "
"env's name. Keep whichever one you meant to run."
)
if not self.env_id:
raise ValueError(
'no env configured — set env = { taskset = { id = "<id>" } } (v1) or legacy = { id = "<id>" } (v0)'
)
raise ValueError('no env configured — set env = { taskset = { id = "<id>" } }')
if self.resolved_name == "agg":
raise ValueError(
'Environment name "agg" is reserved for cross-env metric aggregation. Use a different name or id.'
)
return self
@model_validator(mode="after")
def resolve_legacy_env_kwargs(self):
"""For a v0/legacy env, surface the v1 knobs the legacy bridge applies via
``legacy.extra_env_kwargs`` (``env.set_kwargs(...)``): the per-rollout wall-clock
timeout and the multi-turn completion-token budget, read off ``env.agent``.
(``max_seq_len`` is added per train run in ``OrchestratorConfig.resolve_env_config``,
which knows ``seq_len``.)"""
if self.is_legacy:
agent = getattr(self.env, "agent", None)
if agent is not None:
if agent.timeout.rollout is not None:
self.legacy.extra_env_kwargs["timeout_seconds"] = agent.timeout.rollout
if agent.max_output_tokens is not None:
self.legacy.extra_env_kwargs["max_total_completion_tokens"] = agent.max_output_tokens
return self
class TrainSourceConfig(EnvConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
@@ -508,7 +465,7 @@ class OrchestratorConfig(BaseConfig):
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node."""
tasks_per_minute: int | None = Field(None, ge=1)
"""Rate limit per environment worker, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. With multiple workers, the effective total rate is ``workers × this value``. None disables rate limiting."""
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
env_server_base_port: int = Field(5000, ge=1, le=65535)
"""First port of the env-server port range: the source at position ``i`` (train, then eval) is served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address`` keep it instead, without shifting the other sources' ports (indices stay positional). Give concurrent runs on one host distinct bases (e.g. one per multi-run orchestrator)."""
@@ -697,7 +654,7 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def resolve_env_config(self):
"""Set vLLM sampling defaults + legacy env kwargs on each train env from top-level fields."""
"""Set vLLM sampling defaults on each train env from top-level fields."""
for env in self.train.source:
# Policy-sourced rollouts hit our vLLM server; frozen-sourced
# rollouts may hit external OAI endpoints that reject these knobs.
@@ -706,10 +663,6 @@ class OrchestratorConfig(BaseConfig):
env.sampling.extra_body.setdefault("top_k", -1)
env.sampling.extra_body.setdefault("min_p", 0.0)
env.sampling.extra_body.setdefault("return_token_ids", True)
if env.is_legacy:
# v0 env: cap per-turn response tokens to the training budget (the legacy
# bridge applies legacy.extra_env_kwargs via env.set_kwargs).
env.legacy.extra_env_kwargs["max_seq_len"] = self.seq_len
return self
@property
+15 -17
View File
@@ -33,7 +33,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.3.0",
"verifiers[harbor]>=0.3.1.dev14",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -136,20 +136,20 @@ override-dependencies = [
[tool.uv.workspace]
members = [
"deps/research-environments/environments/*/*",
"deps/verifiers/environments/alphabet_sort_v1",
"deps/verifiers/environments/color_codeword_v1",
"deps/verifiers/environments/gsm8k_v1",
"deps/verifiers/environments/kuhn_poker_v1",
"deps/verifiers/environments/proposer_solver_v1",
"deps/verifiers/environments/reverse_text_v1",
"deps/verifiers/environments/wiki_search_v1",
"deps/verifiers/environments/wordle_v1",
"deps/verifiers/environments/alphabet_sort",
"deps/verifiers/environments/color_codeword",
"deps/verifiers/environments/gsm8k",
"deps/verifiers/environments/kuhn_poker",
"deps/verifiers/environments/proposer_solver",
"deps/verifiers/environments/reverse_text",
"deps/verifiers/environments/wiki_search",
"deps/verifiers/environments/wordle",
]
# tau2-synth-v1 and tau3-bench-v1 pin `tau2` forks/revs that conflict with the
# canonical tau2-bench-v1; a workspace shares one lock, so these can't coexist.
# tau2-synth and tau3-bench pin `tau2` forks/revs that conflict with the
# canonical tau2-bench; a workspace shares one lock, so these can't coexist.
exclude = [
"deps/research-environments/environments/tool_use/tau2_synth_v1",
"deps/research-environments/environments/tool_use/tau3_bench_v1",
"deps/research-environments/environments/tool_use/tau2_synth",
"deps/research-environments/environments/tool_use/tau3_bench",
]
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
@@ -195,10 +195,8 @@ torchao = false
[tool.uv.sources]
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
# prime-rl depends on the one `verifiers` package (v0 + v1 + the legacy bridge + the built-in v1
# harnesses/tasksets, now bundled in verifiers.v1). v0 envs resolve from
# deps/{verifiers,research-environments}/environments; v1 tasksets (`-v1`) and the `compact`
# example live under deps/{verifiers,research-environments}/environments.
# prime-rl consumes `verifiers.v1` (incl. the built-in harnesses/tasksets); env tasksets
# live under deps/{verifiers,research-environments}/environments.
verifiers = { path = "deps/verifiers", editable = true }
renderers = { path = "deps/renderers", editable = true }
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
+3 -3
View File
@@ -47,7 +47,7 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -59,7 +59,7 @@ type = "subprocess"
name = "reverse-text-eval"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
split = "test"
[orchestrator.eval.source.env.agent.harness]
@@ -69,7 +69,7 @@ id = "null"
type = "subprocess"
```
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text-v1` or `--orchestrator.eval.source.0.env.taskset.id reverse-text-v1`.
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text` or `--orchestrator.eval.source.0.env.taskset.id reverse-text`.
**Dicts** — TOML uses a section; CLI takes a JSON string: `--trainer.env-vars '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
+1 -1
View File
@@ -26,7 +26,7 @@ uv sync # core only
uv sync --group dev # + pytest, ruff, pre-commit
uv sync --all-extras # + extras (flash-attn, flash-attn-cute, …)
uv sync --all-extras --all-packages # + all env packages (needed to train on them)
uv sync --package prime-rl --package gsm8k-v1 # core + just one env
uv sync --package prime-rl --package gsm8k # core + just one env
```
Environment packages are uv **workspace members**. Those under `deps/research-environments/environments/*/*` are auto-discovered — adding a new env there needs no `pyproject.toml` change. verifiers' example envs are enumerated explicitly in `[tool.uv.workspace].members` (only the ones prime-rl trains or tests on) — to use another, add its path to the list. Members are opt-in: a plain `uv sync` / `--all-extras` does not install them (and would remove them if already present — re-run with `--all-packages`, or `--inexact` to keep them). Install all with `--all-packages`, or a subset with repeated `--package <env>` (include `--package prime-rl` to keep the core). If two envs pin conflicting transitive versions (all members share one lock), add the loser to `[tool.uv.workspace].exclude`.
+1 -1
View File
@@ -35,7 +35,7 @@ uv run rl @ examples/basic/reverse-text/rl.toml --dry-run
- SLURM: single- and multi-node
- Environment packages: before launching a config with a non-core verifier env id,
verify the package imports under `uv run` (for example
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym_v1'))"`).
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym'))"`).
If a local env exists under `deps/research-environments/environments/` or
`deps/verifiers/environments/` but does not import, install the env workspace
members with `uv sync --all-packages` (all) or `uv sync --package prime-rl
+4 -11
View File
@@ -12,21 +12,14 @@ from prime_rl.utils.utils import clean_exit
@clean_exit
def run_server(config: EnvServerConfig):
# ``serve.pool`` (static or elastic) sizes the server; a v0/legacy env runs through
# the bridge, a v1 env is a native env block — both speak the same serve protocol,
# so the orchestrator is agnostic. serve_env applies the logging setup in this process
# and in every spawned worker.
server_kwargs = (
{"env_id": config.env_id, "env_args": config.legacy.args, "extra_env_kwargs": config.legacy.extra_env_kwargs}
if config.is_legacy
else {"config_data": env_config_data(config.env), "max_concurrent": config.serve.max_concurrent}
)
# ``serve.pool`` (static or elastic) sizes the server. serve_env applies the logging
# setup in this process and in every spawned worker.
serve_env(
**pool_serve_kwargs(config.serve.pool),
legacy=config.is_legacy,
address=config.serve.address,
log_setup=partial(setup_env_server_logging, config.log.level, config.log.json_logging),
**server_kwargs,
config_data=env_config_data(config.env),
max_concurrent=config.serve.max_concurrent,
)
+1 -2
View File
@@ -105,7 +105,7 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
# One EnvServerConfig TOML per launcher-managed source: `env-server @ <path>` binds
# at the source's deterministic address, where the orchestrator connects. The source's
# env/serve/legacy blocks carry over; its other knobs (sampling, algo, name, ...) are
# env/serve blocks carry over; its other knobs (sampling, algo, name, ...) are
# orchestrator-side.
for split, source, address in env_servers(config):
env_dir = output_dir / ENVS_DIR / split
@@ -114,7 +114,6 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
env_server_dict = {
"env": source_dict["env"],
"serve": {**source_dict.get("serve", {}), "address": address},
"legacy": source_dict.get("legacy", {}),
"log": {"level": config.orchestrator.log.vf_level, "json_logging": config.orchestrator.log.json_logging},
}
with open(env_dir / f"{source.resolved_name}.toml", "wb") as f:
+1 -1
View File
@@ -15,7 +15,7 @@ class RAEAlgorithm(Algorithm):
"""Role-conditioned advantage estimation (SPIRAL, arXiv:2506.24119):
credit = reward minus a per-agent EMA baseline of that agent's rewards.
The advantage estimator for multi-agent self-play envs (kuhn-poker-v1 and
The advantage estimator for multi-agent self-play envs (kuhn-poker and
friends): in a zero-sum game the group mean is ~0 whatever the policy does,
and centering all agents against it mixes their opposite reward scales — a
structural first-mover edge would read as permanent credit for one agent.
+55 -97
View File
@@ -1,9 +1,7 @@
"""RolloutDispatcher: schedules rollouts under a shared permit counter.
- Capacity (``max_inflight_episodes``) is shared across train + eval. One permit is
one episode: for a v1 env one ``run`` request, and a group-scoring task that runs
N rollouts in one call reserves N permits (each bridged v0 rollout is its own
single-agent episode).
one episode: one ``run`` request against an env server.
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
- Emit-everything invariant: every dispatched episode eventually reaches
``out_q`` exactly once, as a ``list[Rollout]``. Failures
@@ -183,11 +181,11 @@ class RolloutDispatcher:
@property
def inflight_train_count(self) -> int:
return sum(m.rollout_count for m in self.inflight.values() if m.kind == "train")
return sum(1 for m in self.inflight.values() if m.kind == "train")
@property
def inflight_eval_count(self) -> int:
return sum(m.rollout_count for m in self.inflight.values() if m.kind == "eval")
return sum(1 for m in self.inflight.values() if m.kind == "eval")
@property
def available_permits(self) -> int:
@@ -197,7 +195,7 @@ class RolloutDispatcher:
def inflight_by_env(self) -> dict[tuple[RolloutKind, str], int]:
counts: dict[tuple[RolloutKind, str], int] = defaultdict(int)
for meta in self.inflight.values():
counts[(meta.kind, meta.env_name)] += meta.rollout_count
counts[(meta.kind, meta.env_name)] += 1
return dict(counts)
@property
@@ -356,10 +354,7 @@ class RolloutDispatcher:
for gid, group in list(self.groups.items()):
if group.kind != kind or group.rollouts_to_schedule <= 0:
continue
env = envs.get(group.env_name)
cost = group.rollouts_to_schedule if env.requires_group_scoring else 1
if cost <= self.available_permits:
return await self.schedule_group_rollout(gid, group)
return await self.schedule_group_rollout(gid, group)
fresh = self.next_fresh_group(kind, envs)
if fresh is None:
@@ -370,14 +365,13 @@ class RolloutDispatcher:
def next_fresh_group(self, kind: RolloutKind, envs) -> GroupState | None:
"""Pop the next example from the corresponding source and wrap it in
a ``GroupState``. Returns ``None`` if the source is empty or the
picked env's permit cost doesn't fit."""
a ``GroupState``. Returns ``None`` if the source is empty."""
if kind == "train":
source = self.train_source
else:
assert self.eval_source is not None
source = self.eval_source
example = source.next_example(self.available_permits)
example = source.next_example()
if example is None:
return None
@@ -388,8 +382,7 @@ class RolloutDispatcher:
return GroupState(
kind=kind,
env_name=env_name,
task_idx=example["task_idx"],
task=example.get("task"),
task=example["task"],
rollouts_to_schedule=group_size,
target_rollouts=group_size,
eval_step=eval_step,
@@ -397,7 +390,7 @@ class RolloutDispatcher:
)
async def schedule_group_rollout(self, group_id: uuid.UUID, group: GroupState) -> bool:
"""Dispatch one ``run`` / ``run_group`` task for this group.
"""Dispatch one ``run`` task for this group.
Returns False only if we couldn't even schedule one rollout (no clients
ready, no permits). Returns True after issuing one task — the caller
@@ -405,8 +398,8 @@ class RolloutDispatcher:
"""
# Train rollouts use the env sampler's pool via the
# renderer/token train client. Eval always evaluates the policy and
# goes through the eval client (chat-completions) — the same path the
# legacy orchestrator used, so eval scores stay comparable.
# goes through the eval client (chat-completions) so eval scores stay
# comparable.
if group.kind == "eval":
pool, model_name = self.policy_pool, self.policy.model_name
live_sourced = True
@@ -429,73 +422,48 @@ class RolloutDispatcher:
else:
cache_salt = None
if env.requires_group_scoring:
# Legacy-only route (a v1 env never group-scores) — addressed by row.
permits = group.rollouts_to_schedule
group.rollouts_to_schedule = 0
await self.acquire(permits)
task: asyncio.Task = asyncio.create_task(
env.run_group(
client=client,
task_idx=group.task_idx,
model_name=model_name,
group_size=permits,
cache_salt=cache_salt,
)
)
else:
# A v1 env takes the task itself; the legacy bridge its dataset row.
if group.task is not None:
addressing = {"task_data": group.task.data.model_dump(mode="json")}
else:
addressing = {"task_idx": group.task_idx}
permits = 1
group.rollouts_to_schedule -= 1
await self.acquire(permits)
task = asyncio.create_task(
env.run(
client=client,
model_name=model_name,
cache_salt=cache_salt,
**addressing,
)
group.rollouts_to_schedule -= 1
await self.acquire()
task = asyncio.create_task(
env.run(
client=client,
model_name=model_name,
cache_salt=cache_salt,
task_data=group.task.data.model_dump(mode="json"),
)
)
self.inflight[task] = InflightRollout(
kind=group.kind,
env_name=group.env_name,
group_id=group_id,
policy_version=group.policy_version_at_start,
rollout_count=permits,
client_config=client,
eval_step=group.eval_step,
)
return True
async def acquire(self, n: int) -> None:
"""Reserve ``n`` permits + rate-limit each one. Caller must precheck
``available_permits >= n``; this is not a blocking acquire."""
for _ in range(n):
if self.rate_limiter is not None:
await self.rate_limiter.acquire()
self.inflight_permits += 1
async def acquire(self) -> None:
"""Reserve one permit + rate-limit it. Caller must precheck
``available_permits >= 1``; this is not a blocking acquire."""
if self.rate_limiter is not None:
await self.rate_limiter.acquire()
self.inflight_permits += 1
def release(self, n: int) -> None:
self.inflight_permits -= n
def release(self) -> None:
self.inflight_permits -= 1
async def handle_completed_rollout(self, task: asyncio.Task) -> None:
"""Emit every dispatched episode exactly once to ``out_q``: a ``run``
result as one episode, a legacy ``run_group`` result as ``rollout_count``
single-trace episodes. Task exceptions synthesize ``rollout_count``
error-marker episodes so the sink's count-to-``group_size`` finalization
still triggers. Cancelled tasks (popped by ``drop_group``) raise
``CancelledError`` and are discarded — ``drop_group`` already emitted
their markers.
"""Emit every dispatched episode exactly once to ``out_q``. Task
exceptions synthesize an error-marker episode so the sink's
count-to-``group_size`` finalization still triggers. Cancelled tasks
(popped by ``drop_group``) raise ``CancelledError`` and are discarded —
``drop_group`` already emitted their markers.
"""
meta = self.inflight.pop(task, None)
if meta is None:
return # already handled by drop_group / cancel_inflight_rollouts
self.release(meta.rollout_count)
self.release()
group = self.groups.get(meta.group_id)
is_synth_exception = False
@@ -508,13 +476,12 @@ class RolloutDispatcher:
return
except Exception as exc:
get_logger().warning(f"Rollout task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
task_idx = group.task_idx if group is not None else -1
task_idx = group.task.data.idx if group is not None else -1
rollouts = [
Rollout(
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
agent=vf.AgentInfo(config=vf.AgentConfig()),
)
for _ in range(meta.rollout_count)
]
for r in rollouts:
r.record_error(exc)
@@ -533,13 +500,7 @@ class RolloutDispatcher:
get_logger().warning(
f"Rollout failed in group {meta.group_id} ({meta.env_name}) — {r.last_error.type}: {r.last_error.message}"
)
if meta.rollout_count == 1:
# A ``run`` task: the whole result is one episode.
await self.emit_episode(meta, group, rollouts)
else:
# A legacy ``run_group`` task: one single-trace episode per trace.
for r in rollouts:
await self.emit_episode(meta, group, [r])
await self.emit_episode(meta, group, rollouts)
async def emit_episode(self, meta: InflightRollout, group: GroupState | None, rollouts: list[Rollout]) -> None:
"""Stamp prime-rl metadata onto one completed episode and put it on
@@ -571,7 +532,7 @@ class RolloutDispatcher:
(both in-flight and not-yet-scheduled). Returns the count for
off-policy metrics."""
group = self.groups.pop(group_id, None)
task_idx = group.task_idx if group is not None else -1
task_idx = group.task.data.idx if group is not None else -1
# Sync claim phase: pop matching tasks from ``self.inflight`` and
# release their permits in one non-yielding sweep. After this loop
@@ -583,26 +544,25 @@ class RolloutDispatcher:
if meta.group_id != group_id:
continue
del self.inflight[task]
self.release(meta.rollout_count)
self.release()
claimed.append((task, meta))
tasks_to_cancel = [task for task, _ in claimed]
inflight_cancelled = sum(meta.rollout_count for _, meta in claimed)
inflight_cancelled = len(claimed)
last_meta: InflightRollout | None = claimed[-1][1] if claimed else None
for _, meta in claimed:
for _ in range(meta.rollout_count):
trace = Rollout(
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
agent=vf.AgentInfo(config=vf.AgentConfig()),
ok=False,
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
stop_condition="error",
)
await self.emit_episode(meta, group, [trace])
trace = Rollout(
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
agent=vf.AgentInfo(config=vf.AgentConfig()),
ok=False,
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
stop_condition="error",
)
await self.emit_episode(meta, group, [trace])
# For non-group-scoring envs, the group may have rollouts that
# were never dispatched (``rollouts_to_schedule > 0``). Emit
# markers for those too so the sink hits ``target_rollouts``
# The group may have rollouts that were never dispatched
# (``rollouts_to_schedule > 0``). Emit markers for those too so the
# sink hits ``target_rollouts``
#
# ``last_meta`` can be ``None`` if the only inflight task for this
# group completed naturally between ``on_version_pending``'s snapshot
@@ -614,7 +574,6 @@ class RolloutDispatcher:
env_name=group.env_name,
group_id=group_id,
policy_version=group.policy_version_at_start,
rollout_count=1,
eval_step=group.eval_step,
)
unscheduled_cancelled = group.rollouts_to_schedule
@@ -636,7 +595,6 @@ class RolloutDispatcher:
env_name=group.env_name,
group_id=group_id,
policy_version=group.policy_version_at_start if group else 0,
rollout_count=1,
eval_step=group.eval_step,
)
if group is not None
@@ -657,8 +615,8 @@ class RolloutDispatcher:
"""Cancel all in-flight rollouts. Used on shutdown — doesn't emit
markers since the sinks are being torn down anyway."""
for meta in self.inflight.values():
self.metrics.record_cancellation(kind=meta.kind, env_name=meta.env_name, n=meta.rollout_count)
self.release(meta.rollout_count)
self.metrics.record_cancellation(kind=meta.kind, env_name=meta.env_name)
self.release()
tasks = list(self.inflight.keys())
self.inflight.clear()
self.groups.clear()
@@ -676,9 +634,9 @@ class RolloutDispatcher:
if meta.kind != "train":
continue
self.inflight.pop(task, None)
self.release(meta.rollout_count)
self.metrics.record_cancellation(kind="train", env_name=meta.env_name, n=meta.rollout_count)
cancelled += meta.rollout_count
self.release()
self.metrics.record_cancellation(kind="train", env_name=meta.env_name)
cancelled += 1
train_tasks.append(task)
train_group_ids.add(meta.group_id)
for gid in train_group_ids:
+21 -51
View File
@@ -10,9 +10,7 @@ once, and each dispatched episode ships its task's data on the request
(``task_data``); the server pydantic-validates it into the taskset's declared
``TaskData`` type and runs it. That keeps the server (and every worker in its
pool) stateless about data — no per-worker dataset loads, no idx-addressed task
cache — and gives the orchestrator real tasks to cycle, shuffle, and filter. Only
the legacy (v0) bridge, whose dataset genuinely lives server-side, is still driven
by ``task_idx`` (its count comes from ``info``).
cache — and gives the orchestrator real tasks to cycle, shuffle, and filter.
The server answers one ``Episode`` per run request, whose traces we validate into
``Trace[WireTaskData]`` — real ``vf.Trace``\\ s (never loose dicts) whose task
@@ -41,7 +39,7 @@ from prime_rl.utils.logger import get_logger
ROLLOUT_TYPE = Rollout[vf.WireTaskData]
# Max wait for the env server to answer health. Generous because the launcher spawns
# servers concurrently with the orchestrator, and a legacy server loads its dataset
# servers concurrently with the orchestrator, and a server imports its env package
# before serving.
ENV_SERVER_STARTUP_TIMEOUT = 600.0
@@ -56,12 +54,11 @@ class Env:
self.sampling_args: dict = {}
self.num_tasks: int | None = 0
"""Task count; ``None`` means the taskset is infinite."""
self.requires_group_scoring: bool = False
self.tasks: Iterator[vf.Task] | None = None
"""The env's tasks, client-side; ``None`` for legacy (its dataset lives on the
server). A finite taskset is materialized at ``start()`` (``num_tasks`` is its
count) and iterated from there; an infinite one streams off its generator.
Consumed once — by ``TrainSource`` (train) or ``EvalEnv.start`` (eval)."""
"""The env's tasks, client-side, set at ``start()``. A finite taskset is
materialized (``num_tasks`` is its count) and iterated from there; an infinite
one streams off its generator. Consumed once — by ``TrainSource`` (train) or
``EvalEnv.start`` (eval)."""
self._env_client: EnvClient | None = None
@property
@@ -75,29 +72,23 @@ class Env:
return self._env_client
async def start(self) -> None:
"""Connect to the env server and load the taskset client-side (legacy instead
asks the server for ``info`` — its dataset is server-side)."""
"""Connect to the env server and load the taskset client-side."""
get_logger().debug(f"Connecting {self.name} to env server {self.address}")
self._env_client = EnvClient(address=self.address)
# The server may still be coming up (the launcher spawns it concurrently with
# the orchestrator), so poll until it answers.
await self.env_client.wait_for_server_startup(timeout=ENV_SERVER_STARTUP_TIMEOUT)
if self.config.is_legacy:
info = await self.env_client.info()
self.num_tasks = info.num_tasks
self.requires_group_scoring = info.requires_group_scoring
taskset = vf.load_taskset(self.config.env.taskset)
if type(taskset).INFINITE:
self.tasks = iter(taskset.load())
self.num_tasks = None
else:
taskset = vf.load_taskset(self.config.env.taskset)
if type(taskset).INFINITE:
self.tasks = iter(taskset.load())
self.num_tasks = None
else:
# Materialize off the event loop — load() may pull a dataset.
materialized = await asyncio.to_thread(lambda: list(taskset.load()))
self.tasks = iter(materialized)
self.num_tasks = len(materialized)
# Materialize off the event loop — load() may pull a dataset.
materialized = await asyncio.to_thread(lambda: list(taskset.load()))
self.tasks = iter(materialized)
self.num_tasks = len(materialized)
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
get_logger().info(f"Env {self.name} ready: num_tasks={num_tasks} group_scoring={self.requires_group_scoring}")
get_logger().info(f"Env {self.name} ready: num_tasks={num_tasks}")
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
sampling = {**self.sampling_args}
@@ -110,17 +101,13 @@ class Env:
client: vf.ClientConfig,
model_name: str,
cache_salt: str | None,
task_data: dict | None = None,
task_idx: int | None = None,
task_data: dict,
) -> list[Rollout]:
"""Run one episode; return its typed Traces. A v1 env takes the task itself
(``task_data``); the legacy bridge is addressed by dataset row (``task_idx``).
A zero-trace episode raises (the dispatcher synthesizes the error marker); a
not-``ok`` episode marks its clean traces failed so partial episodes never
train."""
"""Run one episode; return its typed Traces. A zero-trace episode raises (the
dispatcher synthesizes the error marker); a not-``ok`` episode marks its clean
traces failed so partial episodes never train."""
episode = await self.env_client.run(
task_data=task_data,
task_idx=task_idx,
client=client,
model=model_name,
sampling=self._sampling(cache_salt),
@@ -140,19 +127,6 @@ class Env:
rollout.ok = False
return rollouts
async def run_group(
self, client: vf.ClientConfig, task_idx: int, model_name: str, group_size: int, cache_salt: str | None
) -> list[Rollout]:
"""Run a group of rollouts for ``task_idx`` (group-scoring envs); return typed Traces."""
wires = await self.env_client.run_group(
task_idx=task_idx,
n=group_size,
client=client,
model=model_name,
sampling=self._sampling(cache_salt),
)
return [ROLLOUT_TYPE.model_construct(**dict(wire)) for wire in wires]
class TrainEnv(Env):
config: TrainSourceConfig
@@ -175,15 +149,11 @@ class EvalEnv(Env):
async def start(self) -> None:
await super().start()
n = self.config.num_examples
if self.tasks is None: # legacy: the dataset lives on the server — address it by row
count = self.num_tasks if n < 0 else min(n, self.num_tasks)
self.examples = [{"task_idx": i} for i in range(count)]
return
if self.num_tasks is None and n < 0:
raise ValueError(f"Eval env {self.name} has an infinite taskset — set num_examples to bound it")
# A fixed eval set, pulled off the tasks once and reused every epoch.
tasks = list(self.tasks) if n < 0 else list(islice(self.tasks, n))
self.examples = [{"task_idx": task.data.idx, "task": task} for task in tasks]
self.examples = [{"task": task} for task in tasks]
EnvT = TypeVar("EnvT", bound=Env)
+1 -3
View File
@@ -63,15 +63,13 @@ class EvalSink:
"""One entry per accumulating ``(env, eval_step)`` batch:
``(env_name, eval_step, batch_count, expected, buffered)``.
``batch_count`` is finalized-group episodes in ``pending_batches``;
``buffered`` is partial-group episode arrivals from non-group-scoring envs."""
``buffered`` is partial-group episode arrivals."""
batch_counts: dict[tuple[str, int], int] = dict(self.pending_batch_episodes)
buffered: dict[tuple[str, int], int] = {}
for group_id, rollouts in self.pending_groups.items():
if not rollouts:
continue
env_name = rollouts[0].env_name
if self.eval_envs.get(env_name).requires_group_scoring:
continue
bkey = (env_name, rollouts[0].eval_step)
buffered[bkey] = buffered.get(bkey, 0) + self.pending_group_episodes.get(group_id, 0)
return [
+4 -11
View File
@@ -1,9 +1,8 @@
"""EvalSource: trigger-driven, finite-per-epoch pull of eval examples.
The orchestrator pokes ``trigger(step)`` after each ship + once at
startup; the dispatcher pulls via ``next_example(available_permits)``
until ``bool(source) == False``. Constructed only when eval is
configured."""
startup; the dispatcher pulls via ``next_example()`` until
``bool(source) == False``. Constructed only when eval is configured."""
from __future__ import annotations
@@ -68,16 +67,10 @@ class EvalSource:
self.queue.append(row)
return fired
def next_example(self, available_permits: int) -> dict | None:
"""Pop the next eval example if the head's permit cost fits in
``available_permits``; otherwise leave it for a later call."""
def next_example(self) -> dict | None:
"""Pop the next eval example, or ``None`` when the queue is empty."""
if not self.queue:
return None
head = self.queue[0]
env = self.eval_envs.get(head["env_name"])
cost = env.config.group_size if env.requires_group_scoring else 1
if cost > available_permits:
return None
return self.queue.popleft()
def __bool__(self) -> bool:
+1 -1
View File
@@ -271,7 +271,7 @@ class EpisodeMetrics:
def episodes(self) -> list[list[Rollout]]:
"""The subset's rollouts grouped into their episodes. A rollout without an
``episode_id`` (legacy envs, synthesized error markers) is its own episode."""
``episode_id`` (synthesized error markers) is its own episode."""
grouped: dict[str, list[Rollout]] = {}
for r in self.rollouts:
grouped.setdefault(r.episode_id or r.id, []).append(r)
+4 -17
View File
@@ -108,13 +108,9 @@ class TrainSink:
return self.pending_tokens, self.token_batch_size, "tokens"
def buffered_count(self) -> int:
"""Episodes that have arrived but sit in not-yet-complete groups
(non-group-scoring envs) — buffered in the sink ahead of the batch."""
return sum(
self.pending_group_episodes.get(group_id, 0)
for group_id, rollouts in self.pending_groups.items()
if rollouts and not self.train_envs.get(rollouts[0].env_name).requires_group_scoring
)
"""Episodes that have arrived but sit in not-yet-complete groups —
buffered in the sink ahead of the batch."""
return sum(self.pending_group_episodes.values())
def pending_batch_by_env(self) -> dict[str, int]:
"""Per-env breakdown of ``batch_progress()`` (``pending_batch`` only);
@@ -170,8 +166,7 @@ class TrainSink:
await self.train_envs.get(rollout.env_name).algorithm.finalize_rollout(rollout)
async def process_group(self, group_id: uuid.UUID) -> None:
"""Finalize one GRPO group: drop errored rollouts (the whole group
when ``requires_group_scoring`` and any failed), assign advantages,
"""Finalize one GRPO group: drop errored rollouts, assign advantages,
run pre-batch filters, append survivors to ``pending_batch``."""
group = self.pending_groups.pop(group_id, [])
self.pending_group_episodes.pop(group_id, None)
@@ -188,15 +183,7 @@ class TrainSink:
survivors = [r for r in group if not r.has_error]
num_errored = len(group) - len(survivors)
# Group-scoring envs: any failure makes survivors' rewards unsafe
# (computed relative to the missing ones)
env = self.train_envs.get(env_name)
if num_errored > 0 and env.requires_group_scoring:
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} | "
f"rollouts={len(group)} (errored={num_errored}) | dropped: group-scored partial"
)
return
# Untrainable traces carry no samples and must not skew the group baseline.
survivors = [r for r in survivors if r.agent.trainable]
if not survivors:
+13 -34
View File
@@ -1,12 +1,10 @@
"""TrainSource: weighted round-robin across train envs, infinite pull.
Weights are each env's configured ``ratio`` (default 1, i.e. equal weight
per env). A v1 env serves the tasks the orchestrator loaded client-side: a
per env). An env serves the tasks the orchestrator loaded client-side: a
finite one as a shuffled table (reshuffled with ``seed=epoch`` on cursor
exhaustion), an infinite one (``num_tasks is None``) straight off its
generator — every pull is a fresh task and there are no epochs to shuffle.
A legacy env's dataset lives on its server, so it serves shuffled task
*indices*."""
generator — every pull is a fresh task and there are no epochs to shuffle."""
from __future__ import annotations
@@ -19,11 +17,9 @@ from prime_rl.orchestrator.envs import TrainEnvs
class TrainSource:
"""``next_example(available_permits)`` picks a weighted-RR env and
returns its next example (or ``None`` when the env's per-call permit
cost doesn't fit — the dispatch loop retries when permits free up).
Returned dicts carry ``env_name`` + ``task_idx`` (+ ``task`` for v1 envs,
whose data is shipped to the env server at dispatch).
"""``next_example()`` picks a weighted-RR env and returns its next
example. Returned dicts carry ``env_name`` + ``task``, whose data is
shipped to the env server at dispatch.
The data position round-trips through a checkpoint via ``state_dict()``
/ ``load_state_dict()``: per-env ``{epoch, cursor}`` plus the env-choice
@@ -37,10 +33,6 @@ class TrainSource:
def __init__(self, train_envs: TrainEnvs) -> None:
self.rng = random.Random(42)
# The drawn-but-undispatched env. A draw whose permit cost doesn't fit
# is held here (head-of-line) rather than redrawn, so the choice stream
# advances exactly once per dispatched example and stays reproducible.
self.pending_env: str | None = None
self.envs = list(train_envs)
if not self.envs:
raise ValueError("TrainSource needs at least one train env")
@@ -53,22 +45,17 @@ class TrainSource:
self.iters: dict[str, Iterator[vf.Task]] = {}
self.epochs: dict[str, int] = {}
self.cursors: dict[str, int] = {}
# Group-scoring envs reserve ``group_size`` permits up front;
# per-rollout envs need 1
self.env_costs: dict[str, int] = {}
for env in self.envs:
if env.tasks is None: # legacy: sample over the index range from info()
rows: list[dict] | None = [{"task_idx": i, "env_name": env.name} for i in range(env.num_tasks)]
elif env.num_tasks is None: # infinite: pull the generator per example
rows = None
assert env.tasks is not None, f"env {env.name} not started"
if env.num_tasks is None: # infinite: pull the generator per example
rows: list[dict] | None = None
self.iters[env.name] = env.tasks
else:
rows = [{"task_idx": task.data.idx, "task": task, "env_name": env.name} for task in env.tasks]
rows = [{"task": task, "env_name": env.name} for task in env.tasks]
self.base_rows[env.name] = rows
self.epochs[env.name] = 1
self.cursors[env.name] = 0
self.examples[env.name] = self._shuffle(env.name)
self.env_costs[env.name] = env.config.group_size if env.requires_group_scoring else 1
self.env_names = [e.name for e in self.envs]
self.weights: list[float] = [float(e.config.ratio) for e in self.envs]
@@ -85,17 +72,14 @@ class TrainSource:
return rows
def state_dict(self) -> dict:
"""Env-choice RNG state + pending draw + per-env ``{epoch, cursor}``."""
"""Env-choice RNG state + per-env ``{epoch, cursor}``."""
return {
"rng": self.rng.getstate(),
"pending_env": self.pending_env,
"envs": {name: {"epoch": self.epochs[name], "cursor": self.cursors[name]} for name in self.epochs},
}
def load_state_dict(self, state_dict: dict) -> None:
self.rng.setstate(state_dict["rng"])
pending = state_dict["pending_env"]
self.pending_env = pending if pending in self.env_costs else None
for name, position in state_dict["envs"].items():
if name not in self.base_rows:
continue
@@ -107,19 +91,14 @@ class TrainSource:
else:
self.examples[name] = self._shuffle(name)
def next_example(self, available_permits: int) -> dict | None:
if self.pending_env is None:
self.pending_env = self.rng.choices(self.env_names, weights=self.weights, k=1)[0]
env_name = self.pending_env
if self.env_costs[env_name] > available_permits:
return None
self.pending_env = None
def next_example(self) -> dict | None:
env_name = self.rng.choices(self.env_names, weights=self.weights, k=1)[0]
rows = self.examples[env_name]
cursor = self.cursors[env_name]
if rows is None: # infinite env: pull the next generated task
task = next(self.iters[env_name])
self.cursors[env_name] = cursor + 1
return {"task_idx": task.data.idx, "task": task, "env_name": env_name}
return {"task": task, "env_name": env_name}
if cursor >= len(rows):
self.epochs[env_name] += 1
rows = self._shuffle(env_name)
+3 -6
View File
@@ -41,13 +41,12 @@ RolloutKind = Literal["train", "eval"]
@dataclass
class InflightRollout:
"""Per-task scheduling state in the dispatcher; one entry per in-flight
``run`` / ``run_group`` task."""
``run`` task."""
kind: RolloutKind
env_name: str
group_id: uuid.UUID
policy_version: int
rollout_count: int
client_config: vf.ClientConfig | None = None
off_policy_steps: int = 0
eval_step: int | None = None
@@ -60,12 +59,10 @@ class GroupState:
kind: RolloutKind
env_name: str
task_idx: int
task: vf.Task
"""The group's task — its data is shipped on every dispatch."""
rollouts_to_schedule: int
target_rollouts: int
task: vf.Task | None = None
"""The group's task (v1 envs — its data is shipped on every dispatch). ``None`` for
legacy envs, which are addressed by ``task_idx`` alone."""
emitted: int = 0
eval_step: int | None = None
pinned_client: vf.ClientConfig | None = None
+2 -2
View File
@@ -2,8 +2,8 @@ import msgspec
# Encoded tensor: {dtype: "float32", shape: [...], data: <bytes>}.
# Mirrors verifiers.utils.serve_utils.msgpack_encoder so the same wire
# shape is used end-to-end from renderer → orchestrator → trainer.
# Mirrors verifiers' env-serve msgpack encoder so the same wire shape is
# used end-to-end from renderer → orchestrator → trainer.
class EncodedTensor(msgspec.Struct, array_like=True, gc=False):
dtype: str
shape: list[int]
+1 -4
View File
@@ -23,10 +23,7 @@ async def safe_cancel_all(tasks: list[asyncio.Task]) -> None:
class EventLoopLagMonitor:
"""Monitors how busy the main event loop is by timing short sleeps.
Vendored from verifiers.utils.async_utils (the orchestrator now runs on
v1 and no longer depends on v1 verifiers)."""
"""Monitors how busy the main event loop is by timing short sleeps."""
def __init__(self, measure_interval: float = 0.1, max_measurements: int = 1000):
assert measure_interval > 0 and max_measurements > 0
+36 -51
View File
@@ -1,10 +1,10 @@
"""End-to-end integration test for the Qwen3-VL renderer path.
Walks a multimodal request through the full client stack — RendererClient
→ renderers.client.generate → /inference/v1/generate features payload —
with the HTTP layer mocked, and verifies that vLLM can deserialize the
features back into engine inputs identical to what its own server-side
processor would have produced for the same messages.
Walks a multimodal request through ``renderers.client.generate`` — the
tokenize + /inference/v1/generate features payload path the v1 train
client drives — with the HTTP layer mocked, and verifies that vLLM can
deserialize the features back into engine inputs identical to what its
own server-side processor would have produced for the same messages.
This is the strongest end-to-end check we can run without a GPU. The
remaining missing piece (vLLM actually consuming the engine input,
@@ -17,7 +17,6 @@ import asyncio
import json
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock
import httpx
import pytest
@@ -43,9 +42,9 @@ pytestmark = pytest.mark.skipif(
class _FakeOpenAI:
"""Minimal AsyncOpenAI stand-in that captures POST bodies.
The renderer client calls ``client.post(absolute_url, body=...)``;
we capture the body for assertions and return a canned generate
response so the parse-side of the flow runs.
``renderers.client.generate`` calls ``client.post(absolute_url,
body=...)``; we capture the body for assertions and return a canned
generate response so the parse-side of the flow runs.
"""
def __init__(self):
@@ -76,9 +75,9 @@ class _FakeOpenAI:
return httpx.Response(200, content=json.dumps(payload).encode())
def test_renderer_client_qwen3_vl_e2e_features_payload_roundtrips_through_vllm():
"""Walk a Qwen3-VL multimodal turn through the renderer client and
verify the resulting ``/inference/v1/generate`` body has a valid
def test_generate_qwen3_vl_e2e_features_payload_roundtrips_through_vllm():
"""Walk a Qwen3-VL multimodal turn through ``renderers.client.generate``
and verify the resulting ``/inference/v1/generate`` body has a valid
``features`` payload that:
1. parses through vLLM's ``GenerateRequest`` pydantic model,
@@ -89,13 +88,9 @@ def test_renderer_client_qwen3_vl_e2e_features_payload_roundtrips_through_vllm()
"""
from PIL import Image
from renderers.base import load_tokenizer
from renderers.client import generate
from renderers.qwen3_vl import Qwen3VLRenderer
from transformers import AutoProcessor
from verifiers.clients.renderer_client import RendererClient
from verifiers.types import (
ClientConfig,
UserMessage,
)
from vllm.entrypoints.scale_out.token_in_token_out.mm_serde import decode_mm_kwargs_item
from vllm.entrypoints.scale_out.token_in_token_out.protocol import GenerateRequest
@@ -106,47 +101,37 @@ def test_renderer_client_qwen3_vl_e2e_features_payload_roundtrips_through_vllm()
image_pad_id = tokenizer.convert_tokens_to_ids("<|image_pad|>")
# ── Manually wire a RendererClient bypassing the pool factory. ──────
client_cfg = ClientConfig(client_type="renderer", base_url="http://fake-host:8000/v1")
rc = object.__new__(RendererClient)
rc._config = client_cfg
rc._renderer = renderer
rc._pool_size = 1
rc._client = _FakeOpenAI()
rc.logger = MagicMock()
fake = _FakeOpenAI()
# ── Build a verifiers-shaped user message with an image. ────────────
# ── Build a user message with an image (OpenAI content-part shape). ─
img = Image.new("RGB", (224, 224), color=(64, 128, 255))
# The renderer accepts the OpenAI ``image_url`` content-part shape —
# the same shape verifiers' UserMessage carries through.
user = UserMessage(
content=[
{"type": "text", "text": "What's in this picture?"},
# Embed the PIL image directly. The verifiers→renderer message
# converter forwards content unchanged for our purposes.
{"type": "image", "image": img},
]
)
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": "What's in this picture?"},
# Embed the PIL image directly; the renderer consumes it as-is.
{"type": "image", "image": img},
],
}
]
# to_native_prompt converts to renderer-shaped messages.
prompt, _ = asyncio.run(rc.to_native_prompt([user]))
sampling = {"max_tokens": 16}
response = asyncio.run(
rc.get_native_response(
prompt=prompt,
result = asyncio.run(
generate(
client=fake,
renderer=renderer,
messages=messages,
model=_MODEL,
sampling_args=sampling,
tools=None,
sampling_params={"max_tokens": 16},
# Explicit cap so generate() skips the /v1/models discovery round-trip.
max_prompt_len=1_000_000,
)
)
# ── The HTTP body should carry a features payload. ──────────────────
fake = rc.client
assert isinstance(fake, _FakeOpenAI)
assert len(fake.calls) == 1
body = fake.calls[0]["body"]
assert "features" in body, "RendererClient should ship features for image content"
assert "features" in body, "generate should ship features for image content"
features = body["features"]
# ── Pydantic-roundtrip through vLLM's GenerateRequest model. ────────
@@ -184,7 +169,7 @@ def test_renderer_client_qwen3_vl_e2e_features_payload_roundtrips_through_vllm()
assert item["image_grid_thw"].data.tolist() == expected_grid
# ── Response parsed through renderer's parse_response. ──────────────
assert response["completion_ids"] == [50, 60, 151645]
assert result["completion_ids"] == [50, 60, 151645]
# multi_modal_data surfaces on the result so the caller can persist it.
assert response["multi_modal_data"] is not None
assert len(response["multi_modal_data"].mm_items["image"]) == 1
assert result["multi_modal_data"] is not None
assert len(result["multi_modal_data"].mm_items["image"]) == 1
+8 -3
View File
@@ -182,7 +182,12 @@ def test_env_algo_overrides_top_level():
{
"renderer": {"name": "qwen3"}, # echo needs the renderer's role attribution
"algo": {"type": "echo"},
"train": {"source": [{"legacy": {"id": "a"}, "algo": {"type": "grpo"}}, {"legacy": {"id": "b"}}]},
"train": {
"source": [
{"env": {"taskset": {"id": "reverse-text"}}, "algo": {"type": "grpo"}},
{"env": {"taskset": {"id": "reverse-text"}}, "name": "b"},
]
},
}
)
env_a, env_b = config.train.source
@@ -199,7 +204,7 @@ def test_env_algo_overrides_top_level():
OrchestratorConfig.model_validate(
{
"renderer": {"name": "qwen3"},
"train": {"env": [{"legacy": {"id": "removed"}}]},
"train": {"env": [{"env": {"taskset": {"id": "removed"}}}]},
}
)
@@ -207,7 +212,7 @@ def test_env_algo_overrides_top_level():
OrchestratorConfig.model_validate(
{
"renderer": {"name": "qwen3"},
"eval": {"env": [{"legacy": {"id": "removed"}}]},
"eval": {"env": [{"env": {"taskset": {"id": "removed"}}}]},
}
)
Generated
+335 -307
View File
File diff suppressed because it is too large Load Diff