Compare commits

...
Author SHA1 Message Date
c1674ac93c feat: dynamic pass-through vLLM inference metrics to W&B (#3240)
* feat: dynamic pass-through vLLM inference metrics to wandb

Replace the hand-curated inference metric allowlist with a dynamic
pass-through collector: every vllm:* Prometheus family is logged,
per-engine under inference/engine/{id}/ and cross-engine aggregations
(min/max/mean/median/sum) under inference/{agg|prefill|decode}/.

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

* refactor: drop InferenceMetricsConfig, keep collect_inference_metrics flag

Hardcode poll interval, aggregations, and per-engine logging in the
collector; config surface is unchanged from main (collect_inference_metrics
+ inference_metrics_roles).

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

* Add inference health section to the overview view

Seven panels, each pairing the fleet aggregate (mean/sum) with the
cross-engine tail that flags a single sick engine - max for pressure
(KV usage, preemptions, waiting, prompt-token recompute), min for
health (prefix hit rate, generation throughput). A saturated engine
thrashing its KV cache hides inside fleet means; the tails surface it.

Also compute the prefix-cache hit-rate ratio per engine (not only
pooled over the fleet) so the min/max aggregations exist for it.

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

* Flatten metric keys to inference/{scope}/{metric}/{stat}

Drop the vllm: family prefix (the collector only admits vllm:* families,
so it carries no information), flatten per-engine series from
inference/engine/{id}/... to inference/{id}/..., and move scope-level
quantiles (:p50 -> /p50) and the pooled ratio (-> /pooled) into the
stat segment so every key reads inference/{scope}/{metric}/{stat}.

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

* Add min series to KV usage and waiting panels

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 16:03:10 -07:00
halleriteandGitHub b1d4f2fa6c chore(ruff): pin path-dep import classification (#3263) 2026-08-13 19:14:25 +02:00
d43e0f329b perf!: remove the zero-gradient-ratio metric (#3249)
get_zero_gradient_ratio launched a device-scalar transfer and a
count_nonzero kernel per parameter plus two all-reduces and a sync every
step, serializing the post-backward path on models with many tensors: on
Qwen3-30B-A3B (8xH200, seq 8K) it cost 1.4 s of a 4.6 s step. The metric
also read 1.0 on every validation run, so it was likely not measuring
what it intended on FSDP2 DTensor gradients. Removes the metric, its
trainer call sites, and the Prometheus gauge.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 09:10:44 -07:00
8c1f196dd3 chore: bump verifiers for prime-sandboxes 0.2.36 (#3259)
* Bump verifiers for prime-sandboxes 0.2.36

prime-sandboxes 0.2.36 gives each live ACP process its own HTTP
transport (prime#831), fixing the h2 stream-cap deadlock that made
rlm rollouts fail with 'process stdin RPC failed (deadline_exceeded)'
above ~100 concurrency.

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

* Repoint verifiers submodule to merged main

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 16:43:09 -07:00
chethanukandGitHub 753a3fec0a docs(k8s): drop dead docs links and fix PVC name in Helm README (#3242)
k8s/README.md links to /prime-rl/kubernetes, /prime-rl/deployment and
/prime-rl/troubleshooting. All three return 404: those pages are not in
docs/ and have no entry in docs/mint.json. Drop the two Kubernetes links
and the troubleshooting bullet — the README's own sections are the chart
documentation — and retarget the deployment bullet at /prime-rl/scaling,
which is where the multi-node and SLURM content lives now.

The uninstall snippets also name the wrong PVC. templates/pvc.yaml names
it {{ .Release.Name }}-shared-data, so after the documented
`helm install my-exp`, `kubectl delete pvc prime-rl-shared-data` fails
NotFound and reads as if the data is already gone.

Closes #3054
2026-08-12 09:42:34 -07:00
3ad13dd0bc fix: skip weight pre-download for random-init debug runs (#3247)
pre_download_model fetched the full weight snapshot even when
debug.random_init never reads the weights — for large models that pulls
hundreds of GB (GLM-5: ~1.4 TB) into the shared HF cache before a fake-data
debug run. Random-init runs now fetch only config and tokenizer files.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 08:51:06 -07:00
ee06d333e4 chore: bump verifiers to latest main (#3246)
verifiers 42a6c95de..a506236ec:
- fix: compact harness runs without a container (#2329)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 20:02:42 -07:00
91d4b92597 chore: bump verifiers and prime-envs to latest main (#3245)
verifiers d53ab56f0..42a6c95de:
- feat: metadata-only overrides for config-plugged functions (#2323)
- feat(compact): one tool call per turn, notes-only carryover (#2313)

prime-envs 1f1f915a..b30aad36:
- feat!: add train/eval graph split to wikispeedia (#759)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 19:40:27 -07:00
82acb12ed7 fix: revert default DPPO masking thresholds to 0.2 (#3244)
Revert bb23623d6 (#3236). The tighter 0.1 trust region masks the few
high-leverage decision tokens once their probability moves >0.1 across
off-policy staleness, slowing LoRA convergence (reverse-text LoRA CI
smoke: 0.5-0.6 reward @ step 15 vs 0.8 with 0.2).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 19:35:13 -07:00
124f9694a6 chore: stop dumping resolved orchestrator config to control/ (#3243)
The orchestrator wrote its resolved config to <output_dir>/control/orch.toml,
a relict of the deprecated multi-tenant setup. The launcher already persists
resolved configs under the output directory.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 19:27:44 -07:00
4308fe3aba chore!: point at the renamed prime-envs repo (#3241)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 14:54:54 -07:00
minh hoangandGitHub da53d4c064 chore: bump renderers for Nemotron 3.5 (Lightning) renderer (#3239) 2026-08-11 12:23:08 -07:00
minh hoangandGitHub efe8e7fda8 feat: auto-resolve parsers for Nemotron 3.5 (Lightning) (#3237)
* feat: auto-resolve parsers for Nemotron 3.5 (Lightning)

* test: drop NVFP4 expectation, BF16 only

* clean up docstrings
2026-08-11 11:57:36 -07:00
bb23623d6e feat: change default masking thresholds to 0.1 (#3236)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 11:23:41 -07:00
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
f2ead102d1 feat(laguna): support per-element attention gating (#3229)
Laguna's config carries a `gating` field that prime-rl's port dropped, so
g_proj was always sized for per-head gating:

    self.g_proj = nn.Linear(config.hidden_size, num_heads, bias=False)

That matches Laguna S (`gating = "per-head"`, g_proj [48, 3072]) and is wrong
for Laguna M (`gating = "per-element"`, g_proj [8192, 4096] = num_heads x
head_dim). Loading M.1 fails with

    ValueError: Size mismatch between saved torch.Size([8192, 4096]) and
    current: torch.Size([64, 4096]) for model.layers.0.self_attn.g_proj.weight

Carry `gating` on LagunaConfig and size g_proj from it, following upstream's
semantics exactly (poolside/Laguna-M.1 modeling_laguna.py):

    True / "per-element"  one gate per (head, head_dim) channel
    "per-head"            one gate per head, broadcast across head_dim
    False                 no gating

Note the default is `True`, not "per-head": a checkpoint that omits the field
gets per-element upstream, so defaulting the other way would silently mis-size
it. bool and str are both accepted for the same reason.

Verified against both checkpoints: g_proj matches [48, 3072] for S-2.1 and
[8192, 4096] for M.1, and the gate math is bit-identical to upstream in both
modes (max abs diff 0.0). End to end, a 4-node trainer probe loads the real
452GB M.1 checkpoint through load_dcp_from_hf with no size mismatch, where it
previously failed at model construction.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 21:41:50 -07:00
halleriteandGitHub c698bdeb2a chore: bump research-environments for the toolset register() fix (#3230) 2026-08-10 20:11:43 +02:00
6e33f3f82f chore: bump verifiers for the unbounded model-call timeout (#3227)
Bumps deps/verifiers 29e3a0f7 -> a298bcfe, picking up two commits:

  a298bcfe fix(v1): restore the unbounded model-call timeout (#2304)
  9ca7f5d6 Fix plain HTTP CONNECT for Docker framework routes (#2298)

verifiers#2218 had consolidated client construction into
build_async_openai/DEFAULT_TIMEOUT and, in doing so, replaced the relay
client's explicit `timeout=None` with a 600s read timeout mirroring the OAI
SDK default. That cap reached every model-call path, since DEFAULT_TIMEOUT
feeds clients/eval.py as well as build_async_openai, which judge.py and
clients/train.py use.

600s is fine for chat-shaped evals and wrong for RL: a single agentic turn on
a long SWE trajectory routinely runs past ten minutes, and when it does the
rollout dies as `ProviderError: Request timed out` even though the model was
still producing. Because it truncates the longest trajectories specifically,
the loss is biased rather than uniform. Seen on the laguna-s SWE RL run here.
#2304 restores unbounded read/write/pool and keeps connect at 5.0 so an
unreachable endpoint still fails fast.

No lockfile change: verifiers is an editable path dependency
(`source = { editable = "deps/verifiers" }`), and neither commit touches its
pyproject, so only the submodule pointer moves.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 21:41:10 -07:00
102 changed files with 979 additions and 1288 deletions
+1 -1
View File
@@ -174,7 +174,7 @@ jobs:
run: |
if [ -f .gitmodules ]; then
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/pydantic-config deps/verifiers deps/renderers deps/research-environments
git submodule update --init --recursive -- deps/pydantic-config deps/verifiers deps/renderers deps/prime-envs
fi
- name: Log in to GitHub Container Registry
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
with:
+2 -2
View File
@@ -32,7 +32,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
- name: Install dependencies
@@ -100,7 +100,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
- name: Install dependencies
+1 -1
View File
@@ -79,7 +79,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
with:
+3 -3
View File
@@ -4,9 +4,9 @@
[submodule "renderers"]
path = deps/renderers
url = git@github.com:PrimeIntellect-ai/renderers.git
[submodule "research-environments"]
path = deps/research-environments
url = git@github.com:PrimeIntellect-ai/research-environments.git
[submodule "prime-envs"]
path = deps/prime-envs
url = git@github.com:PrimeIntellect-ai/prime-envs.git
[submodule "pydantic-config"]
path = deps/pydantic-config
url = https://github.com/PrimeIntellect-ai/pydantic-config
+1 -1
View File
@@ -95,7 +95,7 @@ cd prime-rl
2. Initialize submodules
```bash
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
```
3. Install [uv](https://docs.astral.sh/uv/)
+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"
Vendored Submodule
+1
Submodule deps/prime-envs added at b30aad3637
+1 -1
+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
@@ -20,7 +20,7 @@ The three processes communicate through configurable transports — by default t
curl -sSL https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/main/scripts/install.sh | bash
```
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`research-environments`](https://github.com/PrimeIntellect-ai/research-environments) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`prime-envs`](https://github.com/PrimeIntellect-ai/prime-envs) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
You need at least one NVIDIA GPU (RTX 3090/4090/5090, A100, H100, H200, or B200). Single-GPU runs are supported for debugging; production RL is typically 1× inference node + 1+ trainer nodes.
+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 |
+6 -6
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"
@@ -122,7 +122,7 @@ choices = ["A", "B"]
# [[orchestrator.train.source.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
@@ -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"
@@ -155,7 +155,7 @@ choices = ["A", "B"]
# [[orchestrator.train.source.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
@@ -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"
@@ -193,7 +193,7 @@ model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
# [[orchestrator.eval.source.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
+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"
+9 -9
View File
@@ -105,20 +105,20 @@ 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]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.train.source.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
# path = "deps/prime-envs/rubrics/swe.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
@@ -144,19 +144,19 @@ 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"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
# path = "deps/prime-envs/rubrics/swe.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
@@ -178,19 +178,19 @@ 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"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
# path = "deps/prime-envs/rubrics/swe.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
+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"
+8 -8
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
@@ -223,8 +223,8 @@ uv run eval reverse-text-v1 --harness.id null \
```bash
helm uninstall my-exp
# Optionally delete shared data:
kubectl delete pvc prime-rl-shared-data
# Optionally delete shared data. The PVC is named <release-name>-shared-data:
kubectl delete pvc my-exp-shared-data
```
**What the Helm chart provides:**
+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"
+4 -6
View File
@@ -2,8 +2,6 @@
This directory contains a Helm chart for deploying prime-rl training infrastructure on Kubernetes clusters.
For complete documentation, see the [Kubernetes guide](https://docs.primeintellect.ai/prime-rl/kubernetes).
## Quick Start
```bash
@@ -64,11 +62,11 @@ helm install my-exp ./prime-rl \
```bash
helm uninstall my-exp
kubectl delete pvc prime-rl-shared-data # Warning: deletes data!
# The PVC is named <release-name>-shared-data (see templates/pvc.yaml)
kubectl delete pvc my-exp-shared-data # Warning: deletes data!
```
## Learn More
- [Full Kubernetes documentation](https://docs.primeintellect.ai/prime-rl/kubernetes) - Architecture, configuration, distributed training
- [Deployment guide](https://docs.primeintellect.ai/prime-rl/deployment) - Non-Kubernetes deployments
- [Troubleshooting](https://docs.primeintellect.ai/prime-rl/troubleshooting) - Common issues
- [Scaling guide](https://docs.primeintellect.ai/prime-rl/scaling) - Non-Kubernetes multi-node deployment (SLURM), parallelism, benchmarking
+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
@@ -33,6 +33,7 @@ REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "deepseek_r1"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Super"), "nemotron_v3"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Nano"), "nano_v3"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3\.5"), "nano_v3"),
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
# Only Qwen3 Thinking models reason — Instruct/base models do not.
(re.compile(r"^Qwen/Qwen3-.*Thinking"), "deepseek_r1"),
+18 -19
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",
@@ -128,28 +128,28 @@ override-dependencies = [
"openenv-core",
]
# research-environments packages are auto-discovered as workspace members, so new
# prime-envs packages are auto-discovered as workspace members, so new
# envs there need no per-package registration. verifiers' example envs are opt-in:
# only the ones prime-rl trains or tests on are listed, so an upstream example with
# conflicting pins can't break the shared lock. Install them with
# `uv sync --all-packages`.
[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/prime-envs/environments/*/*",
"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/prime-envs/environments/tool_use/tau2_synth",
"deps/prime-envs/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,prime-envs}/environments.
verifiers = { path = "deps/verifiers", editable = true }
renderers = { path = "deps/renderers", editable = true }
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
@@ -263,6 +261,7 @@ select = ["F", "I"]
# Without this, ruff classifies prime_rl.configs.* as third-party because it
# doesn't live under src/.
known-first-party = ["prime_rl"]
known-third-party = ["verifiers", "renderers", "pydantic_config"]
[tool.ruff]
line-length = 120
+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.
+2 -2
View File
@@ -26,10 +26,10 @@ 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`.
Environment packages are uv **workspace members**. Those under `deps/prime-envs/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`.
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
+2 -2
View File
@@ -35,8 +35,8 @@ 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'))"`).
If a local env exists under `deps/research-environments/environments/` or
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym'))"`).
If a local env exists under `deps/prime-envs/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
--package <env>` (one) — they're auto-discovered, no `pyproject.toml` edit needed.
+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,
)
+2 -3
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:
@@ -648,7 +647,7 @@ def rl(config: RLConfig):
if not config.dry_run:
from prime_rl.trainer.model import pre_download_model
pre_download_model(config.trainer.model.name)
pre_download_model(config.trainer.model.name, skip_weights=config.trainer.model.debug.random_init)
if config.slurm is not None:
rl_slurm(config)
+1 -1
View File
@@ -214,7 +214,7 @@ def sft(config: SFTConfig):
if not config.dry_run:
from prime_rl.trainer.model import pre_download_model
pre_download_model(config.model.name)
pre_download_model(config.model.name, skip_weights=config.model.debug.random_init)
if config.slurm is not None:
sft_slurm(config)
+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:
+228 -329
View File
@@ -1,9 +1,10 @@
from __future__ import annotations
import asyncio
import math
import time
from collections import deque
from dataclasses import dataclass, field
from statistics import mean, median
import wandb
from httpx import AsyncClient
@@ -12,105 +13,41 @@ from prometheus_client.parser import text_string_to_metric_families
from prime_rl.utils.logger import get_logger
POLL_INTERVAL = 5.0
WINDOW_SIZE = 20
FETCH_TIMEOUT = 5.0
METRIC_PREFIX = "vllm:"
PD_ROLES = {"prefill", "decode"}
QUANTILES = {"p50": 0.5, "p90": 0.9, "p99": 0.99}
AGGREGATIONS = {"min": min, "max": max, "sum": sum, "mean": mean, "median": median}
COUNTER_KEYS = {
"vllm:prompt_tokens": "prompt_tokens_total",
"vllm:prompt_tokens_total": "prompt_tokens_total",
"vllm:generation_tokens": "generation_tokens_total",
"vllm:generation_tokens_total": "generation_tokens_total",
"vllm:request_success": "request_success_total",
"vllm:request_success_total": "request_success_total",
"vllm:prefix_cache_queries": "prefix_cache_queries",
"vllm:prefix_cache_queries_total": "prefix_cache_queries",
"vllm:prefix_cache_hits": "prefix_cache_hits",
"vllm:prefix_cache_hits_total": "prefix_cache_hits",
"vllm:nixl_num_failed_transfers_total": "nixl_failed_transfers_total",
"vllm:nixl_num_failed_notifications_total": "nixl_failed_notifications_total",
"vllm:nixl_num_kv_expired_reqs_total": "nixl_kv_expired_requests_total",
}
GAUGE_KEYS = {
"vllm:num_requests_running": "running_requests",
"vllm:num_requests_waiting": "waiting_requests",
"vllm:kv_cache_usage_perc": "kv_cache_usage_perc",
"vllm:gpu_cache_usage_perc": "kv_cache_usage_perc",
"vllm:cpu_cache_usage_perc": "cpu_cache_usage_perc",
"vllm:gpu_prefix_cache_hit_rate": "gpu_prefix_cache_hit_rate",
"vllm:cpu_prefix_cache_hit_rate": "cpu_prefix_cache_hit_rate",
}
HISTOGRAM_SUM_KEYS = {
"vllm:request_prefill_time_seconds_sum": "request_prefill_time_seconds_sum",
"vllm:request_decode_time_seconds_sum": "request_decode_time_seconds_sum",
"vllm:request_queue_time_seconds_sum": "request_queue_time_seconds_sum",
"vllm:time_to_first_token_seconds_sum": "time_to_first_token_seconds_sum",
"vllm:inter_token_latency_seconds_sum": "inter_token_latency_seconds_sum",
"vllm:e2e_request_latency_seconds_sum": "e2e_request_latency_seconds_sum",
"vllm:nixl_xfer_time_seconds_sum": "nixl_xfer_time_seconds_sum",
"vllm:nixl_bytes_transferred_sum": "nixl_bytes_transferred_sum",
}
HISTOGRAM_COUNT_KEYS = {
"vllm:request_prefill_time_seconds_count": "request_prefill_time_seconds_count",
"vllm:request_decode_time_seconds_count": "request_decode_time_seconds_count",
"vllm:request_queue_time_seconds_count": "request_queue_time_seconds_count",
"vllm:time_to_first_token_seconds_count": "time_to_first_token_seconds_count",
"vllm:inter_token_latency_seconds_count": "inter_token_latency_seconds_count",
"vllm:e2e_request_latency_seconds_count": "e2e_request_latency_seconds_count",
"vllm:nixl_xfer_time_seconds_count": "nixl_xfer_time_seconds_count",
"vllm:nixl_bytes_transferred_count": "nixl_bytes_transferred_count",
# Scope-level ratios derived from counter deltas; each operand lists legacy and
# OpenMetrics sample names, whichever the running vLLM version emits.
RATIO_METRICS = {
"prefix_cache_hit_rate": (
("prefix_cache_hits", "prefix_cache_hits_total"),
("prefix_cache_queries", "prefix_cache_queries_total"),
),
}
@dataclass
class EngineRollup:
running_requests: float = 0.0
waiting_requests: float = 0.0
kv_cache_usage_perc: float = 0.0
cpu_cache_usage_perc: float | None = None
gpu_prefix_cache_hit_rate: float | None = None
cpu_prefix_cache_hit_rate: float | None = None
prompt_tokens_total: float = 0.0
generation_tokens_total: float = 0.0
request_success_total: float = 0.0
prefix_cache_queries: float = 0.0
prefix_cache_hits: float = 0.0
nixl_failed_transfers_total: float = 0.0
nixl_failed_notifications_total: float = 0.0
nixl_kv_expired_requests_total: float = 0.0
request_prefill_time_seconds_sum: float = 0.0
request_prefill_time_seconds_count: float = 0.0
request_decode_time_seconds_sum: float = 0.0
request_decode_time_seconds_count: float = 0.0
request_queue_time_seconds_sum: float = 0.0
request_queue_time_seconds_count: float = 0.0
time_to_first_token_seconds_sum: float = 0.0
time_to_first_token_seconds_count: float = 0.0
inter_token_latency_seconds_sum: float = 0.0
inter_token_latency_seconds_count: float = 0.0
e2e_request_latency_seconds_sum: float = 0.0
e2e_request_latency_seconds_count: float = 0.0
nixl_xfer_time_seconds_sum: float = 0.0
nixl_xfer_time_seconds_count: float = 0.0
nixl_bytes_transferred_sum: float = 0.0
nixl_bytes_transferred_count: float = 0.0
class HistogramSnapshot:
sum: float = 0.0
count: float = 0.0
buckets: dict[float, float] = field(default_factory=dict)
"""Upper bound (``le``) -> cumulative count."""
@dataclass
class NodeRollup:
engines: dict[str, EngineRollup] = field(default_factory=dict)
class EngineSnapshot:
"""All samples scraped for one engine, keyed by vLLM sample name.
@property
def engine_count(self) -> int:
return len(self.engines)
Samples that carry extra labels (e.g. ``finished_reason``) are summed over
those labels so each name maps to a single value per engine.
"""
def summed(self, attribute: str) -> float:
return sum(getattr(engine, attribute) for engine in self.engines.values())
def values(self, attribute: str) -> list[float]:
return [value for engine in self.engines.values() if (value := getattr(engine, attribute)) is not None]
gauges: dict[str, float] = field(default_factory=dict)
counters: dict[str, float] = field(default_factory=dict)
histograms: dict[str, HistogramSnapshot] = field(default_factory=dict)
@dataclass(frozen=True)
@@ -118,284 +55,222 @@ class MetricsEndpoint:
client: AsyncClient
role: str | None
key: str
name: str
@dataclass(frozen=True)
class TimedRollup:
class TimedSnapshot:
timestamp: float
rollup: NodeRollup
snapshot: EngineSnapshot
@dataclass(frozen=True)
class EndpointSample:
class EngineSample:
endpoint: MetricsEndpoint
engine_label: str
timestamp: float
rollup: NodeRollup
snapshot: EngineSnapshot
@property
def engine_id(self) -> str:
return f"{self.endpoint.name}.{self.engine_label}"
@property
def key(self) -> tuple[str, str]:
return (self.endpoint.key, self.engine_label)
def parse_prometheus_text(text: str) -> NodeRollup:
"""Parse vLLM Prometheus metrics into per-engine counters, gauges, and histogram totals."""
engines: dict[str, EngineRollup] = {}
def parse_prometheus_text(text: str) -> dict[str, EngineSnapshot]:
"""Parse a vLLM Prometheus exposition into one snapshot per engine label."""
engines: dict[str, EngineSnapshot] = {}
for family in text_string_to_metric_families(text):
if not family.name.startswith(METRIC_PREFIX) or family.type not in ("counter", "gauge", "histogram"):
continue
for sample in family.samples:
engine_id = sample.labels.get("engine", "aggregate")
engine = engines.setdefault(engine_id, EngineRollup())
if sample.name in GAUGE_KEYS:
setattr(engine, GAUGE_KEYS[sample.name], float(sample.value))
elif sample.name in COUNTER_KEYS:
attribute = COUNTER_KEYS[sample.name]
setattr(engine, attribute, getattr(engine, attribute) + float(sample.value))
elif sample.name in HISTOGRAM_SUM_KEYS:
setattr(engine, HISTOGRAM_SUM_KEYS[sample.name], float(sample.value))
elif sample.name in HISTOGRAM_COUNT_KEYS:
setattr(engine, HISTOGRAM_COUNT_KEYS[sample.name], float(sample.value))
return NodeRollup(engines=engines)
if sample.name.endswith("_created") or not math.isfinite(sample.value):
continue
engine = engines.setdefault(sample.labels.get("engine", "0"), EngineSnapshot())
name = sample.name.removeprefix(METRIC_PREFIX)
if family.type == "gauge":
engine.gauges[name] = engine.gauges.get(name, 0.0) + sample.value
elif family.type == "counter":
engine.counters[name] = engine.counters.get(name, 0.0) + sample.value
else:
histogram = engine.histograms.setdefault(family.name.removeprefix(METRIC_PREFIX), HistogramSnapshot())
if sample.name.endswith("_sum"):
histogram.sum += sample.value
elif sample.name.endswith("_count"):
histogram.count += sample.value
elif sample.name.endswith("_bucket"):
le = float(sample.labels["le"])
histogram.buckets[le] = histogram.buckets.get(le, 0.0) + sample.value
return engines
def build_metrics_endpoints(
admin_clients: list[AsyncClient], roles: list[str | None] | None = None
) -> list[MetricsEndpoint]:
"""Attach optional P/D roles to admin clients used for metrics polling."""
"""Attach optional P/D roles and stable display names to admin clients."""
if roles is None:
roles = [None] * len(admin_clients)
if len(roles) != len(admin_clients):
raise ValueError(f"Got {len(roles)} inference metric role(s) for {len(admin_clients)} admin client(s)")
endpoints: list[MetricsEndpoint] = []
counts: dict[str, int] = {}
for client, role in zip(admin_clients, roles):
normalized_role = role if role in PD_ROLES else None
if role is not None and normalized_role is None:
if role is not None and role not in PD_ROLES:
raise ValueError(f"Unsupported inference metrics role: {role}")
endpoints.append(MetricsEndpoint(client=client, role=normalized_role, key=str(client.base_url).rstrip("/")))
prefix = role or "server"
index = counts.get(prefix, 0)
counts[prefix] = index + 1
endpoints.append(
MetricsEndpoint(
client=client,
role=role,
key=str(client.base_url).rstrip("/"),
name=f"{prefix}{index}",
)
)
return endpoints
def max_vio(values: list[float]) -> float:
"""Return the max-load violation used for MoE load-balance reporting."""
if not values:
return 0.0
balanced_load = sum(values) / len(values)
if balanced_load == 0:
return 0.0
return (max(values) - balanced_load) / balanced_load
def counter_rate(samples: list[EndpointSample], previous: dict[str, TimedRollup], attribute: str) -> float | None:
"""Sum per-endpoint counter rates for a scope."""
rates: list[float] = []
for sample in samples:
previous_sample = previous.get(sample.endpoint.key)
if previous_sample is None:
continue
dt = sample.timestamp - previous_sample.timestamp
delta = sample.rollup.summed(attribute) - previous_sample.rollup.summed(attribute)
if dt <= 0 or delta < 0:
continue
rates.append(delta / dt)
if not rates:
def histogram_quantile(buckets: dict[float, float], quantile: float) -> float | None:
"""Estimate a quantile from cumulative bucket deltas, Prometheus-style."""
total = max(buckets.values(), default=0.0)
if total <= 0:
return None
return sum(rates)
target = quantile * total
previous_le, previous_cumulative = 0.0, 0.0
for le, cumulative in sorted(buckets.items()):
if cumulative >= target:
if math.isinf(le) or cumulative == previous_cumulative:
return previous_le
return previous_le + (le - previous_le) * (target - previous_cumulative) / (
cumulative - previous_cumulative
)
previous_le, previous_cumulative = le, cumulative
return None
def counter_ratio(
samples: list[EndpointSample],
previous: dict[str, TimedRollup],
numerator_attribute: str,
denominator_attribute: str,
) -> float | None:
"""Compute a scope-level ratio from counter deltas."""
numerator_delta = 0.0
denominator_delta = 0.0
for sample in samples:
previous_sample = previous.get(sample.endpoint.key)
if previous_sample is None:
continue
endpoint_numerator_delta = sample.rollup.summed(numerator_attribute) - previous_sample.rollup.summed(
numerator_attribute
def engine_values(sample: EngineSample, previous: TimedSnapshot | None) -> dict[str, float]:
"""Pass-through values plus interval-derived rates and means for one engine.
Counter rates use ``:rate`` (per second), histogram interval means use
``:mean``, and histogram completion rates use ``:rate``, mirroring how one
would express them as PromQL over the poll interval.
"""
values: dict[str, float] = dict(sample.snapshot.gauges)
values.update(sample.snapshot.counters)
for name, histogram in sample.snapshot.histograms.items():
values[f"{name}_sum"] = histogram.sum
values[f"{name}_count"] = histogram.count
if previous is None:
return values
dt = sample.timestamp - previous.timestamp
if dt <= 0:
return values
for name, value in sample.snapshot.counters.items():
delta = value - previous.snapshot.counters.get(name, 0.0)
if delta >= 0:
values[f"{name}:rate"] = delta / dt
for name, histogram in sample.snapshot.histograms.items():
previous_histogram = previous.snapshot.histograms.get(name, HistogramSnapshot())
sum_delta = histogram.sum - previous_histogram.sum
count_delta = histogram.count - previous_histogram.count
if count_delta >= 0:
values[f"{name}:rate"] = count_delta / dt
if count_delta > 0 and sum_delta >= 0:
values[f"{name}:mean"] = sum_delta / count_delta
# Per-engine ratios so the scope aggregations include min/max — the pooled
# scope-level ratio alone hides a single engine's collapse (e.g. one engine
# thrashing at a 5% prefix hit rate inside a healthy fleet average).
for name, (numerator_names, denominator_names) in RATIO_METRICS.items():
numerator = sum(
sample.snapshot.counters.get(c, 0.0) - previous.snapshot.counters.get(c, 0.0) for c in numerator_names
)
endpoint_denominator_delta = sample.rollup.summed(denominator_attribute) - previous_sample.rollup.summed(
denominator_attribute
denominator = sum(
sample.snapshot.counters.get(c, 0.0) - previous.snapshot.counters.get(c, 0.0) for c in denominator_names
)
if endpoint_numerator_delta < 0 or endpoint_denominator_delta < 0:
continue
numerator_delta += endpoint_numerator_delta
denominator_delta += endpoint_denominator_delta
if denominator_delta <= 0:
return None
return numerator_delta / denominator_delta
if numerator >= 0 and denominator > 0:
values[name] = numerator / denominator
return values
def histogram_average(
samples: list[EndpointSample],
previous: dict[str, TimedRollup],
sum_attribute: str,
count_attribute: str,
) -> float | None:
"""Compute a scope-level histogram average from sum/count deltas."""
sum_delta = 0.0
count_delta = 0.0
for sample in samples:
previous_sample = previous.get(sample.endpoint.key)
if previous_sample is None:
continue
endpoint_sum_delta = sample.rollup.summed(sum_attribute) - previous_sample.rollup.summed(sum_attribute)
endpoint_count_delta = sample.rollup.summed(count_attribute) - previous_sample.rollup.summed(count_attribute)
if endpoint_sum_delta < 0 or endpoint_count_delta < 0:
continue
sum_delta += endpoint_sum_delta
count_delta += endpoint_count_delta
if count_delta <= 0:
return None
return sum_delta / count_delta
def mean(values: list[float]) -> float | None:
"""Return the arithmetic mean for non-empty metric value lists."""
if not values:
return None
return sum(values) / len(values)
def bucket_deltas(sample: EngineSample, previous: TimedSnapshot | None) -> dict[str, dict[float, float]]:
"""Per-histogram cumulative bucket deltas since the previous scrape."""
if previous is None:
return {}
deltas: dict[str, dict[float, float]] = {}
for name, histogram in sample.snapshot.histograms.items():
previous_buckets = previous.snapshot.histograms.get(name, HistogramSnapshot()).buckets
delta = {le: count - previous_buckets.get(le, 0.0) for le, count in histogram.buckets.items()}
if delta and all(count >= 0 for count in delta.values()):
deltas[name] = delta
return deltas
def build_scope_metrics(
scope: str,
samples: list[EndpointSample],
previous: dict[str, TimedRollup],
values_per_engine: list[dict[str, float]],
bucket_deltas_per_engine: list[dict[str, dict[float, float]]],
counter_deltas: dict[str, float],
) -> dict[str, float]:
"""Build W&B metric values for one inference scope."""
running_values = [value for sample in samples for value in sample.rollup.values("running_requests")]
waiting_values = [value for sample in samples for value in sample.rollup.values("waiting_requests")]
kv_values = [value for sample in samples for value in sample.rollup.values("kv_cache_usage_perc")]
cpu_kv_values = [value for sample in samples for value in sample.rollup.values("cpu_cache_usage_perc")]
prefix_gauge_values = [value for sample in samples for value in sample.rollup.values("gpu_prefix_cache_hit_rate")]
cpu_prefix_values = [value for sample in samples for value in sample.rollup.values("cpu_prefix_cache_hit_rate")]
"""Aggregate per-engine values into ``inference/{scope}/{metric}/{agg}`` series."""
prefix = f"inference/{scope}"
metrics: dict[str, float] = {
f"{prefix}/running_requests": sum(running_values),
f"{prefix}/waiting_requests": sum(waiting_values),
f"{prefix}/running_imbalance": max_vio(running_values),
f"{prefix}/waiting_imbalance": max_vio(waiting_values),
f"{prefix}/nixl_failed_transfers_total": sum(
sample.rollup.summed("nixl_failed_transfers_total") for sample in samples
),
f"{prefix}/nixl_failed_notifications_total": sum(
sample.rollup.summed("nixl_failed_notifications_total") for sample in samples
),
f"{prefix}/nixl_kv_expired_requests_total": sum(
sample.rollup.summed("nixl_kv_expired_requests_total") for sample in samples
),
}
metrics: dict[str, float] = {}
if kv_values:
metrics[f"{prefix}/kv_cache_usage_mean"] = sum(kv_values) / len(kv_values)
metrics[f"{prefix}/kv_cache_usage_max"] = max(kv_values)
if cpu_kv_values:
metrics[f"{prefix}/cpu_kv_cache_usage_mean"] = sum(cpu_kv_values) / len(cpu_kv_values)
metrics[f"{prefix}/cpu_kv_cache_usage_max"] = max(cpu_kv_values)
names = {name for values in values_per_engine for name in values}
for name in sorted(names):
engine_values_for_name = [values[name] for values in values_per_engine if name in values]
for aggregation, fn in AGGREGATIONS.items():
metrics[f"{prefix}/{name}/{aggregation}"] = fn(engine_values_for_name)
prefix_cache_hit_rate = counter_ratio(samples, previous, "prefix_cache_hits", "prefix_cache_queries")
if prefix_cache_hit_rate is None:
prefix_cache_hit_rate = mean(prefix_gauge_values)
if prefix_cache_hit_rate is not None:
metrics[f"{prefix}/prefix_cache_hit_rate"] = prefix_cache_hit_rate
cpu_prefix_cache_hit_rate = mean(cpu_prefix_values)
if cpu_prefix_cache_hit_rate is not None:
metrics[f"{prefix}/cpu_prefix_cache_hit_rate"] = cpu_prefix_cache_hit_rate
histogram_names = {name for deltas in bucket_deltas_per_engine for name in deltas}
for name in sorted(histogram_names):
pooled: dict[float, float] = {}
for deltas in bucket_deltas_per_engine:
for le, count in deltas.get(name, {}).items():
pooled[le] = pooled.get(le, 0.0) + count
for label, quantile in QUANTILES.items():
value = histogram_quantile(pooled, quantile)
if value is not None:
metrics[f"{prefix}/{name}/{label}"] = value
prompt_token_rate = counter_rate(samples, previous, "prompt_tokens_total")
generation_token_rate = counter_rate(samples, previous, "generation_tokens_total")
if scope == "prefill":
if prompt_token_rate is not None:
metrics[f"{prefix}/throughput"] = prompt_token_rate
elif scope == "decode":
if generation_token_rate is not None:
metrics[f"{prefix}/throughput"] = generation_token_rate
else:
token_rates = [rate for rate in (prompt_token_rate, generation_token_rate) if rate is not None]
if token_rates:
metrics[f"{prefix}/throughput"] = sum(token_rates)
counter_metrics = {
"completed_requests": "request_success_total",
"nixl_transfers_per_second": "nixl_xfer_time_seconds_count",
"nixl_bytes_per_second": "nixl_bytes_transferred_sum",
}
for metric_name, attribute in counter_metrics.items():
rate = counter_rate(samples, previous, attribute)
if rate is not None:
metrics[f"{prefix}/{metric_name}"] = rate
histogram_metrics = {
"avg_queue_time_seconds": (
"request_queue_time_seconds_sum",
"request_queue_time_seconds_count",
),
"avg_ttft_seconds": (
"time_to_first_token_seconds_sum",
"time_to_first_token_seconds_count",
),
"avg_tpot_seconds": (
"inter_token_latency_seconds_sum",
"inter_token_latency_seconds_count",
),
"avg_e2e_latency_seconds": (
"e2e_request_latency_seconds_sum",
"e2e_request_latency_seconds_count",
),
"nixl_transfer_time_seconds": (
"nixl_xfer_time_seconds_sum",
"nixl_xfer_time_seconds_count",
),
"nixl_avg_bytes_per_transfer": (
"nixl_bytes_transferred_sum",
"nixl_bytes_transferred_count",
),
}
for metric_name, (sum_attribute, count_attribute) in histogram_metrics.items():
value = histogram_average(samples, previous, sum_attribute, count_attribute)
if value is not None:
metrics[f"{prefix}/{metric_name}"] = value
prefill_time = histogram_average(
samples,
previous,
"request_prefill_time_seconds_sum",
"request_prefill_time_seconds_count",
)
decode_time = histogram_average(
samples,
previous,
"request_decode_time_seconds_sum",
"request_decode_time_seconds_count",
)
if scope == "prefill":
if prefill_time is not None:
metrics[f"{prefix}/avg_time_seconds"] = prefill_time
elif scope == "decode":
if decode_time is not None:
metrics[f"{prefix}/avg_time_seconds"] = decode_time
else:
time_values = [value for value in (prefill_time, decode_time) if value is not None]
if time_values:
metrics[f"{prefix}/avg_time_seconds"] = sum(time_values) / len(time_values)
for name, (numerator_names, denominator_names) in RATIO_METRICS.items():
numerator = sum(counter_deltas.get(candidate, 0.0) for candidate in numerator_names)
denominator = sum(counter_deltas.get(candidate, 0.0) for candidate in denominator_names)
if denominator > 0:
metrics[f"{prefix}/{name}/pooled"] = numerator / denominator
return metrics
class InferenceMetricsCollector:
"""Polls vLLM Prometheus /metrics and logs smoothed role-aware values to W&B.
"""Polls vLLM Prometheus /metrics and mirrors every engine metric to W&B.
The ``agg`` scope is always logged. The ``prefill`` and ``decode`` scopes are
logged only when endpoints are explicitly or implicitly identified as a
disaggregated P/D deployment.
All ``vllm:*`` families are passed through dynamically (the ``vllm:``
prefix is stripped): gauges and counters verbatim, histograms as
``_sum``/``_count`` plus derived ``:rate``/``:mean`` and scope-level
quantiles. Keys are ``inference/{scope}/{metric}/{stat}``: per-engine
series under ``inference/{engine_id}/{metric}`` and cross-engine
aggregations under ``inference/agg/{metric}/{stat}`` (plus
``inference/prefill|decode/...`` for disaggregated deployments). Engine
ids (``server0.0``, ``prefill0.1``, ...) never collide with the scope
names.
"""
def __init__(self, admin_clients: list[AsyncClient], roles: list[str | None] | None = None):
self.endpoints = build_metrics_endpoints(admin_clients, roles=roles)
self.metric_history: dict[str, deque[float]] = {}
self.previous: dict[str, TimedRollup] = {}
self.previous: dict[tuple[str, str], TimedSnapshot] = {}
self.task: asyncio.Task | None = None
self.has_pd_roles = {endpoint.role for endpoint in self.endpoints if endpoint.role is not None} == PD_ROLES
get_logger().info(
"Collecting inference metrics from "
+ ", ".join(f"{endpoint.name}={endpoint.key}" for endpoint in self.endpoints)
)
async def start(self):
wandb.define_metric("inference/*", step_metric="_timestamp")
@@ -415,7 +290,7 @@ class InferenceMetricsCollector:
async def fetch(endpoint: MetricsEndpoint) -> str | None:
try:
response = await endpoint.client.get("/metrics", timeout=5.0)
response = await endpoint.client.get("/metrics", timeout=FETCH_TIMEOUT)
response.raise_for_status()
return response.text
except Exception as e:
@@ -424,33 +299,57 @@ class InferenceMetricsCollector:
results = await asyncio.gather(*[fetch(endpoint) for endpoint in self.endpoints])
samples = [
EndpointSample(endpoint=endpoint, timestamp=now, rollup=parse_prometheus_text(text))
EngineSample(endpoint=endpoint, engine_label=engine_label, timestamp=now, snapshot=snapshot)
for endpoint, text in zip(self.endpoints, results)
if text is not None
for engine_label, snapshot in sorted(parse_prometheus_text(text).items())
]
if not samples:
return
metrics = build_scope_metrics("agg", samples, self.previous)
metrics = self.build_metrics(samples)
for sample in samples:
self.previous[sample.key] = TimedSnapshot(timestamp=sample.timestamp, snapshot=sample.snapshot)
if metrics:
metrics["_timestamp"] = time.time()
wandb.log(metrics)
def build_metrics(self, samples: list[EngineSample]) -> dict[str, float]:
values_per_engine = [engine_values(sample, self.previous.get(sample.key)) for sample in samples]
bucket_deltas_per_engine = [bucket_deltas(sample, self.previous.get(sample.key)) for sample in samples]
metrics: dict[str, float] = {}
for sample, values in zip(samples, values_per_engine):
for name, value in values.items():
metrics[f"inference/{sample.engine_id}/{name}"] = value
scopes: list[tuple[str, list[int]]] = [("agg", list(range(len(samples))))]
if self.has_pd_roles:
for role in sorted(PD_ROLES):
role_samples = [sample for sample in samples if sample.endpoint.role == role]
if role_samples:
metrics.update(build_scope_metrics(role, role_samples, self.previous))
indices = [i for i, sample in enumerate(samples) if sample.endpoint.role == role]
if indices:
scopes.append((role, indices))
for sample in samples:
self.previous[sample.endpoint.key] = TimedRollup(timestamp=sample.timestamp, rollup=sample.rollup)
smoothed_metrics = self.smooth_metrics(metrics)
if smoothed_metrics:
smoothed_metrics["_timestamp"] = time.time()
wandb.log(smoothed_metrics)
def smooth_metrics(self, metrics: dict[str, float]) -> dict[str, float]:
"""Add current values to the smoothing window and return W&B-ready metrics."""
for key, value in metrics.items():
self.metric_history.setdefault(key, deque(maxlen=WINDOW_SIZE)).append(value)
return {key: sum(values) / len(values) for key, values in self.metric_history.items() if values}
for scope, indices in scopes:
counter_deltas: dict[str, float] = {}
for i in indices:
previous = self.previous.get(samples[i].key)
if previous is None:
continue
for name, value in samples[i].snapshot.counters.items():
delta = value - previous.snapshot.counters.get(name, 0.0)
if delta >= 0:
counter_deltas[name] = counter_deltas.get(name, 0.0) + delta
metrics.update(
build_scope_metrics(
scope,
[values_per_engine[i] for i in indices],
[bucket_deltas_per_engine[i] for i in indices],
counter_deltas,
)
)
return metrics
async def stop(self):
if self.task is not None:
+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)
@@ -27,7 +27,6 @@ import time
import uuid
from typing import TYPE_CHECKING
import tomli_w
import verifiers.v1 as vf
from modelexpress import p2p_pb2
from modelexpress.client import MxClient
@@ -78,7 +77,6 @@ from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
from prime_rl.transport import setup_micro_batch_sender
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
from prime_rl.utils.client import init_nccl_broadcast, init_nixl_broadcast
from prime_rl.utils.config import to_toml_dict
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.monitor import setup_monitor
@@ -207,12 +205,6 @@ class Orchestrator:
config = self.config
set_default_executor()
# Persist the resolved config alongside the run
config_dir = config.output_dir / "control"
config_dir.mkdir(parents=True, exist_ok=True)
with open(config_dir / "orch.toml", "wb") as f:
tomli_w.dump(to_toml_dict(config), f)
get_logger().info(f"Initializing tokenizer ({config.tokenizer})")
self.tokenizer = setup_tokenizer(config.tokenizer)
+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
+13 -4
View File
@@ -68,14 +68,23 @@ from prime_rl.utils.utils import format_time
from prime_rl.utils.vlm import get_language_model, get_vision_encoder, is_vlm_architecture
def pre_download_model(model_name: str) -> None:
"""Pre-download model from HuggingFace Hub so all nodes have cached weights before training."""
def pre_download_model(model_name: str, *, skip_weights: bool = False) -> None:
"""Pre-download model from HuggingFace Hub so all nodes have cached weights before training.
With ``skip_weights`` (random-init debug runs), only config and tokenizer files are fetched.
"""
if Path(model_name).exists():
get_logger().info(f"Model {model_name} found at local path, skipping download")
return
get_logger().info(f"Pre-downloading model {model_name}")
t0 = time.perf_counter()
path = snapshot_download(repo_id=model_name, repo_type="model")
if skip_weights:
get_logger().info(f"Pre-downloading config and tokenizer for {model_name} (random init, skipping weights)")
path = snapshot_download(
repo_id=model_name, repo_type="model", allow_patterns=["*.json", "*.txt", "tokenizer*", "*.jinja"]
)
else:
get_logger().info(f"Pre-downloading model {model_name}")
path = snapshot_download(repo_id=model_name, repo_type="model")
get_logger().debug(
f"Finished pre-downloading model {model_name} to {path} in {format_time(time.perf_counter() - t0)}"
)
@@ -64,6 +64,7 @@ class LagunaConfig(PretrainedConfig):
eos_token_id: int | list[int] | None = None,
head_dim: int = 128,
attention_bias: bool = False,
gating: bool | str = True,
partial_rotary_factor: float | None = None,
num_attention_heads_per_layer: list[int] | None = None,
mlp_layer_types: list[str] | None = None,
@@ -98,6 +99,7 @@ class LagunaConfig(PretrainedConfig):
self.layer_types = layer_types or ["full_attention"] * num_hidden_layers
self.head_dim = head_dim
self.attention_bias = attention_bias
self.gating = gating
self.partial_rotary_factor = partial_rotary_factor
self.num_attention_heads_per_layer = num_attention_heads_per_layer or [num_attention_heads] * num_hidden_layers
self.mlp_layer_types = mlp_layer_types or ["dense"] + ["sparse"] * (num_hidden_layers - 1)
@@ -106,7 +106,16 @@ class LagunaFlashAttention(FlashAttention):
self.attention_dropout = config.attention_dropout
self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
self.sliding_window = config.sliding_window if self.is_local_attention else None
self.g_proj = nn.Linear(config.hidden_size, num_heads, bias=False)
# Attention output gating, mirroring the upstream Laguna implementation:
# True / "per-element" (Laguna M): one gate per (head, head_dim) channel
# "per-head" (Laguna S): one gate per head, broadcast across head_dim
# False: no gating
gating = getattr(config, "gating", True)
self.gating = bool(gating)
self.gate_per_head = gating == "per-head"
if self.gating:
gate_size = num_heads if self.gate_per_head else num_heads * self.head_dim
self.g_proj = nn.Linear(config.hidden_size, gate_size, bias=False)
self.o_proj = nn.Linear(num_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)
def forward(
@@ -127,8 +136,13 @@ class LagunaFlashAttention(FlashAttention):
)
input_shape = hidden_states.shape[:-1]
attn_output = attn_output.view(*input_shape, self.num_heads, self.head_dim)
gate = F.softplus(self.g_proj(hidden_states).float()).to(attn_output.dtype)
attn_output = (attn_output * gate.unsqueeze(-1)).view(*input_shape, -1)
if self.gating:
gate = F.softplus(self.g_proj(hidden_states).float()).to(attn_output.dtype)
# per-head gates broadcast across head_dim; per-element gates are already
# one-per-channel and line up with the [..., num_heads, head_dim] view.
gate = gate.unsqueeze(-1) if self.gate_per_head else gate.view(*attn_output.shape)
attn_output = attn_output * gate
attn_output = attn_output.view(*input_shape, -1)
return self.o_proj(attn_output), None
-5
View File
@@ -50,7 +50,6 @@ from prime_rl.trainer.utils import (
Tensors,
export_benchmark_json,
filter_rl_trainer_tensor_stats_for_wandb,
get_zero_gradient_ratio,
get_ckpt_disk_metrics,
setup_torch_distributed,
print_benchmark,
@@ -544,8 +543,6 @@ def train(config: TrainerConfig):
if grad_norm.device.type == "cpu":
grad_norm = grad_norm.to(torch.device("cuda"))
zero_grad_ratio = get_zero_gradient_ratio(model.parameters(), parallel_dims.dp_replicate)
# Update the model parameters
optimizer.step()
optimizer.zero_grad()
@@ -650,7 +647,6 @@ def train(config: TrainerConfig):
# Log optimizer metrics
optim_metrics = {
"optim/lr": current_lr,
"optim/zero_grad_ratio": zero_grad_ratio,
"step": progress.step,
}
if grad_norm is not None:
@@ -695,7 +691,6 @@ def train(config: TrainerConfig):
mfu=mfu,
entropy=tensor_stats.get("entropy/all/mean", 0.0),
mismatch_kl=tensor_stats.get("mismatch_kl/all/mean", 0.0),
zero_grad_ratio=zero_grad_ratio,
)
# Send heartbeat if configured
-4
View File
@@ -40,7 +40,6 @@ from prime_rl.trainer.utils import (
GarbageCollection,
MemoryProfiler,
export_benchmark_json,
get_zero_gradient_ratio,
get_ckpt_disk_metrics,
print_sample,
setup_torch_distributed,
@@ -470,8 +469,6 @@ def train(config: SFTConfig):
)
if grad_norm.device.type == "cpu":
grad_norm = grad_norm.to(torch.device("cuda"))
zero_grad_ratio = get_zero_gradient_ratio(model.parameters(), parallel_dims.dp_replicate)
logger.debug("Optimizer step")
optimizer.step()
optimizer.zero_grad()
@@ -578,7 +575,6 @@ def train(config: SFTConfig):
# Log optimizer metrics
optim_metrics = {
"optim/lr": current_lr,
"optim/zero_grad_ratio": zero_grad_ratio,
"step": progress.step,
}
if grad_norm is not None:
+1 -59
View File
@@ -4,7 +4,6 @@ import pickle
import shutil
import time
from collections import defaultdict
from collections.abc import Iterable
from datetime import timedelta
from pathlib import Path
from typing import Any
@@ -16,8 +15,7 @@ from rich import print as rich_print
from rich.console import Console
from rich.table import Table
from rich.text import Text
from torch import Tensor, nn
from torch.distributed.tensor import DTensor
from torch import Tensor
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.trainer.world import get_world
@@ -55,62 +53,6 @@ class GarbageCollection:
get_logger().info(f"[GC] collection took {time.monotonic() - begin:.2f}s")
def _to_local_tensor(tensor: Tensor | DTensor) -> Tensor:
if isinstance(tensor, DTensor):
return tensor.to_local()
return tensor
def count_zero_gradient_elements(parameters: Iterable[nn.Parameter]) -> tuple[Tensor, Tensor]:
"""Count zero-gradient parameter elements on the local distributed shards.
Parameters that require gradients but did not receive one in the current step
are counted as fully zero. This makes inactive MoE experts visible in the
metric instead of silently dropping them from the count.
"""
device = torch.device("cuda", torch.cuda.current_device()) if torch.cuda.is_available() else torch.device("cpu")
num_zeros = torch.zeros((), dtype=torch.long, device=device)
num_tracked = torch.zeros((), dtype=torch.long, device=device)
for param in parameters:
if not param.requires_grad:
continue
local_param = _to_local_tensor(param.detach())
if local_param.numel() == 0:
continue
if local_param.device != num_zeros.device:
num_zeros = num_zeros.to(local_param.device)
num_tracked = num_tracked.to(local_param.device)
local_numel = torch.tensor(local_param.numel(), dtype=torch.long, device=local_param.device)
num_tracked += local_numel
if param.grad is None:
num_zeros += local_numel
continue
local_grad = _to_local_tensor(param.grad.detach())
if local_grad.numel() != local_param.numel():
raise ValueError("Local gradient shape does not match the local parameter shape")
num_zeros += local_numel - torch.count_nonzero(local_grad)
return num_zeros, num_tracked
def get_zero_gradient_ratio(parameters: Iterable[nn.Parameter], dp_replicate: int = 1) -> float:
num_zero_grad, num_grad_elements = count_zero_gradient_elements(parameters)
dist.all_reduce(num_zero_grad, op=dist.ReduceOp.SUM)
dist.all_reduce(num_grad_elements, op=dist.ReduceOp.SUM)
if dp_replicate > 1:
num_zero_grad = torch.div(num_zero_grad, dp_replicate, rounding_mode="floor")
num_grad_elements = torch.div(num_grad_elements, dp_replicate, rounding_mode="floor")
return (num_zero_grad.float() / num_grad_elements.clamp_min(1).float()).item()
def get_ckpt_disk_metrics(output_dir: Path) -> dict[str, float]:
"""
Disk usage metrics for the checkpoint directory (<output_dir>/checkpoints).
+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
-7
View File
@@ -103,11 +103,6 @@ class MetricsServer(HealthServer):
"trainer_mismatch_kl", "KL divergence between trainer and inference model", registry=self._registry
)
self._kl_ent_ratio = Gauge("trainer_kl_ent_ratio", "Ratio of mismatch KL to entropy", registry=self._registry)
self._zero_grad_ratio = Gauge(
"trainer_zero_grad_ratio",
"Fraction of tracked parameter elements with zero gradient",
registry=self._registry,
)
def _make_handler(self) -> type[BaseHTTPRequestHandler]:
"""Create handler with /metrics and /health endpoints."""
@@ -164,7 +159,6 @@ class MetricsServer(HealthServer):
mfu: float = 0.0,
entropy: float = 0.0,
mismatch_kl: float = 0.0,
zero_grad_ratio: float = 0.0,
) -> None:
"""Update metrics after a training step."""
self._step.set(step)
@@ -177,7 +171,6 @@ class MetricsServer(HealthServer):
self._mfu.set(mfu)
self._entropy.set(entropy)
self._mismatch_kl.set(mismatch_kl)
self._zero_grad_ratio.set(zero_grad_ratio)
if entropy > 0:
self._kl_ent_ratio.set(mismatch_kl / entropy)
self._last_step_ts.set(time.time())
+37 -5
View File
@@ -322,11 +322,32 @@ PERFORMANCE_METRICS = [
"time/step",
"time/wait_for_batch",
"time/wait_for_policy",
"inference/agg/throughput",
"inference/agg/running_requests",
"inference/agg/waiting_requests",
"inference/agg/kv_cache_usage_mean",
"inference/agg/prefix_cache_hit_rate",
]
# Inference health panels: each pairs the fleet aggregate (mean/sum) with the cross-engine
# tail that flags a single sick engine - max for pressure metrics, min for health metrics.
# One saturated engine thrashing its KV cache (preempt -> re-prefill -> cache eviction) hides
# inside fleet means; the max/min series is what surfaces it.
INFERENCE_PANELS = [
[
"inference/agg/kv_cache_usage_perc/mean",
"inference/agg/kv_cache_usage_perc/min",
"inference/agg/kv_cache_usage_perc/max",
],
["inference/agg/num_preemptions_total:rate/sum", "inference/agg/num_preemptions_total:rate/max"],
[
"inference/agg/num_requests_running/mean",
"inference/agg/num_requests_running/min",
"inference/agg/num_requests_running/max",
],
[
"inference/agg/num_requests_waiting/mean",
"inference/agg/num_requests_waiting/min",
"inference/agg/num_requests_waiting/max",
],
["inference/agg/prefix_cache_hit_rate/pooled", "inference/agg/prefix_cache_hit_rate/min"],
["inference/agg/generation_tokens_total:rate/sum", "inference/agg/generation_tokens_total:rate/min"],
["inference/agg/prompt_tokens_total:rate/sum", "inference/agg/prompt_tokens_total:rate/max"],
]
# Dense grid: more, smaller panels per row and enough rows that sections don't paginate.
@@ -344,6 +365,16 @@ def line_panels(metrics: Sequence[str], regexes: Sequence[str]) -> list[wr.LineP
]
def inference_section() -> ws.Section:
# Multi-series panels (aggregate + tail), on wall time like all inference/* metrics.
return ws.Section(
name="inference",
is_open=True,
panels=[wr.LinePlot(x="RelativeTime(Wall)", y=list(series)) for series in INFERENCE_PANELS],
layout_settings=ws.SectionLayoutSettings(columns=COLUMNS, rows=ROWS),
)
def section(name: str, metrics: Sequence[str] = (), regexes: Sequence[str] = ()) -> ws.Section:
return ws.Section(
name=name,
@@ -393,6 +424,7 @@ def build_sections(train_envs: Sequence[str] = (), eval_envs: Sequence[str] = ()
# Env names unknown (e.g. SFT): one regex section matching any eval env.
sections.append(eval_section("eval", ".*"))
sections.append(section("stability", metrics=STABILITY_METRICS))
sections.append(inference_section())
sections.append(section("performance", metrics=PERFORMANCE_METRICS))
return sections
+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"}}}]},
}
)

Some files were not shown because too many files have changed in this diff Show More